unc-cli-rs 0.8.0

human-friendly console utility that helps to interact with unc Protocol from command line.
Documentation
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
use std::fmt::Write;

use color_eyre::{
    eyre::{Context, Report},
    owo_colors::OwoColorize,
};
use thiserror::Error;

use unc_primitives::types::{BlockId, BlockReference};

use crate::common::{CallResultExt, JsonRpcClientExt, RpcQueryResponseExt};

mod contract_metadata;

#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = crate::GlobalContext)]
#[interactive_clap(output_context = ContractContext)]
pub struct Contract {
    #[interactive_clap(skip_default_input_arg)]
    /// What is the contract account ID?
    contract_account_id: crate::types::account_id::AccountId,
    #[interactive_clap(named_arg)]
    /// Select network
    network_config: crate::network_view_at_block::NetworkViewAtBlockArgs,
}

impl Contract {
    pub fn input_contract_account_id(
        context: &crate::GlobalContext,
    ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> {
        crate::common::input_non_signer_account_id_from_used_account_list(
            &context.config.credentials_home_dir,
            "What is the contract account ID?",
        )
    }
}

#[derive(Clone)]
pub struct ContractContext(crate::network_view_at_block::ArgsForViewContext);

impl ContractContext {
    pub fn from_previous_context(
        previous_context: crate::GlobalContext,
        scope: &<Contract as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope,
    ) -> color_eyre::eyre::Result<Self> {
        let on_after_getting_block_reference_callback: crate::network_view_at_block::OnAfterGettingBlockReferenceCallback = std::sync::Arc::new({
            let account_id: unc_primitives::types::AccountId = scope.contract_account_id.clone().into();

            move |network_config, block_reference| {
                let view_code_response = network_config
                    .json_rpc_client()
                    .blocking_call(unc_jsonrpc_client::methods::query::RpcQueryRequest {
                        block_reference: block_reference.clone(),
                        request: unc_primitives::views::QueryRequest::ViewCode {
                            account_id: account_id.clone(),
                        },
                    })
                    .wrap_err_with(|| format!("Failed to fetch query ViewCode for <{}> on network <{}>", &account_id, network_config.network_name))?;

                tokio::runtime::Runtime::new()
                    .unwrap()
                    .block_on(display_inspect_contract(&account_id, network_config, view_code_response))
            }
        });
        Ok(Self(crate::network_view_at_block::ArgsForViewContext {
            config: previous_context.config,
            on_after_getting_block_reference_callback,
            interacting_with_account_ids: vec![scope.contract_account_id.clone().into()],
        }))
    }
}

impl From<ContractContext> for crate::network_view_at_block::ArgsForViewContext {
    fn from(item: ContractContext) -> Self {
        item.0
    }
}

async fn display_inspect_contract(
    account_id: &unc_primitives::types::AccountId,
    network_config: &crate::config::NetworkConfig,
    view_code_response: unc_jsonrpc_primitives::types::query::RpcQueryResponse,
) -> crate::CliResult {
    let json_rpc_client = network_config.json_rpc_client();
    let block_reference = BlockReference::from(BlockId::Hash(view_code_response.block_hash));
    let contract_code_view =
        if let unc_jsonrpc_primitives::types::query::QueryResponseKind::ViewCode(result) =
            view_code_response.kind
        {
            result
        } else {
            return Err(color_eyre::Report::msg("Error call result".to_string()));
        };

    let account_view = get_account_view(
        &network_config.network_name,
        &json_rpc_client,
        &block_reference,
        account_id,
    )
    .await?;

    let access_keys = get_access_keys(
        &network_config.network_name,
        &json_rpc_client,
        &block_reference,
        account_id,
    )
    .await?;

    let mut table = prettytable::Table::new();
    table.set_format(*prettytable::format::consts::FORMAT_NO_COLSEP);

    table.add_row(prettytable::row![
        Fg->account_id,
        format!("At block #{}\n({})", view_code_response.block_height, view_code_response.block_hash)
    ]);

    let contract_status = if account_view.code_hash == unc_primitives::hash::CryptoHash::default()
    {
        "No contract code".to_string()
    } else {
        hex::encode(account_view.code_hash.as_ref())
    };
    table.add_row(prettytable::row![
        Fy->"SHA-256 checksum hex",
        contract_status
    ]);

    table.add_row(prettytable::row![
        Fy->"Storage used",
        format!("{} ({} Wasm + {} data)",
            bytesize::ByteSize(account_view.storage_usage),
            bytesize::ByteSize(u64::try_from(contract_code_view.code.len())?),
            bytesize::ByteSize(
                account_view.storage_usage
                    .checked_sub(u64::try_from(contract_code_view.code.len())?)
                    .expect("Unexpected error")
            )
        )
    ]);

    let access_keys_summary = if access_keys.is_empty() {
        "Contract is locked (no access keys)".to_string()
    } else {
        let full_access_keys_count = access_keys
            .iter()
            .filter(|access_key| {
                matches!(
                    access_key.access_key.permission,
                    unc_primitives::views::AccessKeyPermissionView::FullAccess
                )
            })
            .count();
        format!(
            "{} full access keys and {} function-call-only access keys",
            full_access_keys_count,
            access_keys.len() - full_access_keys_count
        )
    };
    table.add_row(prettytable::row![
        Fy->"Access keys",
        access_keys_summary
    ]);

    match get_contract_source_metadata(&json_rpc_client, &block_reference, account_id).await {
        Ok(contract_source_metadata) => {
            table.add_row(prettytable::row![
                Fy->"Contract version",
                contract_source_metadata.version.unwrap_or_default()
            ]);
            table.add_row(prettytable::row![
                Fy->"Contract link",
                contract_source_metadata.link.unwrap_or_default()
            ]);
            table.add_row(prettytable::row![
                Fy->"Supported standards",
                contract_source_metadata.standards
                    .iter()
                    .fold(String::new(), |mut output, standard| {
                        let _ = writeln!(output, "{} ({})", standard.standard, standard.version);
                        output
                    })
            ]);
        }
        Err(err) => {
            table.add_row(prettytable::row![
                "",
                textwrap::fill(
                    &format!(
                        "{}: {}",
                        match &err {
                            FetchContractSourceMetadataError::ContractSourceMetadataNotSupported => "Info",
                            FetchContractSourceMetadataError::ContractSourceMetadataUnknownFormat(_) |
                            FetchContractSourceMetadataError::RpcError(_) => "Warning",
                        },
                        err
                    ),
                    80
                )
            ]);

            table.add_row(prettytable::row![
                Fy->"Contract version",
                "N/A"
            ]);
            table.add_row(prettytable::row![
                Fy->"Contract link",
                "N/A"
            ]);
            table.add_row(prettytable::row![
                Fy->"Supported standards",
                "N/A"
            ]);
        }
    }

    match get_contract_abi(&json_rpc_client, &block_reference, account_id).await {
        Ok(abi_root) => {
            table.add_row(prettytable::row![
                Fy->"unc ABI version",
                abi_root.schema_version
            ]);
            table.printstd();

            println!(
                "\n {} (hint: you can download full JSON Schema using `download-abi` command)",
                "Functions:".yellow()
            );
            for function in abi_root.body.functions {
                let mut table_func = prettytable::Table::new();
                table_func.set_format(*prettytable::format::consts::FORMAT_CLEAN);
                table_func.add_empty_row();

                table_func.add_row(prettytable::row![format!(
                    "{} ({}) {}\n{}",
                    format!(
                        "fn {}({}) -> {}",
                        function.name.green(),
                        "...".yellow(),
                        "...".blue()
                    ),
                    match function.kind {
                        unc_abi::AbiFunctionKind::Call =>
                            "read-write function - transcation required",
                        unc_abi::AbiFunctionKind::View => "read-only function",
                    },
                    function
                        .modifiers
                        .iter()
                        .fold(String::new(), |mut output, modifier| {
                            let _ = write!(
                                output,
                                "{} ",
                                match modifier {
                                    unc_abi::AbiFunctionModifier::Init => "init".red(),
                                    unc_abi::AbiFunctionModifier::Payable => "payable".red(),
                                    unc_abi::AbiFunctionModifier::Private => "private".red(),
                                }
                            );
                            output
                        }),
                    function.doc.unwrap_or_default()
                )]);
                table_func.printstd();

                let mut table_args = prettytable::Table::new();
                table_args.set_format(*prettytable::format::consts::FORMAT_CLEAN);
                table_args.get_format().padding(1, 0);

                table_args.add_row(prettytable::row![
                    "...".yellow(),
                    Fy->"Arguments (JSON Schema):",
                ]);
                table_args.add_row(prettytable::row![
                    "   ",
                    if function.params.is_empty() {
                        "No arguments needed".to_string()
                    } else {
                        serde_json::to_string_pretty(&function.params).unwrap_or_default()
                    }
                ]);
                table_args.add_row(prettytable::row![
                    "...".blue(),
                    Fb->"Return Value (JSON Schema):",
                ]);
                table_args.add_row(prettytable::row![
                    "   ",
                    if let Some(result) = function.result {
                        serde_json::to_string_pretty(&result).unwrap_or_default()
                    } else {
                        "No return value".to_string()
                    }
                ]);
                table_args.printstd();
            }
        }
        Err(err) => {
            table.add_row(prettytable::row![
                Fy->"unc ABI version",
                textwrap::fill(
                    &format!(
                        "{}: {}",
                        match &err {
                            FetchAbiError::AbiNotSupported => "Info",
                            FetchAbiError::AbiUnknownFormat(_) | FetchAbiError::RpcError(_) => "Warning",
                        },
                        err
                    ),
                    80
                )
            ]);
            table.printstd();
            println!(
                "\n {} (unc ABI is not available, so only function names are extracted)\n",
                "Functions:".yellow()
            );

            let parser = wasmparser::Parser::new(0);
            for payload in parser.parse_all(&contract_code_view.code) {
                if let wasmparser::Payload::ExportSection(export_section) =
                    payload.wrap_err_with(|| {
                        format!(
                            "Could not parse WebAssembly binary of the contract <{account_id}>."
                        )
                    })?
                {
                    for export in export_section {
                        let export = export
                            .wrap_err_with(|| format!("Could not parse WebAssembly export section of the contract <{account_id}>."))?;
                        if let wasmparser::ExternalKind::Func = export.kind {
                            println!(
                                " fn {}({}) -> {}\n",
                                export.name.green(),
                                "...".yellow(),
                                "...".blue()
                            );
                        }
                    }
                }
            }
        }
    }

    Ok(())
}

async fn get_account_view(
    network_name: &str,
    json_rpc_client: &unc_jsonrpc_client::JsonRpcClient,
    block_reference: &BlockReference,
    account_id: &unc_primitives::types::AccountId,
) -> color_eyre::eyre::Result<unc_primitives::views::AccountView> {
    for _ in 0..5 {
        let account_view_response = json_rpc_client
            .call(unc_jsonrpc_client::methods::query::RpcQueryRequest {
                block_reference: block_reference.clone(),
                request: unc_primitives::views::QueryRequest::ViewAccount {
                    account_id: account_id.clone(),
                },
            })
            .await;

        if let Err(unc_jsonrpc_client::errors::JsonRpcError::TransportError(_)) =
            &account_view_response
        {
            eprintln!("Transport error.\nPlease wait. The next try to send this query is happening right now ...");
            std::thread::sleep(std::time::Duration::from_millis(100))
        } else {
            return account_view_response
                .wrap_err_with(|| {
                    format!(
                        "Failed to fetch query ViewAccount for contract <{account_id}> on network <{network_name}>" 
                    )
                })?
                .account_view();
        }
    }
    color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!(format!(
        "Transport error. Failed to fetch query ViewAccount for contract <{account_id}> on network <{network_name}>"
    )))
}

async fn get_access_keys(
    network_name: &str,
    json_rpc_client: &unc_jsonrpc_client::JsonRpcClient,
    block_reference: &BlockReference,
    account_id: &unc_primitives::types::AccountId,
) -> color_eyre::eyre::Result<Vec<unc_primitives::views::AccessKeyInfoView>> {
    for _ in 0..5 {
        let access_keys_response = json_rpc_client
            .call(unc_jsonrpc_client::methods::query::RpcQueryRequest {
                block_reference: block_reference.clone(),
                request: unc_primitives::views::QueryRequest::ViewAccessKeyList {
                    account_id: account_id.clone(),
                },
            })
            .await;

        if let Err(unc_jsonrpc_client::errors::JsonRpcError::TransportError(_)) =
            &access_keys_response
        {
            eprintln!("Transport error.\nPlease wait. The next try to send this query is happening right now ...");
            std::thread::sleep(std::time::Duration::from_millis(100))
        } else {
            return Ok(access_keys_response
                .wrap_err_with(|| {
                    format!(
                        "Failed to fetch ViewAccessKeyList for contract <{account_id}> on network <{network_name}>"
                    )
                })?
                .access_key_list_view()?
                .keys);
        }
    }
    color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!(format!(
        "Transport error. Failed to fetch query ViewAccessKeyList for contract <{account_id}> on network <{network_name}>"
    )))
}

#[derive(Error, Debug)]
pub enum FetchContractSourceMetadataError {
    #[error("Contract Source Metadata (https://nomicon.io/Standards/SourceMetadata) is not supported by the contract, so there is no way to get detailed information.")]
    ContractSourceMetadataNotSupported,
    #[error("'contract_source_metadata' function call failed due to RPC error, so there is no way to get Contract Source Metadata. See more details about the error:\n\n{0}")]
    RpcError(
        unc_jsonrpc_client::errors::JsonRpcError<
            unc_jsonrpc_primitives::types::query::RpcQueryError,
        >,
    ),
    #[error("The contract source metadata format is unknown (https://nomicon.io/Standards/SourceMetadata), so there is no way to get detailed information. See more details about the error:\n\n{0}")]
    ContractSourceMetadataUnknownFormat(Report),
}

async fn get_contract_source_metadata(
    json_rpc_client: &unc_jsonrpc_client::JsonRpcClient,
    block_reference: &BlockReference,
    account_id: &unc_primitives::types::AccountId,
) -> Result<self::contract_metadata::ContractSourceMetadata, FetchContractSourceMetadataError> {
    let mut retries_left = (0..5).rev();
    loop {
        let contract_source_metadata_response = json_rpc_client
            .call(unc_jsonrpc_client::methods::query::RpcQueryRequest {
                block_reference: block_reference.clone(),
                request: unc_primitives::views::QueryRequest::CallFunction {
                    account_id: account_id.clone(),
                    method_name: "contract_source_metadata".to_owned(),
                    args: unc_primitives::types::FunctionArgs::from(vec![]),
                },
            })
            .await;

        match contract_source_metadata_response {
            Err(unc_jsonrpc_client::errors::JsonRpcError::TransportError(_))
                if retries_left.next().is_some() =>
            {
                eprintln!("Transport error.\nPlease wait. The next try to send this query is happening right now ...");
            }
            Err(unc_jsonrpc_client::errors::JsonRpcError::ServerError(
                unc_jsonrpc_client::errors::JsonRpcServerError::HandlerError(
                    unc_jsonrpc_primitives::types::query::RpcQueryError::ContractExecutionError {
                        vm_error,
                        ..
                    },
                ),
            )) if vm_error.contains("MethodNotFound") => {
                return Err(FetchContractSourceMetadataError::ContractSourceMetadataNotSupported);
            }
            Err(err) => {
                return Err(FetchContractSourceMetadataError::RpcError(err));
            }
            Ok(contract_source_metadata_response) => {
                return contract_source_metadata_response
                    .call_result()
                    .map_err(FetchContractSourceMetadataError::ContractSourceMetadataUnknownFormat)?
                    .parse_result_from_json::<self::contract_metadata::ContractSourceMetadata>()
                    .wrap_err("Failed to parse contract source metadata")
                    .map_err(
                        FetchContractSourceMetadataError::ContractSourceMetadataUnknownFormat,
                    );
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
}

#[derive(Error, Debug)]
pub enum FetchAbiError {
    #[error("Contact does not support unc ABI (https://github.com/unc/abi), so there is no way to get details about the function argument and return values.")]
    AbiNotSupported,
    #[error("The contact has unknown unc ABI format (https://github.com/unc/abi), so there is no way to get details about the function argument and return values. See more details about the error:\n\n{0}")]
    AbiUnknownFormat(Report),
    #[error("'__contract_abi' function call failed due to RPC error, so there is no way to get details about the function argument and return values. See more details about the error:\n\n{0}")]
    RpcError(
        unc_jsonrpc_client::errors::JsonRpcError<
            unc_jsonrpc_primitives::types::query::RpcQueryError,
        >,
    ),
}

pub async fn get_contract_abi(
    json_rpc_client: &unc_jsonrpc_client::JsonRpcClient,
    block_reference: &BlockReference,
    account_id: &unc_primitives::types::AccountId,
) -> Result<unc_abi::AbiRoot, FetchAbiError> {
    let mut retries_left = (0..5).rev();
    loop {
        let contract_abi_response = json_rpc_client
            .call(unc_jsonrpc_client::methods::query::RpcQueryRequest {
                block_reference: block_reference.clone(),
                request: unc_primitives::views::QueryRequest::CallFunction {
                    account_id: account_id.clone(),
                    method_name: "__contract_abi".to_owned(),
                    args: unc_primitives::types::FunctionArgs::from(vec![]),
                },
            })
            .await;

        match contract_abi_response {
            Err(unc_jsonrpc_client::errors::JsonRpcError::TransportError(_))
                if retries_left.next().is_some() =>
            {
                eprintln!("Transport error.\nPlease wait. The next try to send this query is happening right now ...");
            }
            Err(unc_jsonrpc_client::errors::JsonRpcError::ServerError(
                unc_jsonrpc_client::errors::JsonRpcServerError::HandlerError(
                    unc_jsonrpc_primitives::types::query::RpcQueryError::ContractExecutionError {
                        vm_error,
                        ..
                    },
                ),
            )) if vm_error.contains("MethodNotFound") => {
                return Err(FetchAbiError::AbiNotSupported);
            }
            Err(err) => {
                return Err(FetchAbiError::RpcError(err));
            }
            Ok(contract_abi_response) => {
                return serde_json::from_slice::<unc_abi::AbiRoot>(
                    &zstd::decode_all(
                        contract_abi_response
                            .call_result()
                            .map_err(FetchAbiError::AbiUnknownFormat)?
                            .result
                            .as_slice(),
                    )
                    .wrap_err("Failed to 'zstd::decode_all' unc ABI")
                    .map_err(FetchAbiError::AbiUnknownFormat)?,
                )
                .wrap_err("Failed to parse unc ABI schema")
                .map_err(FetchAbiError::AbiUnknownFormat);
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
}