Skip to content

Commit

Permalink
Fix cache, unit conversion problems
Browse files Browse the repository at this point in the history
  • Loading branch information
Daksh14 committed Aug 29, 2024
1 parent 643945a commit 4b18de0
Show file tree
Hide file tree
Showing 13 changed files with 451 additions and 114 deletions.
47 changes: 26 additions & 21 deletions rusk-wallet/src/bin/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,20 @@
mod history;

use clap::Subcommand;
use dusk_plonk::prelude::BlsScalar;
use rusk_abi::hash::Hasher;
use std::{fmt, path::PathBuf};

use crate::io::prompt;
use crate::settings::Settings;
use crate::{WalletFile, WalletPath};

use dusk_wallet::currency::Dusk;

use dusk_wallet::gas::{Gas, DEFAULT_LIMIT, DEFAULT_PRICE};
use dusk_wallet::{Address, Dusk, Lux, Wallet, EPOCH, MAX_ADDRESSES};
use dusk_wallet_core::{BalanceInfo, StakeInfo};
use dusk_wallet::{Address, Error, Wallet, EPOCH, MAX_ADDRESSES};
use wallet_core::{
prelude::{from_dusk, BlsScalar, StakeData},
BalanceInfo,
};

pub use history::TransactionHistory;

Expand Down Expand Up @@ -91,7 +94,7 @@ pub(crate) enum Command {

/// Price you're going to pay for each gas unit (in LUX)
#[clap(short = 'p', long, default_value_t= DEFAULT_PRICE)]
gas_price: Lux,
gas_price: u64,
},

/// Start staking DUSK
Expand All @@ -110,7 +113,7 @@ pub(crate) enum Command {

/// Price you're going to pay for each gas unit (in LUX)
#[clap(short = 'p', long, default_value_t= DEFAULT_PRICE)]
gas_price: Lux,
gas_price: u64,
},

/// Check your stake information
Expand All @@ -136,7 +139,7 @@ pub(crate) enum Command {

/// Price you're going to pay for each gas unit (in LUX)
#[clap(short = 'p', long, default_value_t= DEFAULT_PRICE)]
gas_price: Lux,
gas_price: u64,
},

/// Withdraw accumulated reward for a stake key
Expand All @@ -151,7 +154,7 @@ pub(crate) enum Command {

/// Price you're going to pay for each gas unit (in LUX)
#[clap(short = 'p', long, default_value_t= DEFAULT_PRICE)]
gas_price: Lux,
gas_price: u64,
},

/// Export BLS provisioner key pair
Expand Down Expand Up @@ -230,7 +233,7 @@ impl Command {
let gas = Gas::new(gas_limit).with_price(gas_price);

let tx = wallet.transfer(sender, &rcvr, amt, gas).await?;
Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes())))
Ok(RunResult::Tx(tx.hash()))
}
Command::Stake {
addr,
Expand All @@ -246,14 +249,16 @@ impl Command {
let gas = Gas::new(gas_limit).with_price(gas_price);

let tx = wallet.stake(addr, amt, gas).await?;
Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes())))
Ok(RunResult::Tx(tx.hash()))
}
Command::StakeInfo { addr, reward } => {
let addr = match addr {
Some(addr) => wallet.claim_as_address(addr)?,
None => wallet.default_address(),
};
let si = wallet.stake_info(addr).await?;
let si =
wallet.stake_info(addr).await?.ok_or(Error::NotStaked)?;

Ok(RunResult::StakeInfo(si, reward))
}
Command::Unstake {
Expand All @@ -270,7 +275,7 @@ impl Command {
let gas = Gas::new(gas_limit).with_price(gas_price);

let tx = wallet.unstake(addr, gas).await?;
Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes())))
Ok(RunResult::Tx(tx.hash()))
}
Command::Withdraw {
addr,
Expand All @@ -286,7 +291,7 @@ impl Command {
let gas = Gas::new(gas_limit).with_price(gas_price);

let tx = wallet.withdraw_reward(addr, gas).await?;
Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes())))
Ok(RunResult::Tx(tx.hash()))
}
Command::Export { addr, dir, name } => {
let addr = match addr {
Expand Down Expand Up @@ -329,7 +334,7 @@ impl Command {
pub enum RunResult {
Tx(BlsScalar),
Balance(BalanceInfo, bool),
StakeInfo(StakeInfo, bool),
StakeInfo(StakeData, bool),
Address(Box<Address>),
Addresses(Vec<Address>),
ExportedKeys(PathBuf, PathBuf),
Expand Down Expand Up @@ -366,21 +371,21 @@ impl fmt::Display for RunResult {
let hash = hex::encode(hash.to_bytes());
write!(f, "> Transaction sent: {hash}",)
}
StakeInfo(si, _) => {
let stake_str = match si.amount {
Some((value, eligibility)) => format!(
StakeInfo(data, _) => {
let stake_str = match data.amount {
Some(amt) => format!(
"Current stake amount is: {} DUSK\n> Stake eligibility from block #{} (Epoch {})",
Dusk::from(value),
eligibility,
eligibility / EPOCH
from_dusk(amt.value),
amt.eligibility,
amt.eligibility / EPOCH
),
None => "No active stake found for this key".to_string(),
};
write!(
f,
"> {}\n> Accumulated reward is: {} DUSK",
stake_str,
Dusk::from(si.reward)
Dusk::from(data.reward)
)
}
ExportedKeys(pk, kp) => {
Expand Down
17 changes: 9 additions & 8 deletions rusk-wallet/src/bin/command/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use std::collections::HashMap;
use std::fmt::{self, Display};

use dusk_wallet::DecodedNote;
use dusk_wallet_core::Transaction;
use rusk_abi::dusk;

use wallet_core::prelude::{dusk, from_dusk, Transaction};

use crate::io::{self, GraphQL};
use crate::settings::Settings;
Expand All @@ -35,17 +35,17 @@ impl TransactionHistory {

impl Display for TransactionHistory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let dusk = self.amount / dusk::dusk(1.0) as f64;
let dusk = self.amount / dusk(1.0) as f64;
let contract = match self.tx.call() {
None => "transfer",
Some((_, method, _)) => method,
Some(call) => &call.fn_name,
};

let fee = match self.direction {
TransactionDirection::In => "".into(),
TransactionDirection::Out => {
let fee = self.fee;
let fee = dusk::from_dusk(fee);
let fee = from_dusk(fee);
format!("{: >12.9}", fee)
}
};
Expand Down Expand Up @@ -95,8 +95,8 @@ pub(crate) async fn transaction_from_notes(
let note_hash = decoded_note.note.hash();
// Looking for the transaction which created the note
let note_creator = txs.iter().find(|(t, _, _)| {
t.outputs().iter().any(|&n| n.hash().eq(&note_hash))
|| t.nullifiers
t.outputs().iter().any(|n| n.hash().eq(&note_hash))
|| t.nullifiers()
.iter()
.any(|tx_null| nullifiers.iter().any(|(n, _)| n == tx_null))
});
Expand All @@ -114,13 +114,14 @@ pub(crate) async fn transaction_from_notes(
true => TransactionDirection::Out,
false => TransactionDirection::In,
};

match ret.iter_mut().find(|th| &th.id == tx_id) {
Some(tx) => tx.amount += note_amount,
None => ret.push(TransactionHistory {
direction,
height: decoded_note.block_height,
amount: note_amount - inputs_amount,
fee: gas_spent * t.fee().gas_price,
fee: gas_spent * t.gas_price(),
tx: t.clone(),
id: tx_id.clone(),
}),
Expand Down
16 changes: 9 additions & 7 deletions rusk-wallet/src/bin/interactive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
// Copyright (c) DUSK NETWORK. All rights reserved.

use bip39::{Language, Mnemonic, MnemonicType};
use dusk_wallet::currency::Dusk;
use dusk_wallet::dat::{DatFileVersion, LATEST_VERSION};
use dusk_wallet::gas;
use dusk_wallet::{Address, Dusk, Error, Wallet, WalletPath, MAX_ADDRESSES};
use dusk_wallet::{Address, Error, Wallet, WalletPath, MAX_ADDRESSES};
use requestty::Question;
use wallet_core::prelude::from_dusk;

use crate::command::DEFAULT_STAKE_GAS_LIMIT;
use crate::io;
Expand Down Expand Up @@ -68,7 +70,7 @@ pub(crate) async fn run_loop(
// get balance for this address
prompt::hide_cursor()?;
let balance = wallet.get_balance(&addr).await?;
let spendable: Dusk = balance.spendable.into();
let spendable = balance.spendable.into();
let total: Dusk = balance.value.into();
prompt::hide_cursor()?;

Expand Down Expand Up @@ -159,7 +161,7 @@ fn menu_addr(wallet: &Wallet<WalletFile>) -> anyhow::Result<AddrSelect> {
));
}

if let Some(rx) = &wallet.sync_rx {
if let Some(rx) = &wallet.state()?.sync_rx {
if let Ok(status) = rx.try_recv() {
action_menu = action_menu
.separator()
Expand Down Expand Up @@ -439,7 +441,7 @@ fn confirm(cmd: &Command) -> anyhow::Result<bool> {
println!(" > Send from = {}", sndr.preview());
println!(" > Recipient = {}", rcvr.preview());
println!(" > Amount to transfer = {} DUSK", amt);
println!(" > Max fee = {} DUSK", Dusk::from(max_fee));
println!(" > Max fee = {} DUSK", from_dusk(max_fee));
prompt::ask_confirm()
}
Command::Stake {
Expand All @@ -452,7 +454,7 @@ fn confirm(cmd: &Command) -> anyhow::Result<bool> {
let max_fee = gas_limit * gas_price;
println!(" > Stake from {}", addr.preview());
println!(" > Amount to stake = {} DUSK", amt);
println!(" > Max fee = {} DUSK", Dusk::from(max_fee));
println!(" > Max fee = {} DUSK", from_dusk(max_fee));
prompt::ask_confirm()
}
Command::Unstake {
Expand All @@ -463,7 +465,7 @@ fn confirm(cmd: &Command) -> anyhow::Result<bool> {
let addr = addr.as_ref().expect("address to be valid");
let max_fee = gas_limit * gas_price;
println!(" > Unstake from {}", addr.preview());
println!(" > Max fee = {} DUSK", Dusk::from(max_fee));
println!(" > Max fee = {} DUSK", from_dusk(max_fee));
prompt::ask_confirm()
}
Command::Withdraw {
Expand All @@ -474,7 +476,7 @@ fn confirm(cmd: &Command) -> anyhow::Result<bool> {
let addr = addr.as_ref().expect("address to be valid");
let max_fee = gas_limit * gas_price;
println!(" > Reward from {}", addr.preview());
println!(" > Max fee = {} DUSK", Dusk::from(max_fee));
println!(" > Max fee = {} DUSK", from_dusk(max_fee));
prompt::ask_confirm()
}
_ => Ok(true),
Expand Down
4 changes: 2 additions & 2 deletions rusk-wallet/src/bin/io/gql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use dusk_wallet_core::Transaction;
use tokio::time::{sleep, Duration};
use wallet_core::prelude::Transaction;

use dusk_wallet::{Error, RuskHttpClient, RuskRequest};
use serde::Deserialize;
Expand Down Expand Up @@ -177,7 +177,7 @@ async fn test() -> Result<(), Box<dyn std::error::Error>> {
.await?;
let block_txs = gql.txs_for_block(90).await?;
block_txs.into_iter().for_each(|(t, chain_txid, _)| {
let hash = rusk_abi::hash::Hasher::digest(t.to_hash_input_bytes());
let hash = t.hash();
let tx_id = hex::encode(hash.to_bytes());
assert_eq!(chain_txid, tx_id);
println!("txid: {tx_id}");
Expand Down
8 changes: 6 additions & 2 deletions rusk-wallet/src/bin/io/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ use bip39::{ErrorKind, Language, Mnemonic};
use dusk_wallet::{dat::DatFileVersion, Error};
use requestty::Question;

use dusk_wallet::{Address, Dusk, Lux};
use dusk_wallet::Address;

use dusk_wallet::gas;
use dusk_wallet::{MAX_CONVERTIBLE, MIN_CONVERTIBLE};
use dusk_wallet::{
currency::{Dusk, Lux},
MAX_CONVERTIBLE, MIN_CONVERTIBLE,
};
use sha2::{Digest, Sha256};

/// Request the user to authenticate with a password
Expand Down Expand Up @@ -244,6 +247,7 @@ pub(crate) fn request_token_amt(
.build();

let a = requestty::prompt_one(question)?;

Ok(a.as_float().expect("answer to be a float").into())
}

Expand Down
15 changes: 8 additions & 7 deletions rusk-wallet/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@ use clap::Parser;
use std::fs::{self, File};
use std::io::Write;
use tracing::{warn, Level};
use wallet_core::prelude::from_dusk;

use bip39::{Language, Mnemonic, MnemonicType};

use crate::command::TransactionHistory;
use crate::settings::{LogFormat, Settings};

use dusk_wallet::{dat, Error};
use dusk_wallet::{Dusk, SecureWalletFile, Wallet, WalletPath};
use dusk_wallet::{SecureWalletFile, Wallet, WalletPath};

use config::Config;
use io::{prompt, status};
Expand Down Expand Up @@ -83,7 +84,7 @@ where

// check for connection errors
match con {
Err(Error::RocksDB(e)) => panic!{"Invalid cache {e}"},
Err(Error::RocksDB(e)) => panic!{"Please reset the cache! {e}"},
Err(e) => warn!("[OFFLINE MODE]: Unable to connect to Rusk, limited functionality available: {e}"),
_ => {}
}
Expand Down Expand Up @@ -287,9 +288,9 @@ async fn exec() -> anyhow::Result<()> {
Some(cmd) => match cmd.run(&mut wallet, &settings).await? {
RunResult::Balance(balance, spendable) => {
if spendable {
println!("{}", Dusk::from(balance.spendable));
println!("{}", from_dusk(balance.spendable));
} else {
println!("{}", Dusk::from(balance.value));
println!("{}", from_dusk(balance.value));
}
}
RunResult::Address(addr) => {
Expand All @@ -311,13 +312,13 @@ async fn exec() -> anyhow::Result<()> {
}
RunResult::StakeInfo(info, reward) => {
if reward {
println!("{}", Dusk::from(info.reward));
println!("{}", from_dusk(info.reward));
} else {
let staked_amount = match info.amount {
Some((staked, ..)) => staked,
Some(info) => info.value,
None => 0,
};
println!("{}", Dusk::from(staked_amount));
println!("{}", from_dusk(staked_amount));
}
}
RunResult::ExportedKeys(pub_key, key_pair) => {
Expand Down
Loading

0 comments on commit 4b18de0

Please sign in to comment.