rusk-wallet 0.3.0

A library providing functionalities to create wallets compatible with Dusk
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use std::fmt::Display;
use std::io::stdout;

use crossterm::cursor::MoveUp;
use crossterm::execute;
use crossterm::terminal::{Clear, ClearType};
use dusk_core::stake::DEFAULT_MINIMUM_STAKE;
use dusk_core::transfer::data::MAX_MEMO_SIZE;
use inquire::{InquireError, Select};
use rusk_wallet::currency::Dusk;
use rusk_wallet::gas::{
    self, DEFAULT_LIMIT_CALL, DEFAULT_LIMIT_STAKE, DEFAULT_LIMIT_TRANSFER,
    DEFAULT_PRICE, GAS_PER_DEPLOY_BYTE, MIN_PRICE_DEPLOYMENT,
};
use rusk_wallet::{
    Address, Error, MAX_FUNCTION_NAME_SIZE, MIN_CONVERTIBLE, Wallet,
};

use super::ProfileOp;
use crate::io::prompt::{
    EXIT_HELP, FILTER_HELP, GO_BACK_HELP, MOVE_HELP, SELECT_HELP,
};
use crate::settings::Settings;
use crate::{Command, WalletFile, prompt};

/// The top-level command-menu items
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
enum MenuItem {
    History,
    Transfer,
    Unshield,
    Shield,
    Staking,
    Contracts,
    Back,
}

impl Display for MenuItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MenuItem::History => write!(f, "Show Transactions History"),
            MenuItem::Transfer => write!(f, "Transfer Dusk"),
            MenuItem::Unshield => {
                write!(f, "Convert Shielded Dusk to Public Dusk")
            }
            MenuItem::Shield => {
                write!(f, "Convert Public Dusk to Shielded Dusk")
            }
            MenuItem::Staking => write!(f, "Staking"),
            MenuItem::Contracts => write!(f, "Contracts"),
            MenuItem::Back => write!(f, "Back"),
        }
    }
}

/// Staking submenu items
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
enum StakingMenuItem {
    Stake,
    Unstake,
    ClaimRewards,
    StakeInfo,
    Export,
    Back,
}

impl Display for StakingMenuItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StakingMenuItem::Stake => write!(f, "Stake"),
            StakingMenuItem::Unstake => write!(f, "Unstake"),
            StakingMenuItem::ClaimRewards => {
                write!(f, "Claim Stake Rewards")
            }
            StakingMenuItem::StakeInfo => write!(f, "Stake Info"),
            StakingMenuItem::Export => {
                write!(f, "Export Provisioner Key-Pair")
            }
            StakingMenuItem::Back => write!(f, "Back"),
        }
    }
}

/// Contract submenu items
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
enum ContractsMenuItem {
    ContractDeploy,
    ContractCall,
    DriverDeploy,
    CalculateContractId,
    Back,
}

impl Display for ContractsMenuItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ContractsMenuItem::ContractDeploy => {
                write!(f, "Deploy a Contract")
            }
            ContractsMenuItem::ContractCall => write!(f, "Call a Contract"),
            ContractsMenuItem::DriverDeploy => {
                write!(f, "Deploy a Contract's Driver")
            }
            ContractsMenuItem::CalculateContractId => {
                write!(f, "Calculate Contract ID")
            }
            ContractsMenuItem::Back => write!(f, "Back"),
        }
    }
}

/// Allows the user to choose the operation to perform for the
/// selected profile
pub(crate) async fn online(
    profile_idx: u8,
    wallet: &Wallet<WalletFile>,
    phoenix_spendable: Dusk,
    moonlight_balance: Dusk,
    settings: &Settings,
) -> anyhow::Result<ProfileOp> {
    let cmd_menu = vec![
        MenuItem::History,
        MenuItem::Transfer,
        MenuItem::Unshield,
        MenuItem::Shield,
        MenuItem::Staking,
        MenuItem::Contracts,
        MenuItem::Back,
    ];

    let select = Select::new("What would you like to do?", cmd_menu)
        .with_help_message(
            &[MOVE_HELP, SELECT_HELP, FILTER_HELP, GO_BACK_HELP, EXIT_HELP]
                .join(", "),
        )
        .prompt();

    if let Err(InquireError::OperationCanceled) = select {
        return Ok(ProfileOp::Back);
    }

    let res = match select? {
        MenuItem::Transfer => {
            let rcvr = prompt::request_rcvr_addr("recipient")?;

            let (sender, balance) = match &rcvr {
                Address::Shielded(_) => {
                    (wallet.shielded_account(profile_idx)?, phoenix_spendable)
                }
                Address::Public(_) => {
                    (wallet.public_address(profile_idx)?, moonlight_balance)
                }
            };

            if check_min_gas_balance(
                balance,
                DEFAULT_LIMIT_TRANSFER,
                "a transfer transaction",
            )
            .is_err()
            {
                return Ok(ProfileOp::Stay);
            }

            let memo = Some(prompt::request_str("memo", MAX_MEMO_SIZE)?);
            let amt = if memo.is_some() {
                prompt::request_optional_token_amt("transfer", balance)
            } else {
                prompt::request_token_amt("transfer", balance)
            }?;

            let mempool_gas_prices = wallet.get_mempool_gas_prices().await?;

            ProfileOp::Run(Box::new(Command::Transfer {
                sender: Some(sender),
                rcvr,
                amt,
                gas_limit: prompt::request_gas_limit(
                    gas::DEFAULT_LIMIT_TRANSFER,
                )?,
                memo,
                gas_price: prompt::request_gas_price(
                    DEFAULT_PRICE,
                    mempool_gas_prices,
                )?,
            }))
        }
        MenuItem::History => ProfileOp::Run(Box::new(Command::History {
            profile_idx: Some(profile_idx),
        })),
        MenuItem::Shield => {
            if check_min_gas_balance(
                moonlight_balance,
                DEFAULT_LIMIT_CALL,
                "convert DUSK from public to shielded",
            )
            .is_err()
            {
                return Ok(ProfileOp::Stay);
            }

            let mempool_gas_prices = wallet.get_mempool_gas_prices().await?;

            ProfileOp::Run(Box::new(Command::Shield {
                profile_idx: Some(profile_idx),
                amt: prompt::request_token_amt("convert", moonlight_balance)?,
                gas_limit: prompt::request_gas_limit(gas::DEFAULT_LIMIT_CALL)?,
                gas_price: prompt::request_gas_price(
                    DEFAULT_PRICE,
                    mempool_gas_prices,
                )?,
            }))
        }
        MenuItem::Unshield => {
            if check_min_gas_balance(
                phoenix_spendable,
                DEFAULT_LIMIT_CALL,
                "convert DUSK from shielded to public",
            )
            .is_err()
            {
                return Ok(ProfileOp::Stay);
            }

            let mempool_gas_prices = wallet.get_mempool_gas_prices().await?;

            ProfileOp::Run(Box::new(Command::Unshield {
                profile_idx: Some(profile_idx),
                amt: prompt::request_token_amt("convert", phoenix_spendable)?,
                gas_limit: prompt::request_gas_limit(gas::DEFAULT_LIMIT_CALL)?,
                gas_price: prompt::request_gas_price(
                    DEFAULT_PRICE,
                    mempool_gas_prices,
                )?,
            }))
        }
        MenuItem::Staking => {
            let _ =
                execute!(stdout(), MoveUp(1), Clear(ClearType::CurrentLine));
            return staking_menu(
                profile_idx,
                wallet,
                phoenix_spendable,
                moonlight_balance,
                settings,
            )
            .await;
        }
        MenuItem::Contracts => {
            let _ =
                execute!(stdout(), MoveUp(1), Clear(ClearType::CurrentLine));
            return contracts_menu(
                profile_idx,
                wallet,
                phoenix_spendable,
                moonlight_balance,
            )
            .await;
        }
        MenuItem::Back => ProfileOp::Back,
    };

    Ok(res)
}

/// Allows the user to choose the operation to perform for the
/// selected profile while in offline mode
pub(crate) fn offline(
    profile_idx: u8,
    settings: &Settings,
) -> anyhow::Result<ProfileOp> {
    let cmd_menu = vec![StakingMenuItem::Export, StakingMenuItem::Back];

    let select = Select::new("[OFFLINE] What would you like to do?", cmd_menu)
        .with_help_message(
            &[MOVE_HELP, SELECT_HELP, GO_BACK_HELP, EXIT_HELP].join(", "),
        )
        .prompt();

    if let Err(InquireError::OperationCanceled) = select {
        return Ok(ProfileOp::Back);
    }

    let res = match select? {
        StakingMenuItem::Export => ProfileOp::Run(Box::new(Command::Export {
            profile_idx: Some(profile_idx),
            name: None,
            dir: prompt::request_dir(
                "export keys",
                settings.wallet_dir.clone(),
            )?,
            export_pwd: None,
        })),
        StakingMenuItem::Back => ProfileOp::Back,
        _ => unreachable!(),
    };

    Ok(res)
}

/// Displays the staking operations submenu
async fn staking_menu(
    profile_idx: u8,
    wallet: &Wallet<WalletFile>,
    phoenix_spendable: Dusk,
    moonlight_balance: Dusk,
    settings: &Settings,
) -> anyhow::Result<ProfileOp> {
    let menu = vec![
        StakingMenuItem::Stake,
        StakingMenuItem::Unstake,
        StakingMenuItem::ClaimRewards,
        StakingMenuItem::StakeInfo,
        StakingMenuItem::Export,
        StakingMenuItem::Back,
    ];

    let select =
        Select::new("What staking operation would you like to do?", menu)
            .with_help_message(
                &[MOVE_HELP, SELECT_HELP, FILTER_HELP, GO_BACK_HELP, EXIT_HELP]
                    .join(", "),
            )
            .prompt();

    if let Err(InquireError::OperationCanceled) = select {
        return Ok(ProfileOp::Stay);
    }

    let res = match select? {
        StakingMenuItem::Stake => {
            let (addr, balance) = pick_transaction_model(
                wallet,
                profile_idx,
                phoenix_spendable,
                moonlight_balance,
            )?;

            if check_min_gas_balance(
                balance,
                DEFAULT_LIMIT_STAKE,
                "a stake transaction",
            )
            .is_err()
            {
                return Ok(ProfileOp::Stay);
            }

            let mempool_gas_prices = wallet.get_mempool_gas_prices().await?;

            let stake_idx = wallet
                .find_index(&addr)
                .expect("index to exists in interactive mode");
            let stake_pk = wallet
                .public_key(stake_idx)
                .expect("public key to exists in interactive mode");

            let min_val = {
                let has_stake = wallet
                    .stake_info(stake_idx)
                    .await?
                    .map(|s| s.amount.is_some())
                    .unwrap_or_default();

                // if the user has stake then they are performing a topup
                if has_stake {
                    MIN_CONVERTIBLE
                } else {
                    DEFAULT_MINIMUM_STAKE.into()
                }
            };

            if balance < min_val {
                println!(
                    "The stake must be at least {min_val}, but your balance is only {balance}\n"
                );
                return Ok(ProfileOp::Stay);
            }

            let owner = match wallet.find_stake_owner_account(stake_pk).await {
                Ok(account) => account,
                Err(Error::NotStaked) => {
                    let choices = wallet
                        .profiles()
                        .iter()
                        .map(|p| Address::Public(p.public_addr))
                        .collect();
                    prompt::request_owner_key(stake_idx, choices)?
                }
                e => e?,
            };

            ProfileOp::Run(Box::new(Command::Stake {
                address: Some(addr),
                owner: Some(owner),
                amt: prompt::request_stake_token_amt(balance, min_val)?,
                gas_limit: prompt::request_gas_limit(gas::DEFAULT_LIMIT_CALL)?,
                gas_price: prompt::request_gas_price(
                    DEFAULT_PRICE,
                    mempool_gas_prices,
                )?,
            }))
        }
        StakingMenuItem::Unstake => {
            let (addr, balance) = pick_transaction_model(
                wallet,
                profile_idx,
                phoenix_spendable,
                moonlight_balance,
            )?;

            if check_min_gas_balance(
                balance,
                DEFAULT_LIMIT_STAKE,
                "an unstake transaction",
            )
            .is_err()
            {
                return Ok(ProfileOp::Stay);
            }

            let mempool_gas_prices = wallet.get_mempool_gas_prices().await?;

            ProfileOp::Run(Box::new(Command::Unstake {
                address: Some(addr),
                gas_limit: prompt::request_gas_limit(gas::DEFAULT_LIMIT_CALL)?,
                gas_price: prompt::request_gas_price(
                    DEFAULT_PRICE,
                    mempool_gas_prices,
                )?,
            }))
        }
        StakingMenuItem::ClaimRewards => {
            let (addr, balance) = pick_transaction_model(
                wallet,
                profile_idx,
                phoenix_spendable,
                moonlight_balance,
            )?;

            if check_min_gas_balance(
                balance,
                DEFAULT_LIMIT_STAKE,
                "a stake reward claim transaction",
            )
            .is_err()
            {
                return Ok(ProfileOp::Stay);
            }

            let mempool_gas_prices = wallet.get_mempool_gas_prices().await?;
            let max_withdraw = wallet.get_stake_reward(profile_idx).await?;

            ProfileOp::Run(Box::new(Command::ClaimRewards {
                address: Some(addr),
                reward: Some(prompt::request_token_amt_with_default(
                    "claim rewards",
                    max_withdraw,
                    max_withdraw,
                )?),
                gas_limit: prompt::request_gas_limit(gas::DEFAULT_LIMIT_CALL)?,
                gas_price: prompt::request_gas_price(
                    DEFAULT_PRICE,
                    mempool_gas_prices,
                )?,
            }))
        }
        StakingMenuItem::StakeInfo => {
            ProfileOp::Run(Box::new(Command::StakeInfo {
                profile_idx: Some(profile_idx),
                reward: false,
            }))
        }
        StakingMenuItem::Export => ProfileOp::Run(Box::new(Command::Export {
            profile_idx: Some(profile_idx),
            name: None,
            dir: prompt::request_dir(
                "export keys",
                settings.wallet_dir.clone(),
            )?,
            export_pwd: None,
        })),
        StakingMenuItem::Back => ProfileOp::Stay,
    };

    Ok(res)
}

/// Displays the contract operations submenu
async fn contracts_menu(
    profile_idx: u8,
    wallet: &Wallet<WalletFile>,
    phoenix_spendable: Dusk,
    moonlight_balance: Dusk,
) -> anyhow::Result<ProfileOp> {
    let menu = vec![
        ContractsMenuItem::ContractDeploy,
        ContractsMenuItem::ContractCall,
        ContractsMenuItem::DriverDeploy,
        ContractsMenuItem::CalculateContractId,
        ContractsMenuItem::Back,
    ];

    let select =
        Select::new("What contract operation would you like to do?", menu)
            .with_help_message(
                &[MOVE_HELP, SELECT_HELP, FILTER_HELP, GO_BACK_HELP, EXIT_HELP]
                    .join(", "),
            )
            .prompt();

    if let Err(InquireError::OperationCanceled) = select {
        return Ok(ProfileOp::Stay);
    }

    let res = match select? {
        ContractsMenuItem::ContractDeploy => {
            let (addr, balance) = pick_transaction_model(
                wallet,
                profile_idx,
                phoenix_spendable,
                moonlight_balance,
            )?;

            // Request the contract code and determine its length
            let code = prompt::request_contract_code()?;
            let code_len = code.metadata()?.len() as u64;

            let mempool_gas_prices = wallet.get_mempool_gas_prices().await?;

            // Calculate the effective cost for the deployment
            let gas_price = prompt::request_gas_price(
                MIN_PRICE_DEPLOYMENT,
                mempool_gas_prices,
            )?;
            let gas_limit =
                (code_len * GAS_PER_DEPLOY_BYTE) + DEFAULT_LIMIT_TRANSFER;

            if check_min_gas_balance(
                balance,
                gas_limit * gas_price,
                "the deployment of the given contract",
            )
            .is_err()
            {
                return Ok(ProfileOp::Stay);
            }

            ProfileOp::Run(Box::new(Command::ContractDeploy {
                address: Some(addr),
                code,
                init_args: prompt::request_init_args()?,
                deploy_nonce: prompt::request_nonce()?,
                gas_limit: prompt::request_gas_limit(gas_limit)?,
                gas_price,
            }))
        }
        ContractsMenuItem::ContractCall => {
            let (addr, balance) = pick_transaction_model(
                wallet,
                profile_idx,
                phoenix_spendable,
                moonlight_balance,
            )?;

            if check_min_gas_balance(
                balance,
                DEFAULT_LIMIT_CALL,
                "a contract call",
            )
            .is_err()
            {
                return Ok(ProfileOp::Stay);
            }

            let mempool_gas_prices = wallet.get_mempool_gas_prices().await?;

            ProfileOp::Run(Box::new(Command::ContractCall {
                address: Some(addr),
                contract_id: prompt::request_bytes("contract id")?,
                fn_name: prompt::request_str(
                    "function name to call",
                    MAX_FUNCTION_NAME_SIZE,
                )?,
                fn_args: prompt::request_bytes(
                    "arguments of calling function",
                )?,
                deposit: prompt::request_optional_token_amt(
                    "deposit", balance,
                )?,
                gas_limit: prompt::request_gas_limit(gas::DEFAULT_LIMIT_CALL)?,
                gas_price: prompt::request_gas_price(
                    DEFAULT_PRICE,
                    mempool_gas_prices,
                )?,
            }))
        }
        ContractsMenuItem::DriverDeploy => {
            ProfileOp::Run(Box::new(Command::DriverDeploy {
                code: prompt::request_driver_code()?,
                profile_idx: Some(profile_idx),
                contract_id: prompt::request_bytes("contract id")?,
            }))
        }
        ContractsMenuItem::CalculateContractId => {
            ProfileOp::Run(Box::new(Command::CalculateContractId {
                profile_idx: Some(profile_idx),
                deploy_nonce: prompt::request_nonce()?,
                code: prompt::request_contract_code()?,
            }))
        }
        ContractsMenuItem::Back => ProfileOp::Stay,
    };

    Ok(res)
}

/// Prompts the user to select a transaction model (Shielded or Public), and
/// retrieves the corresponding address and balance for the specific profile
fn pick_transaction_model(
    wallet: &Wallet<WalletFile>,
    profile_idx: u8,
    phoenix_spendable: Dusk,
    moonlight_balance: Dusk,
) -> anyhow::Result<(Address, Dusk)> {
    match prompt::request_transaction_model()? {
        prompt::TransactionModel::Shielded => {
            let addr = wallet.shielded_account(profile_idx)?;
            Ok((addr, phoenix_spendable))
        }
        prompt::TransactionModel::Public => {
            let addr = wallet.public_address(profile_idx)?;
            Ok((addr, moonlight_balance))
        }
    }
}

/// Verifies that the user's balance meets the minimum required gas for a given
/// action
fn check_min_gas_balance(
    balance: Dusk,
    min_required_gas: u64,
    action: &str,
) -> anyhow::Result<()> {
    let min_required_gas: Dusk = min_required_gas.into();
    if balance < min_required_gas {
        println!(
            "Balance too low to cover the minimum gas cost for {}.",
            action
        );
        Err(anyhow::anyhow!(
            "Balance too low to cover the minimum gas cost for {}.",
            action
        ))
    } else {
        Ok(())
    }
}