thru-core 0.4.2

Shared implementation for the Thru CLI
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
//! Thru CLI core library — shared implementation for `thru` and `thru-cli` binaries.
//!
//! This crate provides all CLI logic (argument parsing, command dispatch,
//! configuration, crypto helpers, output formatting, etc.).  The two binary
//! crates (`thru-cli` and `thru`) are thin wrappers that call [`run`].

use clap::Parser;
use serde_json::{Value, json};
use std::process;

pub mod cli;
pub mod commands;
pub mod config;
pub mod crypto;
pub mod error;
pub mod feature_gate_account;
pub mod feature_gate_registry;
pub mod output;
pub mod utils;
pub mod version_check;

use cli::{Cli, Commands, FaucetCommands, FaucetWithdrawCommands};
use config::Config;
use error::CliError;

/// Main entry point shared by every binary wrapper.
///
/// Call this from your `#[tokio::main] async fn main()` after initialising
/// the tracing subscriber.
pub async fn run() -> anyhow::Result<()> {
    // Parse command line arguments
    let cli = Cli::parse();

    // Check for newer version if not in quiet/json mode and running interactively
    if !cli.quiet && !cli.json && version_check::is_interactive() {
        version_check::check_and_notify().await;
    }

    // Load configuration. A default key is resolved lazily by commands that
    // omit an explicit named signer.
    let auth_only = matches!(&cli.command, Commands::Auth { .. });
    let developers_only = auth_only
        || matches!(
            &cli.command,
            Commands::Faucet {
                subcommand: FaucetCommands::Withdraw {
                    subcommand: FaucetWithdrawCommands::Thrusd { .. }
                }
            }
        );
    let mut config = if auth_only {
        Config::default()
    } else {
        Config::load().await?
    };

    // Announce the pending transaction signature before sending, except in
    // machine-readable (`--json`) or `--quiet` modes. This works in scripts,
    // pipes, and logs (non-TTY) since the banner only goes to stderr, never
    // to the `--json` payload on stdout.
    config.announce_pending_signature = !cli.json && !cli.quiet;

    // Apply global network overrides
    if auth_only {
        // Developers auth does not load or select a wallet/RPC identity.
    } else if let Some(ref url) = cli.url {
        config.rpc_base_url = url.clone();
    } else if let Some(ref network_name) = cli.network {
        let name = network_name.to_lowercase();
        let net = config.networks.get(&name).cloned().ok_or_else(|| {
            let available = config.list_network_names();
            CliError::Validation(format!(
                "Network '{}' not found. Available networks: {}",
                name,
                if available.is_empty() {
                    "(none)".to_string()
                } else {
                    available.join(", ")
                }
            ))
        })?;
        config.rpc_base_url = net.url;
        config.auth_token = net.auth_token;
    } else if let Some(default_name) = config.default_network.clone() {
        let default_name = default_name.to_lowercase();
        if let Some(net) = config.networks.get(&default_name).cloned() {
            config.rpc_base_url = net.url;
            config.auth_token = net.auth_token;
        }
    }

    // Skip TLS verification when requested (e.g. self-signed / direct-IP nodes)
    config.insecure = cli.insecure;
    if cli.insecure && !cli.quiet && !developers_only {
        eprintln!(
            "warning: TLS certificate verification disabled (--insecure); \
             the connection is not authenticated and is exposed to man-in-the-middle attacks."
        );
    }

    // Execute the command
    let result: Result<(), CliError> = match cli.command {
        Commands::GetVersion => commands::rpc::get_version(&config, cli.json).await,
        Commands::GetHealth => commands::rpc::get_health(&config, cli.json).await,
        Commands::GetStatus => commands::rpc::get_status(&config, cli.json).await,
        Commands::GetHeight => commands::rpc::get_height(&config, cli.json).await,
        Commands::GetAccountInfo {
            account,
            data_start,
            data_len,
        } => {
            commands::rpc::get_account_info(
                &config,
                account.as_deref(),
                data_start,
                data_len,
                cli.json,
            )
            .await
        }
        Commands::GetBalance { account } => {
            commands::rpc::get_balance(&config, account.as_deref(), cli.json).await
        }
        Commands::GetSlotMetrics { slot, end_slot } => {
            commands::rpc::get_slot_metrics(&config, slot, end_slot, cli.json).await
        }
        Commands::Transfer {
            src,
            dst,
            value,
            build_only,
        } => {
            commands::transfer::handle_transfer_command(
                &config, &src, &dst, value, build_only, cli.json,
            )
            .await
        }
        Commands::Token { subcommand } => {
            commands::token::handle_token_command(&config, subcommand, cli.json).await
        }
        Commands::Auth { subcommand } => {
            commands::developers::handle_auth(subcommand, cli.json).await
        }
        Commands::Faucet { subcommand } => {
            commands::faucet::handle_faucet_command(&config, subcommand, cli.json).await
        }
        Commands::Registrar { subcommand } => {
            commands::name_service::handle_registrar_command(&config, subcommand, cli.json).await
        }
        Commands::NameService { subcommand } => {
            commands::name_service::handle_name_service_command(&config, subcommand, cli.json).await
        }
        Commands::Wthru { subcommand } => {
            commands::wthru::handle_wthru_command(&config, subcommand, cli.json).await
        }
        Commands::Bond { subcommand } => {
            commands::bond::handle_bond_command(&config, subcommand, cli.json).await
        }
        Commands::Validator { subcommand } => {
            commands::consensus_validator::handle_validator_command(&config, subcommand, cli.json)
                .await
        }
        Commands::FeatureGates {
            registry,
            subcommand,
        } => {
            commands::feature_gates::handle_feature_gates_command(
                &config,
                registry.as_deref(),
                subcommand,
                cli.json,
            )
            .await
        }
        Commands::Uploader { subcommand } => {
            commands::uploader::handle_uploader_command(&config, subcommand, cli.json).await
        }
        Commands::Abi { subcommand } => {
            commands::abi::handle_abi_command(&config, subcommand, cli.json).await
        }
        Commands::Keys { subcommand } => {
            commands::keys::handle_keys_command(&config, subcommand, cli.json).await
        }
        Commands::Account { subcommand } => {
            commands::account::handle_account_command(&config, subcommand, cli.json).await
        }
        Commands::Program { subcommand } => {
            commands::program::handle_program_command(&config, subcommand, cli.json).await
        }
        Commands::Txn { subcommand } => {
            commands::txn::handle_txn_command(&config, subcommand, cli.json).await
        }
        Commands::Util { subcommand } => {
            let output_format = if cli.json {
                output::OutputFormat::Json
            } else {
                output::OutputFormat::Text
            };
            commands::util::execute_util_command(subcommand, output_format).map_err(CliError::from)
        }
        Commands::Dev { subcommand } => {
            commands::dev::handle_dev_command(&mut config, subcommand, cli.json).await
        }
        Commands::Network { subcommand } => {
            commands::network::handle_network_command(&config, subcommand, cli.json).await
        }
        Commands::Debug { subcommand } => {
            commands::debug::handle_debug_command(&config, subcommand, cli.json).await
        }
    };

    if let Err(err) = result {
        match (&err, cli.json) {
            (CliError::Reported, _) => {
                // Command already emitted user-facing output; just exit with failure.
            }
            (_, true) => {
                let payload = format_error_json(&err);
                output::print_output(payload, true);
            }
            (_, false) => {
                eprintln!("Error: {}", err);
            }
        }
        process::exit(1);
    }

    Ok(())
}

/// Format a [`CliError`] as a JSON [`Value`] for structured output.
pub fn format_error_json(err: &CliError) -> Value {
    match err {
        CliError::TransactionFailed {
            message,
            execution_result,
            vm_error,
            vm_error_label,
            user_error_code,
            user_error_label,
            signature,
        } => {
            let mut error_obj = json!({
                "type": "transaction_failed",
                "message": message,
                "execution_result": execution_result,
                "execution_result_hex": format!("0x{:X}", execution_result),
                "vm_error": vm_error,
                "vm_error_label": vm_error_label,
                "user_error_code": user_error_code,
                "user_error_code_hex": format!("0x{:X}", user_error_code),
                "user_error_label": user_error_label,
            });

            if !signature.is_empty() {
                if let Some(obj) = error_obj.as_object_mut() {
                    obj.insert("signature".to_string(), json!(signature));
                }
            }

            json!({ "error": error_obj })
        }
        CliError::Developers {
            code,
            message,
            status,
            retry_after,
            signature,
        } => json!({
            "error": {
                "type": "developers", "code": code, "message": message,
                "status": status, "retry_after_seconds": retry_after, "signature": signature,
            }
        }),
        CliError::TransactionSubmission(message) => json!({
            "error": {
                "type": "transaction_submission",
                "message": message,
            }
        }),
        CliError::TransactionVerification(message) => json!({
            "error": {
                "type": "transaction_verification",
                "message": message,
            }
        }),
        CliError::TransactionDetailsUnavailable {
            signature,
            outcome,
            message,
        } => json!({
            "error": {
                "type": "transaction_details_unavailable",
                "message": format!("Transaction observed via stream but details unavailable: {message}"),
                "signature": signature,
                "consensus_status": outcome.consensus_status,
                "execution_result": outcome.execution_result.as_ref().map(|exec| exec.execution_result),
                "vm_error": outcome.execution_result.as_ref().map(|exec| exec.vm_error),
            }
        }),
        CliError::ProgramUpload(message) => json!({
            "error": {
                "type": "program_upload",
                "message": message,
            }
        }),
        CliError::ProgramCleanup(message) => json!({
            "error": {
                "type": "program_cleanup",
                "message": message,
            }
        }),
        CliError::Crypto(message) => json!({
            "error": {
                "type": "crypto",
                "message": message,
            }
        }),
        CliError::Validation(message) => json!({
            "error": {
                "type": "validation",
                "message": message,
            }
        }),
        CliError::NonceManagement(message) => json!({
            "error": {
                "type": "nonce_management",
                "message": message,
            }
        }),
        CliError::ResumeValidation(message) => json!({
            "error": {
                "type": "resume_validation",
                "message": message,
            }
        }),
        CliError::ResumeValidationAccount {
            message,
            account,
            seed,
        } => json!({
            "error": {
                "type": "resume_validation",
                "message": message,
                "account": account,
                "seed": seed,
            }
        }),
        CliError::AccountNotFound(message) => json!({
            "error": {
                "type": "account_not_found",
                "message": message,
            }
        }),
        CliError::HashMismatch(message) => json!({
            "error": {
                "type": "hash_mismatch",
                "message": message,
            }
        }),
        CliError::MetaAccountClosed(message) => json!({
            "error": {
                "type": "meta_account_closed",
                "message": message,
            }
        }),
        CliError::Generic { message } => json!({
            "error": {
                "type": "generic",
                "message": message,
            }
        }),
        CliError::Reported => json!({
            "error": {
                "type": "reported",
                "message": "Error already reported",
            }
        }),
        CliError::Config(config_error) => json!({
            "error": {
                "type": "config",
                "message": config_error.to_string(),
            }
        }),
        CliError::Rpc(message) => json!({
            "error": {
                "type": "rpc",
                "message": message,
            }
        }),
        CliError::Transport(message) => json!({
            "error": {
                "type": "transport",
                "message": message,
            }
        }),
        CliError::Io(io_error) => json!({
            "error": {
                "type": "io",
                "message": io_error.to_string(),
                "kind": format!("{:?}", io_error.kind()),
            }
        }),
    }
}

#[cfg(test)]
mod transaction_outcome_tests {
    use super::*;
    use thru_client::proto::{
        core::v1::TransactionExecutionResult, services::v1::SendAndTrackTxnResponse,
    };

    fn query_failure(execution_result: Option<TransactionExecutionResult>) -> CliError {
        thru_client::ClientError::TransactionDetailsUnavailable {
            signature: "submitted-signature".into(),
            outcome: Box::new(SendAndTrackTxnResponse {
                consensus_status: 4,
                execution_result,
                ..Default::default()
            }),
            source: Box::new(thru_client::ClientError::Rpc("query unavailable".into())),
        }
        .into()
    }

    #[test]
    fn observed_failure_is_reported_as_failed_not_reconcilable() {
        let error = query_failure(Some(TransactionExecutionResult {
            vm_error: -511,
            user_error_code: 17,
            ..Default::default()
        }));
        let json = format_error_json(&error);
        assert_eq!(json["error"]["type"], "transaction_failed");
        assert_eq!(json["error"]["signature"], "submitted-signature");
        assert_eq!(json["error"]["vm_error"], -511);
        assert_eq!(json["error"]["user_error_code"], 17);
        assert!(
            error
                .to_string()
                .contains("TN_RUNTIME_TXN_ERR_NONCE_TOO_LOW")
        );
    }

    #[test]
    fn observed_success_is_not_reported_as_failed_submission() {
        let error = query_failure(Some(TransactionExecutionResult::default()));
        let json = format_error_json(&error);
        assert_eq!(json["error"]["type"], "transaction_details_unavailable");
        assert_eq!(json["error"]["signature"], "submitted-signature");
        assert_eq!(json["error"]["execution_result"], 0);
        assert_eq!(json["error"]["vm_error"], 0);
    }

    #[test]
    fn absent_execution_is_not_reported_as_success() {
        let json = format_error_json(&query_failure(None));
        assert_eq!(json["error"]["type"], "transaction_details_unavailable");
        assert_eq!(json["error"]["signature"], "submitted-signature");
        assert!(json["error"]["execution_result"].is_null());
        assert!(json["error"]["vm_error"].is_null());
    }
}