ant-cli 0.5.2

CLI client for the Autonomi network
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
// Copyright 2024 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

mod analyze;
#[cfg(feature = "developer")]
mod developer;
mod file;
mod pointer;
mod register;
mod scratchpad;
mod vault;
mod wallet;

use crate::actions::NetworkContext;
use crate::args::max_fee_per_gas::MaxFeePerGasParam;
use crate::opt::{NetworkId, Opt};
use autonomi::networking::Quorum;
use clap::{Args, CommandFactory as _, Subcommand, error::ErrorKind};
use color_eyre::Result;
use pointer::TargetDataType;
use pointer::parse_target_data_type;
use std::num::NonZeroUsize;
use std::path::PathBuf;

/// Shared payment-related flags for file cost and upload commands
#[derive(Args, Debug, Clone)]
pub struct PaymentFlags {
    /// Use standard payment mode instead of single-node payment (default).
    /// Standard mode pays 3 nodes individually, which costs more in gas fees.
    /// Single-node payment (default) pays only one node with 3x that amount, saving gas fees.
    /// Note: This only applies to regular payments, not merkle payments.
    #[arg(long, conflicts_with = "merkle")]
    pub disable_single_node_payment: bool,
    /// Force merkle tree payments regardless of chunk count.
    /// By default, merkle payments are used for >= 64 chunks.
    /// Mutually exclusive with --regular and --disable-single-node-payment.
    #[arg(long, conflicts_with_all = ["regular", "disable_single_node_payment"])]
    pub merkle: bool,
    /// Force regular per-batch payments regardless of chunk count.
    /// By default, regular payments are used for < 64 chunks. Mutually exclusive with --merkle.
    #[arg(long, conflicts_with = "merkle")]
    pub regular: bool,
}

#[derive(Subcommand, Debug)]
pub enum SubCmd {
    /// Operations related to file handling.
    File {
        #[command(subcommand)]
        command: FileCmd,
    },

    /// Operations related to register management.
    Register {
        #[command(subcommand)]
        command: RegisterCmd,
    },

    /// Operations related to vault management.
    Vault {
        #[command(subcommand)]
        command: VaultCmd,
    },

    /// Operations related to scratchpad management.
    Scratchpad {
        #[command(subcommand)]
        command: ScratchpadCmd,
    },

    /// Operations related to pointer management.
    Pointer {
        #[command(subcommand)]
        command: PointerCmd,
    },

    /// Operations related to wallet management.
    Wallet {
        #[command(subcommand)]
        command: WalletCmd,
    },

    /// Operations related to data analysis.
    #[command(alias = "analyse")]
    Analyze {
        /// The address of the data to analyse.
        addr: String,
        /// Show closest nodes to this address instead of analyzing it.
        #[arg(long)]
        closest_nodes: bool,
        /// Show all holders of the record at this address.
        #[arg(long)]
        holders: bool,
        /// Check health of closest nodes by requesting storage proofs for the target chunk address.
        #[arg(long)]
        nodes_health: bool,
        /// Repair records with insufficient copies in closest group.
        /// When analyzing with --closest-nodes, automatically re-upload records
        /// that have less than 3 holders among the closest 7 nodes.
        #[arg(long)]
        repair: bool,
        /// Filter network scan to only target addresses starting with this hex character (0-9, a-f).
        /// Only applies when using --nodes-health with a number of rounds.
        #[arg(long)]
        addr_range: Option<char>,
        /// Recursively analyze all discovered addresses (chunks, pointers, etc.)
        #[arg(short, long)]
        recursive: bool,
        /// Verbose output. Detailed description of the analysis.
        #[arg(short, long)]
        verbose: bool,
        /// Output results as JSON to a file. Append-only writing.
        /// If path is a file, appends to that file.
        /// If path is a directory, enables file rotations (50MB max per file, 10 files max).
        #[arg(long)]
        json: Option<PathBuf>,
    },

    /// Developer and analytics tools for network diagnostics.
    /// Requires the `developer` feature to be enabled on both client and node.
    #[cfg(feature = "developer")]
    Developer {
        #[command(subcommand)]
        command: DeveloperCmd,
    },
}

#[derive(Subcommand, Debug)]
pub enum FileCmd {
    /// Estimate cost to upload a file.
    Cost {
        /// The file to estimate cost for.
        file: String,
        /// Estimate cost for public upload. Everyone can see public data on the Network.
        /// Default is private (data encrypted, datamaps kept local).
        #[arg(short, long)]
        public: bool,
        /// Exclude archive metadata from cost estimate.
        /// By default, archive cost is included for directory uploads.
        #[arg(long)]
        no_archive: bool,
        #[command(flatten)]
        payment_flags: PaymentFlags,
    },

    /// Upload a file and pay for it. Data on the Network is private by default.
    Upload {
        /// The file to upload.
        file: String,
        /// Upload the file as public. Everyone can see public data on the Network.
        #[arg(short, long)]
        public: bool,
        /// Skip creating an archive after uploading a directory.
        /// When uploading a directory, files are normally grouped into an archive for easier management.
        /// This flag uploads the files individually without creating the archive metadata.
        /// Note: This option only affects directory uploads - single file uploads never create archives.
        #[arg(long)]
        no_archive: bool,
        /// Retry failed uploads automatically after 1 minute pause.
        /// This will persistently retry any failed chunks until all data is successfully uploaded.
        #[arg(long)]
        #[clap(default_value = "0")]
        retry_failed: u64,
        #[command(flatten)]
        payment_flags: PaymentFlags,
        #[command(flatten)]
        transaction_opt: TransactionOpt,
    },

    /// Download a file from the given address.
    Download {
        /// The address of the file to download.
        addr: String,
        /// The destination file path.
        dest_file: String,
        /// Experimental: Optionally specify the quorum for the download (makes sure that we have n copies for each chunk).
        ///
        /// Possible values are: "one", "majority", "all", n (where n is a number greater than 0)
        #[arg(short, long, value_parser = parse_quorum)]
        quorum: Option<Quorum>,
        /// Experimental: Optionally specify the number of retries for the download.
        #[arg(short, long)]
        retries: Option<usize>,
        /// By default, chunks will be cached to enable resuming downloads.
        /// Set this flag to disable the cache.
        #[arg(long)]
        disable_cache: bool,
        /// Custom cache directory for chunk caching.
        /// If not specified, uses the default Autonomi client data directory.
        /// This option only applies when cache is enabled (default).
        #[arg(long, conflicts_with = "disable_cache")]
        cache_dir: Option<PathBuf>,
    },

    /// List previous uploads
    List {
        /// List files in archives. Requires network connection.
        #[arg(short, long)]
        verbose: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum RegisterCmd {
    /// Generate a new register key.
    GenerateKey {
        /// Overwrite existing key if it exists
        /// Warning: overwriting the existing key will result in loss of access to any existing registers created using that key
        #[arg(short, long)]
        overwrite: bool,
    },

    /// Estimate cost to register a name.
    Cost {
        /// The name to register.
        name: String,
    },

    /// Create a new register with the given name and value.
    /// Note that anyone with the register address can read its value.
    Create {
        /// The name of the register.
        name: String,
        /// The value to store in the register.
        value: String,
        /// Treat the value as a hex string and convert it to binary before storing
        #[arg(long)]
        hex: bool,
        #[command(flatten)]
        transaction_opt: TransactionOpt,
    },

    /// Edit an existing register.
    /// Note that anyone with the register address can read its value.
    Edit {
        /// Use the name of the register instead of the address
        /// Note that only the owner of the register can use this shorthand as the address can be generated from the name and register key.
        #[arg(short, long)]
        name: bool,
        /// The address of the register
        /// With the name option on the address will be used as a name
        address: String,
        /// The new value to store in the register.
        value: String,
        /// Treat the value as a hex string and convert it to binary before storing
        #[arg(long)]
        hex: bool,
        #[command(flatten)]
        transaction_opt: TransactionOpt,
    },

    /// Get the value of a register.
    Get {
        /// Use the name of the register instead of the address
        /// Note that only the owner of the register can use this shorthand as the address can be generated from the name and register key.
        #[arg(short, long)]
        name: bool,
        /// The address of the register
        /// With the name option on the address will be used as a name
        address: String,
        /// Display the value as a hex string instead of raw bytes
        #[arg(long)]
        hex: bool,
    },

    /// Show the history of values for a register.
    History {
        /// Use the name of the register instead of the address
        /// Note that only the owner of the register can use this shorthand as the address can be generated from the name and register key.
        #[arg(short, long)]
        name: bool,
        /// The address of the register
        /// With the name option on the address will be used as a name
        address: String,
        /// Display the values as hex strings instead of raw bytes
        #[arg(long)]
        hex: bool,
    },

    /// List previous registers
    List,
}

#[derive(Subcommand, Debug)]
pub enum VaultCmd {
    /// Estimate cost to create a vault.
    Cost {
        /// Expected max_size of a vault, only for cost estimation.
        #[clap(default_value = "3145728")]
        expected_max_size: u64,
    },

    /// Create a vault at a deterministic address based on your `SECRET_KEY`.
    /// Pushing an encrypted backup of your local user data to the network
    Create {
        #[command(flatten)]
        transaction_opt: TransactionOpt,
    },

    /// Load an existing vault from the network.
    /// Use this when loading your user data to a new device.
    /// You need to have your original `SECRET_KEY` to load the vault.
    Load,

    /// Sync vault with the network, safeguarding local user data.
    /// Loads existing user data from the network and merges it with your local user data.
    /// Pushes your local user data to the network.
    Sync {
        /// Force push your local user data to the network.
        /// This will overwrite any existing data in your vault.
        #[arg(short, long)]
        force: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum ScratchpadCmd {
    /// Generate a new general scratchpad key from which all your scratchpad keys can be derived (using their names).
    GenerateKey {
        /// Overwrite existing key if it exists
        /// Warning: overwriting the existing key will result in loss of access to any existing scratchpads
        #[arg(short, long)]
        overwrite: bool,
    },

    /// Estimate cost to create a scratchpad.
    Cost {
        /// The name of the scratchpad.
        name: String,
    },

    /// Create a new scratchpad.
    Create {
        /// The name of the scratchpad.
        name: String,
        /// The data to store in the scratchpad (Up to 4MB)
        data: String,
        #[command(flatten)]
        transaction_opt: TransactionOpt,
    },

    /// Share a scratchpad secret key with someone else.
    /// Sharing this key means that the other party will have permanent read and write access to the scratchpad.
    Share {
        /// The name of the scratchpad.
        name: String,
    },

    /// Get the contents of an existing scratchpad from the network.
    Get {
        /// The name of the scratchpad.
        name: String,
        /// Indicate that this is an external scratchpad secret key.
        /// (Use this when interacting with a scratchpad shared with you by someone else)
        #[arg(short, long)]
        secret_key: bool,
        /// Display the data as a hex string instead of raw bytes
        #[arg(long)]
        hex: bool,
    },

    /// Edit the contents of an existing scratchpad.
    Edit {
        /// The name of the scratchpad.
        name: String,
        /// Indicate that this is an external scratchpad secret key.
        /// (Use this when interacting with a scratchpad shared with you by someone else)
        #[arg(short, long)]
        secret_key: bool,
        /// The new data to store in the scratchpad (Up to 4MB)
        data: String,
    },

    /// List owned scratchpads
    List {
        /// Verbose output. Detailed description of the scratchpads.
        #[arg(short, long)]
        verbose: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum PointerCmd {
    /// Generate a new general pointer key from which all your pointer keys can be derived (using their names).
    GenerateKey {
        /// Overwrite existing key if it exists
        /// Warning: overwriting the existing key will result in loss of access to any existing pointers
        #[arg(short, long)]
        overwrite: bool,
    },

    /// Estimate cost to create a pointer.
    Cost {
        /// The name of the pointer.
        name: String,
    },

    /// Create a new pointer.
    Create {
        /// The name of the pointer.
        name: String,
        /// The target address to point to
        target: String,
        /// The data type of the target (valid values: graph, scratchpad, pointer, chunk, auto)
        /// If not specified (or 'auto'), the type will be automatically detected by fetching the data from the network
        #[arg(value_parser = parse_target_data_type, default_value = "auto", long, short)]
        target_data_type: TargetDataType,
        #[command(flatten)]
        transaction_opt: TransactionOpt,
    },

    /// Share a pointer secret key with someone else.
    /// Sharing this key means that the other party will have permanent read and write access to the pointer.
    Share {
        /// The name of the pointer.
        name: String,
    },

    /// Get the target of an existing pointer from the network.
    Get {
        /// The name of the pointer.
        name: String,
        /// Indicate that this is an external pointer secret key.
        /// (Use this when interacting with a pointer shared with you by someone else)
        #[arg(short, long)]
        secret_key: bool,
    },

    /// Edit the target of an existing pointer.
    Edit {
        /// The name of the pointer.
        name: String,
        /// The new target address to point to
        target: String,
        /// The data type of the target (valid values: graph, scratchpad, pointer, chunk, auto)
        /// If not specified (or 'auto'), the type will be automatically detected by fetching the data from the network
        #[arg(value_parser = parse_target_data_type, default_value = "auto", long, short)]
        target_data_type: TargetDataType,
        /// Indicate that this is an external pointer secret key.
        /// (Use this when interacting with a pointer shared with you by someone else)
        #[arg(short, long)]
        secret_key: bool,
    },

    /// List owned pointers
    List {
        /// Verbose output. Detailed description of the pointers.
        #[arg(short, long)]
        verbose: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum WalletCmd {
    /// Create a wallet.
    Create {
        /// Optional flag to not add a password.
        #[clap(long, action)]
        no_password: bool,
        /// Optional password to encrypt the wallet with.
        #[clap(long, short)]
        password: Option<String>,
    },

    /// Import an existing wallet.
    Import {
        /// Hex-encoded private key.
        private_key: String,
        /// Optional flag to not add a password.
        #[clap(long, action)]
        no_password: bool,
        /// Optional password to encrypt the wallet with.
        #[clap(long, short)]
        password: Option<String>,
    },

    /// Print the private key of a wallet.
    Export,

    /// Check the balance of the wallet.
    Balance,
}

/// Developer and analytics tools for network diagnostics.
/// Only available when the `developer` feature is enabled.
#[cfg(feature = "developer")]
#[derive(Subcommand, Debug)]
pub enum DeveloperCmd {
    /// Query a node to get its network view of closest peers to a target address.
    ///
    /// This asks the specified node to perform an actual Kademlia network lookup
    /// (not just return its local routing table) and returns the results from
    /// that node's network perspective.
    ClosestPeers {
        /// Node to query: either a PeerId or full multiaddr.
        ///
        /// Examples:
        ///   - PeerId: 12D3KooWRBhwfeP2Y4TCx1SM6s9rUoHhR5STiGwxBhgFRcw3UERE
        ///   - Multiaddr: /ip4/127.0.0.1/udp/12000/quic-v1/p2p/12D3KooW...
        ///
        /// When only a PeerId is provided, the peer's address is discovered via the network.
        #[arg(name = "node")]
        node_addr: String,
        /// Target address to find closest peers for (hex string or PeerId).
        #[arg(name = "target")]
        target: String,
        /// Number of peers to return (default: uses K_VALUE, typically 20).
        #[arg(short = 'n', long)]
        num_peers: Option<usize>,
        /// Compare the node's perspective with the client's perspective.
        #[arg(long)]
        compare: bool,
    },
    /// Get the version of a node.
    ///
    /// Queries a specific node to retrieve its software version.
    NodeVersion {
        /// Node to query: either a PeerId or full multiaddr.
        ///
        /// Examples:
        ///   - PeerId: 12D3KooWRBhwfeP2Y4TCx1SM6s9rUoHhR5STiGwxBhgFRcw3UERE
        ///   - Multiaddr: /ip4/127.0.0.1/udp/12000/quic-v1/p2p/12D3KooW...
        ///
        /// When only a PeerId is provided, the peer's address is discovered via the network.
        #[arg(name = "node")]
        node_addr: String,
    },
    /// Get a storage quote from a specific peer.
    ///
    /// This queries a specific node to get a quote for storing data at a given address.
    /// The quote contains pricing metrics and node information.
    GetQuote {
        /// Peer to query: either a PeerId or full multiaddr.
        ///
        /// Examples:
        ///   - PeerId: 12D3KooWRBhwfeP2Y4TCx1SM6s9rUoHhR5STiGwxBhgFRcw3UERE
        ///   - Multiaddr: /ip4/127.0.0.1/udp/12000/quic-v1/p2p/12D3KooW...
        ///
        /// When only a PeerId is provided, the peer's address is discovered via the network.
        #[arg(name = "peer")]
        peer_addr: String,
        /// Target address for the quote (hex string, ChunkAddress, or XorName).
        /// If not provided, a random address will be generated.
        #[arg(name = "address")]
        address: Option<String>,
        /// Data type index (default: 0 for Chunk).
        #[arg(short = 't', long, default_value = "0")]
        data_type: u32,
        /// Data size in bytes (default: 1048576 = 1MB).
        #[arg(short = 's', long, default_value = "1048576")]
        data_size: usize,
    },
}

#[derive(Args, Debug)]
pub(crate) struct TransactionOpt {
    /// Max fee per gas / gas price bid.
    /// Options:
    /// - `low`: Use the average max gas price bid.
    /// - `market`: Use the current max gas price bid, with a max of 4 * the average gas price bid. (default)
    /// - `auto`: Use the current max gas price bid. WARNING: Can result in high gas fees! (default: when using custom EVM network)
    /// - `limited-auto:<WEI AMOUNT>`: Use the current max gas price bid, with a specified upper limit.
    /// - `unlimited`: Do not use a limit for the gas price bid. WARNING: Can result in high gas fees!
    /// - `<WEI AMOUNT>`: Set a custom max gas price bid.
    #[clap(long, verbatim_doc_comment)]
    pub max_fee_per_gas: Option<MaxFeePerGasParam>,
}

pub async fn handle_subcommand(opt: Opt) -> Result<()> {
    let cmd = opt.command;

    let network_context = if opt.alpha {
        NetworkContext::new(opt.peers, NetworkId::alpha())
    } else {
        NetworkContext::new(opt.peers, opt.network_id)
    };

    match cmd {
        Some(SubCmd::File { command }) => match command {
            FileCmd::Cost {
                file,
                public,
                no_archive,
                payment_flags,
            } => file::cost(&file, public, !no_archive, network_context, payment_flags).await,
            FileCmd::Upload {
                file,
                public,
                no_archive,
                retry_failed,
                payment_flags,
                transaction_opt,
            } => {
                if let Err((err, exit_code)) = file::upload(
                    &file,
                    public,
                    no_archive,
                    network_context,
                    transaction_opt.max_fee_per_gas,
                    retry_failed,
                    payment_flags,
                )
                .await
                {
                    eprintln!("{err:?}");
                    std::process::exit(exit_code);
                } else {
                    Ok(())
                }
            }
            FileCmd::Download {
                addr,
                dest_file,
                quorum,
                retries,
                disable_cache,
                cache_dir,
            } => {
                if let Err((err, exit_code)) = file::download(
                    &addr,
                    &dest_file,
                    network_context,
                    quorum,
                    retries,
                    !disable_cache, // Invert the flag - cache is enabled by default
                    cache_dir.as_ref(),
                )
                .await
                {
                    eprintln!("{err:?}");
                    if !disable_cache {
                        println!("Successfully downloaded chunks were cached.");
                        println!(
                            "Please run the command again to obtain the chunks that were not retrieved and complete the download."
                        );
                    }
                    std::process::exit(exit_code);
                } else {
                    Ok(())
                }
            }
            FileCmd::List { verbose } => {
                if let Err((err, exit_code)) = file::list(network_context, verbose).await {
                    eprintln!("{err:?}");
                    std::process::exit(exit_code);
                } else {
                    Ok(())
                }
            }
        },
        Some(SubCmd::Register { command }) => match command {
            RegisterCmd::GenerateKey { overwrite } => register::generate_key(overwrite),
            RegisterCmd::Cost { name } => register::cost(&name, network_context).await,
            RegisterCmd::Create {
                name,
                value,
                hex,
                transaction_opt,
            } => {
                register::create(
                    &name,
                    &value,
                    hex,
                    network_context,
                    transaction_opt.max_fee_per_gas,
                )
                .await
            }
            RegisterCmd::Edit {
                address,
                name,
                value,
                hex,
                transaction_opt,
            } => {
                register::edit(
                    address,
                    name,
                    &value,
                    hex,
                    network_context,
                    transaction_opt.max_fee_per_gas,
                )
                .await
            }
            RegisterCmd::Get { address, name, hex } => {
                register::get(address, name, hex, network_context).await
            }
            RegisterCmd::History { address, name, hex } => {
                register::history(address, name, hex, network_context).await
            }
            RegisterCmd::List => register::list(),
        },
        Some(SubCmd::Vault { command }) => match command {
            VaultCmd::Cost { expected_max_size } => {
                vault::cost(network_context, expected_max_size).await
            }
            VaultCmd::Create { transaction_opt } => {
                vault::create(network_context, transaction_opt.max_fee_per_gas).await
            }
            VaultCmd::Load => vault::load(network_context).await,
            VaultCmd::Sync { force } => vault::sync(force, network_context).await,
        },
        Some(SubCmd::Scratchpad { command }) => match command {
            ScratchpadCmd::GenerateKey { overwrite } => scratchpad::generate_key(overwrite),
            ScratchpadCmd::Cost { name } => scratchpad::cost(name, network_context).await,
            ScratchpadCmd::Create {
                name,
                data,
                transaction_opt,
            } => {
                scratchpad::create(network_context, name, data, transaction_opt.max_fee_per_gas)
                    .await
            }
            ScratchpadCmd::Share { name } => scratchpad::share(name),
            ScratchpadCmd::Get {
                name,
                secret_key,
                hex,
            } => scratchpad::get(network_context, name, secret_key, hex).await,
            ScratchpadCmd::Edit {
                name,
                secret_key,
                data,
            } => scratchpad::edit(network_context, name, secret_key, data).await,
            ScratchpadCmd::List { verbose } => scratchpad::list(verbose),
        },
        Some(SubCmd::Pointer { command }) => match command {
            PointerCmd::GenerateKey { overwrite } => pointer::generate_key(overwrite),
            PointerCmd::Cost { name } => pointer::cost(name, network_context).await,
            PointerCmd::Create {
                name,
                target,
                target_data_type,
                transaction_opt,
            } => {
                pointer::create(
                    network_context,
                    name,
                    target,
                    target_data_type,
                    transaction_opt.max_fee_per_gas,
                )
                .await
            }
            PointerCmd::Share { name } => pointer::share(name),
            PointerCmd::Get { name, secret_key } => {
                pointer::get(network_context, name, secret_key).await
            }
            PointerCmd::Edit {
                name,
                target,
                target_data_type,
                secret_key,
            } => pointer::edit(network_context, name, secret_key, target, target_data_type).await,
            PointerCmd::List { verbose } => pointer::list(verbose),
        },
        Some(SubCmd::Wallet { command }) => match command {
            WalletCmd::Create {
                no_password,
                password,
            } => wallet::create(no_password, password),
            WalletCmd::Import {
                private_key,
                no_password,
                password,
            } => wallet::import(private_key, no_password, password),
            WalletCmd::Export => wallet::export(),
            WalletCmd::Balance => wallet::balance(network_context).await,
        },
        Some(SubCmd::Analyze {
            addr,
            closest_nodes,
            holders,
            nodes_health,
            repair,
            addr_range,
            verbose,
            recursive,
            json,
        }) => {
            analyze::analyze(
                &addr,
                closest_nodes,
                holders,
                nodes_health,
                repair,
                addr_range,
                recursive,
                verbose,
                network_context,
                json,
            )
            .await
        }
        #[cfg(feature = "developer")]
        Some(SubCmd::Developer { command }) => match command {
            DeveloperCmd::ClosestPeers {
                node_addr,
                target,
                num_peers,
                compare,
            } => {
                developer::closest_peers(&node_addr, &target, num_peers, compare, network_context)
                    .await
            }
            DeveloperCmd::NodeVersion { node_addr } => {
                developer::node_version(&node_addr, network_context).await
            }
            DeveloperCmd::GetQuote {
                peer_addr,
                address,
                data_type,
                data_size,
            } => {
                developer::get_quote(
                    &peer_addr,
                    address.as_deref(),
                    data_type,
                    data_size,
                    network_context,
                )
                .await
            }
        },
        None => {
            // If no subcommand is given, default to clap's error behaviour.
            Opt::command()
                .error(ErrorKind::MissingSubcommand, "Please provide a subcommand")
                .exit();
        }
    }
}

fn parse_quorum(str: &str) -> Result<Quorum, String> {
    match str {
        "one" => Ok(Quorum::One),
        "majority" => Ok(Quorum::Majority),
        "all" => Ok(Quorum::All),
        _ => {
            let n: NonZeroUsize = str.parse().map_err(|_| "Invalid quorum value")?;
            Ok(Quorum::N(n))
        }
    }
}