casper-client 5.0.1

A client library and binary for interacting with the Casper network
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
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! # Casper client library
//!
//! The crate provides functions for interacting with a Casper network.
//!
//! Most of the functions involve sending a JSON-RPC request to a specified node on the chosen
//! network, and providing the RPC response.
//!
//! # Common Parameters
//!
//! Many of the functions have similar parameters.  Descriptions for these common ones follow:
//!
//! * <code>rpc_id: <a href="enum.JsonRpcId.html">JsonRpcId</a></code> - The JSON-RPC identifier,
//!   applied to the request and returned in the response.
//! * <code>node_address: &<a href="https://doc.rust-lang.org/std/primitive.str.html">str</a></code> -
//!   The hostname or IP and port of the server, e.g. `http://127.0.0.1:7777`.
//! * <code>verbosity: <a href="enum.Verbosity.html">Verbosity</a></code> - When `Low`, nothing is
//!   printed to stdout.  For `Medium`, the request and response are printed to `stdout` with long
//!   string fields (e.g. hex-formatted raw Wasm bytes) shortened to a string indicating the char
//!   count of the field.  `High` verbosity is the same as `Medium` except without abbreviation of
//!   long fields.
//! * <code>maybe_block_identifier: <a href="https://doc.rust-lang.org/core/option/enum.Option.html">Option</a><<a href="rpcs/common/enum.BlockIdentifier.html">BlockIdentifier</a>></code> -
//!   The identifier of the [`Block`] to use, either block height or block hash.  If `None`, the
//!   latest `Block` known on the server will be used.

#![doc(
    html_root_url = "https://docs.rs/casper-client/5.0.1",
    html_favicon_url = "https://raw.githubusercontent.com/casper-network/casper-node/master/images/CasperLabs_Logo_Favicon_RGB_50px.png",
    html_logo_url = "https://raw.githubusercontent.com/casper-network/casper-node/master/images/CasperLabs_Logo_Symbol_RGB.png",
    test(attr(forbid(warnings)))
)]
#![warn(
    missing_docs,
    trivial_casts,
    trivial_numeric_casts,
    unused_qualifications
)]
#![allow(clippy::result_large_err)]
pub mod cli;
mod error;
mod json_rpc;
#[cfg(feature = "std-fs-io")]
pub mod keygen;
#[cfg(any(feature = "std-fs-io", test))]
mod output_kind;
pub mod rpcs;
pub mod types;
mod validation;
mod verbosity;
mod verification;
mod verification_types;

extern crate alloc;

#[cfg(any(feature = "std-fs-io", test))]
use std::{
    env::current_dir,
    fs,
    io::{Cursor, Read, Write},
    path::Path,
};

#[cfg(feature = "std-fs-io")]
use serde::Serialize;

#[cfg(any(feature = "std-fs-io", test))]
use casper_types::SecretKey;
#[cfg(doc)]
use casper_types::{account::Account, Block, StoredValue, Transfer};
use casper_types::{
    Deploy, DeployHash, Digest, Key, PublicKey, Transaction, TransactionHash, URef,
};

#[cfg(any(feature = "std-fs-io", test))]
use base64::{engine::general_purpose::STANDARD, Engine};
pub use error::Error;
use json_rpc::JsonRpcCall;
pub use json_rpc::{JsonRpcId, SuccessResponse};
#[cfg(any(feature = "std-fs-io", test))]
pub use output_kind::OutputKind;
use rpcs::{
    common::{BlockIdentifier, GlobalStateIdentifier},
    results::{
        GetAccountResult, GetAddressableEntityResult, GetAuctionInfoResult, GetBalanceResult,
        GetBlockResult, GetBlockTransfersResult, GetChainspecResult, GetDeployResult,
        GetDictionaryItemResult, GetEraInfoResult, GetEraSummaryResult, GetNodeStatusResult,
        GetPeersResult, GetRewardResult, GetStateRootHashResult, GetTransactionResult,
        GetValidatorChangesResult, ListRpcsResult, PutDeployResult, PutTransactionResult,
        QueryBalanceDetailsResult, QueryBalanceResult, QueryGlobalStateResult,
        SpeculativeExecResult, SpeculativeExecTxnResult,
    },
    v2_0_0::{
        get_account::{AccountIdentifier, GetAccountParams, GET_ACCOUNT_METHOD},
        get_auction_info::{GetAuctionInfoParams, GET_AUCTION_INFO_METHOD},
        get_balance::{GetBalanceParams, GET_BALANCE_METHOD},
        get_block::{GetBlockParams, GET_BLOCK_METHOD},
        get_block_transfers::{GetBlockTransfersParams, GET_BLOCK_TRANSFERS_METHOD},
        get_chainspec::GET_CHAINSPEC_METHOD,
        get_deploy::{GetDeployParams, GET_DEPLOY_METHOD},
        get_dictionary_item::{GetDictionaryItemParams, GET_DICTIONARY_ITEM_METHOD},
        get_entity::{EntityIdentifier, GetAddressableEntityParams, GET_ENTITY_METHOD},
        get_era_info::{GetEraInfoParams, GET_ERA_INFO_METHOD},
        get_era_summary::{GetEraSummaryParams, GET_ERA_SUMMARY_METHOD},
        get_node_status::GET_NODE_STATUS_METHOD,
        get_peers::GET_PEERS_METHOD,
        get_reward::{GetRewardParams, GET_REWARD_METHOD},
        get_state_root_hash::{GetStateRootHashParams, GET_STATE_ROOT_HASH_METHOD},
        get_transaction::{GetTransactionParams, GET_TRANSACTION_METHOD},
        get_validator_changes::GET_VALIDATOR_CHANGES_METHOD,
        list_rpcs::LIST_RPCS_METHOD,
        put_deploy::{PutDeployParams, PUT_DEPLOY_METHOD},
        put_transaction::{PutTransactionParams, PUT_TRANSACTION_METHOD},
        query_balance::{PurseIdentifier, QueryBalanceParams, QUERY_BALANCE_METHOD},
        query_balance_details::{QueryBalanceDetailsParams, QUERY_BALANCE_DETAILS_METHOD},
        query_global_state::{QueryGlobalStateParams, QUERY_GLOBAL_STATE_METHOD},
        speculative_exec::{SpeculativeExecParams, SPECULATIVE_EXEC_METHOD},
        speculative_exec_transaction::{SpeculativeExecTxnParams, SPECULATIVE_EXEC_TXN_METHOD},
    },
    DictionaryItemIdentifier, EraIdentifier,
};
pub use validation::ValidateResponseError;
pub use verbosity::Verbosity;
pub use verification::{build_archive, send_verification_request};
#[cfg(any(feature = "std-fs-io", test))]
use verification_types::VerificationDetails;

/// The maximum permissible size in bytes of a Deploy when serialized via `ToBytes`.
///
/// Note: this should be kept in sync with the value of `[deploys.max_deploy_size]` in the
/// production chainspec.
pub const MAX_SERIALIZED_SIZE_OF_DEPLOY: u32 = 1_024 * 1_024;

/// Puts a [`Deploy`] to the network for execution.
///
/// Sends a JSON-RPC `account_put_deploy` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
#[deprecated(since = "3.0.0", note = "use `put_transaction` instead")]
pub async fn put_deploy(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    deploy: Deploy,
) -> Result<SuccessResponse<PutDeployResult>, Error> {
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(PUT_DEPLOY_METHOD, Some(PutDeployParams::new(deploy)))
        .await
}

/// Puts a [`Transaction`] to the network for execution
///
/// Sends a JSON-RPC `account_put_transaction` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn put_transaction(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    transaction: Transaction,
) -> Result<SuccessResponse<PutTransactionResult>, Error> {
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(
            PUT_TRANSACTION_METHOD,
            Some(PutTransactionParams::new(transaction)),
        )
        .await
}

/// Puts a [`Deploy`] to a single node for speculative execution on that node only.
///
/// Sends a JSON-RPC `speculative_exec` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
#[deprecated(since = "3.0.0", note = "use `speculative_exec_txn` instead")]
pub async fn speculative_exec(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    deploy: Deploy,
) -> Result<SuccessResponse<SpeculativeExecResult>, Error> {
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(
            SPECULATIVE_EXEC_METHOD,
            Some(SpeculativeExecParams::new(deploy)),
        )
        .await
}

/// Puts a [`Transaction`] to a single node for speculative execution on that node only.
///
/// Sends a JSON-RPC speculative_exec request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn speculative_exec_txn(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    transaction: Transaction,
) -> Result<SuccessResponse<SpeculativeExecTxnResult>, Error> {
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(
            SPECULATIVE_EXEC_TXN_METHOD,
            Some(SpeculativeExecTxnParams::new(transaction)),
        )
        .await
}

/// Outputs a [`Deploy`] to a file or stdout.
///
/// As a file, the `Deploy` can subsequently be signed by other parties using [`sign_deploy_file`]
/// and then read and sent to the network for execution using [`read_deploy_file`] and
/// [`put_deploy`] respectively.
///
/// `output` specifies the output file and corresponding overwrite behaviour, or if
/// `OutputKind::Stdout`, causes the `Deploy` to be printed `stdout`.
#[deprecated(since = "3.0.0", note = "use `output_transaction` instead")]
#[cfg(any(feature = "std-fs-io", test))]
pub fn output_deploy(output: OutputKind, deploy: &Deploy) -> Result<(), Error> {
    write_deploy(deploy, output.get()?)?;
    output.commit()
}

/// Outputs a [`Transaction`] to a file or stdout.
///
/// As a file, the `Transaction` can subsequently be signed by other parties using [`sign_transaction_file`]
/// and then read and sent to the network for execution using [`read_transaction_file`] and
/// [`put_transaction`] respectively.
///
/// `output` specifies the output file and corresponding overwrite behaviour, or if
/// `OutputKind::Stdout`, causes the `Transaction` to be printed `stdout`.
#[cfg(any(feature = "std-fs-io", test))]
pub fn output_transaction(output: OutputKind, transaction: &Transaction) -> Result<(), Error> {
    write_transaction(transaction, output.get()?)?;
    output.commit()
}

/// Reads a previously-saved [`Deploy`] from a file.
#[deprecated(since = "3.0.0", note = "use `read_transaction_file` instead")]
#[cfg(any(feature = "std-fs-io", test))]
pub fn read_deploy_file<P: AsRef<Path>>(deploy_path: P) -> Result<Deploy, Error> {
    let input = fs::read(deploy_path.as_ref()).map_err(|error| Error::IoError {
        context: format!(
            "unable to read deploy file at '{}'",
            deploy_path.as_ref().display()
        ),
        error,
    })?;
    read_deploy(Cursor::new(input))
}

/// Reads a previously-saved [`Transaction`] from a file.
#[cfg(any(feature = "std-fs-io", test))]
pub fn read_transaction_file<P: AsRef<Path>>(transaction_path: P) -> Result<Transaction, Error> {
    let input = fs::read(transaction_path.as_ref()).map_err(|error| Error::IoError {
        context: format!(
            "unable to read transaction file at '{}'",
            transaction_path.as_ref().display()
        ),
        error,
    })?;
    read_transaction(Cursor::new(input))
}

/// Reads a previously-saved [`Deploy`] from a file, cryptographically signs it, and outputs it
/// to a file or stdout.
///
/// `output` specifies the output file and corresponding overwrite behaviour, or if
/// `OutputKind::Stdout`, causes the `Deploy` to be printed `stdout`.
///
/// The same path can be specified for input and output, and if the operation fails, the original
/// input file will be left unmodified.
#[deprecated(since = "3.0.0", note = "use `sign_transaction_file` instead")]
#[cfg(any(feature = "std-fs-io", test))]
pub fn sign_deploy_file<P: AsRef<Path>>(
    input_path: P,
    secret_key: &SecretKey,
    output: OutputKind,
) -> Result<(), Error> {
    #[allow(deprecated)]
    let mut deploy = read_deploy_file(input_path)?;

    deploy.sign(secret_key);
    deploy.is_valid_size(MAX_SERIALIZED_SIZE_OF_DEPLOY)?;

    write_deploy(&deploy, output.get()?)?;
    output.commit()
}

/// Reads a previously-saved [`Transaction`] from a file, cryptographically signs it, and outputs it to a file or stdout.
///
/// `output` specifies the output file and corresponding overwrite behaviour, or if OutputKind::Stdout,
/// causes the `Transaction` to be printed `stdout`.
#[cfg(any(feature = "std-fs-io", test))]
pub fn sign_transaction_file<P: AsRef<Path>>(
    input_path: P,
    secret_key: &SecretKey,
    output: OutputKind,
) -> Result<(), Error> {
    let mut transaction = read_transaction_file(input_path)?;

    transaction.sign(secret_key);

    write_transaction(&transaction, output.get()?)?;
    output.commit()
}

/// Retrieves a [`Deploy`] and its metadata (i.e. execution results) from the network.
///
/// Sends a JSON-RPC `info_get_deploy` request to the specified node.
///
/// `finalized_approvals` defines whether to return the `Deploy` with its approvals as finalized by
/// consensus of the validators on the network, or as originally received by the specified node.
///
/// For details of the other parameters, see [the module docs](crate#common-parameters).
pub async fn get_deploy(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    deploy_hash: DeployHash,
    finalized_approvals: bool,
) -> Result<SuccessResponse<GetDeployResult>, Error> {
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(
            GET_DEPLOY_METHOD,
            Some(GetDeployParams::new(deploy_hash, finalized_approvals)),
        )
        .await
}

/// Retrieves a [`Transaction`] and its metadata (i.e. execution results) from the network.
///
/// Sends a JSON-RPC `info_get_transaction` request to the specified node.
///
/// `finalized_approvals` defines whether to return the `Transaction` with its approvals as finalized by
/// consensus of the validators on the network, or as originally received by the specified node.
///
/// For details of the other parameters, see [the module docs](crate#common-parameters).
pub async fn get_transaction(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    transaction_hash: TransactionHash,
    finalized_approvals: bool,
) -> Result<SuccessResponse<GetTransactionResult>, Error> {
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(
            GET_TRANSACTION_METHOD,
            Some(GetTransactionParams::new(
                transaction_hash,
                finalized_approvals,
            )),
        )
        .await
}

/// Retrieves a [`Block`] from the network.
///
/// Sends a JSON-RPC `chain_get_block` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_block(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetBlockResult>, Error> {
    let params = maybe_block_identifier.map(GetBlockParams::new);
    let success_response = JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(GET_BLOCK_METHOD, params)
        .await?;
    validation::validate_get_block_result(maybe_block_identifier, &success_response.result)?;
    Ok(success_response)
}

/// Retrieves all [`Transfer`] items for a given [`Block`].
///
/// Sends a JSON-RPC `chain_get_block_transfers` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_block_transfers(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetBlockTransfersResult>, Error> {
    let params = maybe_block_identifier.map(GetBlockTransfersParams::new);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(GET_BLOCK_TRANSFERS_METHOD, params)
        .await
}

/// Retrieves a state root hash at a given [`Block`].
///
/// Sends a JSON-RPC `chain_get_state_root_hash` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_state_root_hash(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetStateRootHashResult>, Error> {
    let params = maybe_block_identifier.map(GetStateRootHashParams::new);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(GET_STATE_ROOT_HASH_METHOD, params)
        .await
}

/// Retrieves era information from the network at a given [`Block`].
///
/// Sends a JSON-RPC `chain_get_era_summary` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_era_summary(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetEraSummaryResult>, Error> {
    let params = maybe_block_identifier.map(GetEraSummaryParams::new);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(GET_ERA_SUMMARY_METHOD, params)
        .await
}

/// Retrieves a [`StoredValue`] from global state at a given [`Block`] or state root hash.
///
/// Sends a JSON-RPC `query_global_state` request to the specified node.
///
/// `key` specifies the key under which the value is stored in global state.
///
/// `path` defines the further path (if any) from `key` to navigate to during the query.  This is
/// only applicable in the case where the value under `key` is an account or contract.  In this
/// case, the first `path` element represents a name in the account/contract's named keys.  If that
/// second `Key` also points to an account or contract, then a second path element can be added to
/// continue the query into that account/contract's named keys.  This can continue up to the
/// server's configured maximum query depth (5 by default).
///
/// For details of the other parameters, see [the module docs](crate#common-parameters).
pub async fn query_global_state(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    global_state_identifier: Option<GlobalStateIdentifier>,
    key: Key,
    path: Vec<String>,
) -> Result<SuccessResponse<QueryGlobalStateResult>, Error> {
    let params = QueryGlobalStateParams::new(global_state_identifier, key, path);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(QUERY_GLOBAL_STATE_METHOD, Some(params))
        .await
}

/// Retrieves a purse's balance from global state at a given [`Block`] or state root hash.
///
/// Sends a JSON-RPC `query_balance` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn query_balance(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    maybe_global_state_identifier: Option<GlobalStateIdentifier>,
    purse_identifier: PurseIdentifier,
) -> Result<SuccessResponse<QueryBalanceResult>, Error> {
    let params = QueryBalanceParams::new(maybe_global_state_identifier, purse_identifier);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(QUERY_BALANCE_METHOD, Some(params))
        .await
}

/// Retrieves a purse's balance from global state at a given [`Block`] or state root hash.
///
/// Sends a JSON-RPC `query_balance_details` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn query_balance_details(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    maybe_global_state_identifier: Option<GlobalStateIdentifier>,
    purse_identifier: PurseIdentifier,
) -> Result<SuccessResponse<QueryBalanceDetailsResult>, Error> {
    let params = QueryBalanceDetailsParams::new(maybe_global_state_identifier, purse_identifier);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(QUERY_BALANCE_DETAILS_METHOD, Some(params))
        .await
}

/// Retrieves a [`StoredValue`] from a dictionary at a given state root hash.
///
/// Sends a JSON-RPC `state_get_dictionary_item` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_dictionary_item(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    state_root_hash: Digest,
    dictionary_item_identifier: DictionaryItemIdentifier,
) -> Result<SuccessResponse<GetDictionaryItemResult>, Error> {
    let params = GetDictionaryItemParams::new(state_root_hash, dictionary_item_identifier);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(GET_DICTIONARY_ITEM_METHOD, Some(params))
        .await
}

/// Retrieves a purse's balance at a given state root hash.
///
/// Sends a JSON-RPC `state_get_balance` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_balance(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    state_root_hash: Digest,
    purse: URef,
) -> Result<SuccessResponse<GetBalanceResult>, Error> {
    let params = GetBalanceParams::new(state_root_hash, purse);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(GET_BALANCE_METHOD, Some(params))
        .await
}

/// Retrieves an [`Account`] at a given [`Block`].
///
/// Sends a JSON-RPC `state_get_account_info` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_account(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    maybe_block_identifier: Option<BlockIdentifier>,
    account_identifier: AccountIdentifier,
) -> Result<SuccessResponse<GetAccountResult>, Error> {
    let params = GetAccountParams::new(account_identifier, maybe_block_identifier);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(GET_ACCOUNT_METHOD, Some(params))
        .await
}

/// Retrieves an [`crate::rpcs::v2_0_0::get_entity::EntityOrAccount`] at a given [`Block`].
///
/// Sends a JSON-RPC `state_get_entity` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_entity(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    maybe_block_identifier: Option<BlockIdentifier>,
    entity_identifier: EntityIdentifier,
) -> Result<SuccessResponse<GetAddressableEntityResult>, Error> {
    let params = GetAddressableEntityParams::new(entity_identifier, maybe_block_identifier);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(GET_ENTITY_METHOD, Some(params))
        .await
}

/// Retrieves a [`GetRewardResult`] at a given [`EraIdentifier`].
///
/// Sends a JSON-RPC `info_get_reward` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_reward(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    maybe_era_identifier: Option<EraIdentifier>,
    validator: PublicKey,
    delegator: Option<PublicKey>,
) -> Result<SuccessResponse<GetRewardResult>, Error> {
    let params = GetRewardParams::new(maybe_era_identifier, validator, delegator);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(GET_REWARD_METHOD, Some(params))
        .await
}

/// Retrieves the bids and validators at a given [`Block`].
///
/// Sends a JSON-RPC `state_get_auction_info` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_auction_info(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetAuctionInfoResult>, Error> {
    let params = maybe_block_identifier.map(GetAuctionInfoParams::new);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(GET_AUCTION_INFO_METHOD, params)
        .await
}

/// Retrieves the status changes of the active validators on the network.
///
/// Sends a JSON-RPC `info_get_validator_changes` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_validator_changes(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
) -> Result<SuccessResponse<GetValidatorChangesResult>, Error> {
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request::<(), _>(GET_VALIDATOR_CHANGES_METHOD, None)
        .await
}

/// Retrieves the IDs and addresses of the specified node's peers.
///
/// Sends a JSON-RPC `info_get_peers` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_peers(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
) -> Result<SuccessResponse<GetPeersResult>, Error> {
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request::<(), _>(GET_PEERS_METHOD, None)
        .await
}

/// Retrieves the status of the specified node.
///
/// Sends a JSON-RPC `info_get_status` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_node_status(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
) -> Result<SuccessResponse<GetNodeStatusResult>, Error> {
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request::<(), _>(GET_NODE_STATUS_METHOD, None)
        .await
}

/// Retrieves the Chainspec of the network.
///
/// Sends a JSON-RPC `info_get_chainspec` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_chainspec(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
) -> Result<SuccessResponse<GetChainspecResult>, Error> {
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request::<(), _>(GET_CHAINSPEC_METHOD, None)
        .await
}

/// Retrieves the interface description (the schema including examples in OpenRPC format) of the
/// JSON-RPC server's API.
///
/// Sends a JSON-RPC `rpc.discover` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn list_rpcs(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
) -> Result<SuccessResponse<ListRpcsResult>, Error> {
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request::<(), _>(LIST_RPCS_METHOD, None)
        .await
}

/// JSON-encode and pretty-print the given value to stdout at the given verbosity level.
///
/// When `verbosity` is `Low`, nothing is printed.  For `Medium`, the value is printed with long
/// string fields shortened to a string indicating the character count of the field.  `High`
/// verbosity is the same as `Medium` except without abbreviation of long fields.
#[cfg(feature = "std-fs-io")]
pub(crate) fn json_pretty_print<T: ?Sized + Serialize>(
    value: &T,
    verbosity: Verbosity,
) -> Result<(), Error> {
    let output = match verbosity {
        Verbosity::Low => return Ok(()),
        Verbosity::Medium => casper_types::json_pretty_print(value),
        Verbosity::High => serde_json::to_string_pretty(value),
    }
    .map_err(|error| Error::FailedToEncodeToJson {
        context: "in json_pretty_print",
        error,
    })?;
    println!("{}", output);
    Ok(())
}

#[cfg(any(feature = "std-fs-io", test))]
fn write_deploy<W: Write>(deploy: &Deploy, mut output: W) -> Result<(), Error> {
    let content =
        serde_json::to_string_pretty(deploy).map_err(|error| Error::FailedToEncodeToJson {
            context: "writing deploy",
            error,
        })?;
    output
        .write_all(content.as_bytes())
        .map_err(|error| Error::IoError {
            context: "unable to write deploy".to_owned(),
            error,
        })
}

#[cfg(any(feature = "std-fs-io", test))]
fn write_transaction<W: Write>(transaction: &Transaction, mut output: W) -> Result<(), Error> {
    let content =
        serde_json::to_string_pretty(transaction).map_err(|error| Error::FailedToEncodeToJson {
            context: "writing transaction",
            error,
        })?;
    output
        .write_all(content.as_bytes())
        .map_err(|error| Error::IoError {
            context: "unable to write transaction".to_owned(),
            error,
        })
}

#[cfg(any(feature = "std-fs-io", test))]
fn read_deploy<R: Read>(input: R) -> Result<Deploy, Error> {
    let deploy: Deploy =
        serde_json::from_reader(input).map_err(|error| Error::FailedToDecodeFromJson {
            context: "reading deploy",
            error,
        })?;
    deploy.is_valid_size(MAX_SERIALIZED_SIZE_OF_DEPLOY)?;
    Ok(deploy)
}

#[cfg(any(feature = "std-fs-io", test))]
fn read_transaction<R: Read>(input: R) -> Result<Transaction, Error> {
    let transaction: Transaction =
        serde_json::from_reader(input).map_err(|error| Error::FailedToDecodeFromJson {
            context: "reading transaction",
            error,
        })?;
    Ok(transaction)
}

/// Retrieves era information from the network at a given switch [`Block`].
///
/// Sends a JSON-RPC `chain_get_era_info_by_switch_block` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).  Note that if the
/// specified block is not a switch block then the response will have no era info.
#[deprecated(
    since = "2.0.0",
    note = "prefer 'get_era_summary' as it doesn't require a switch block"
)]
pub async fn get_era_info(
    rpc_id: JsonRpcId,
    node_address: &str,
    verbosity: Verbosity,
    maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetEraInfoResult>, Error> {
    let params = maybe_block_identifier.map(GetEraInfoParams::new);
    JsonRpcCall::new(rpc_id, node_address, verbosity)?
        .send_request(GET_ERA_INFO_METHOD, params)
        .await
}

/// Verifies the smart contract code against the one deployed at given deploy or transaction hash.
#[cfg(any(feature = "std-fs-io", test))]
pub async fn verify_contract(
    hash_str: &str,
    verification_url_base_path: &str,
    project_path: Option<&str>,
    verbosity: Verbosity,
) -> Result<VerificationDetails, Error> {
    if verbosity == Verbosity::Medium || verbosity == Verbosity::High {
        println!("Hash: {hash_str}");
        println!("Verification service base path: {verification_url_base_path}",);
    }

    let project_path = match project_path {
        Some(path) => Path::new(path).to_path_buf(),
        None => match current_dir() {
            Ok(path) => path,
            Err(error) => {
                eprintln!("Cannot get current directory: {error}");
                return Err(Error::ContractVerificationFailed);
            }
        },
    };

    let archive = match build_archive(&project_path) {
        Ok(archive) => {
            if verbosity == Verbosity::Medium || verbosity == Verbosity::High {
                println!("Created project archive (size: {})", archive.len());
            }
            archive
        }
        Err(error) => {
            eprintln!("Cannot create project archive: {error}");
            return Err(Error::ContractVerificationFailed);
        }
    };

    send_verification_request(
        hash_str,
        verification_url_base_path,
        STANDARD.encode(&archive),
        verbosity,
    )
    .await
}