diff --git a/src/backend_task/core/refresh_wallet_info.rs b/src/backend_task/core/refresh_wallet_info.rs
index bc1fa020f..9b6428c78 100644
--- a/src/backend_task/core/refresh_wallet_info.rs
+++ b/src/backend_task/core/refresh_wallet_info.rs
@@ -30,7 +30,7 @@ impl AppContext {
// Step 2: Iterate over each address and update balances
for address in &addresses {
// Fetch balance for the address from Dash Core
- match self.core_client.get_received_by_address(address, Some(0)) {
+ match self.core_client.get_received_by_address(address, None) {
Ok(new_balance) => {
// Update the wallet's address_balances and database
{
diff --git a/src/backend_task/identity/register_identity.rs b/src/backend_task/identity/register_identity.rs
index ff9f40506..c460b833d 100644
--- a/src/backend_task/identity/register_identity.rs
+++ b/src/backend_task/identity/register_identity.rs
@@ -177,6 +177,7 @@ impl AppContext {
match wallet.asset_lock_transaction(
sdk.network,
amount,
+ true,
identity_index,
Some(self),
) {
@@ -188,6 +189,7 @@ impl AppContext {
wallet.asset_lock_transaction(
sdk.network,
amount,
+ true,
identity_index,
Some(self),
)?
@@ -409,6 +411,7 @@ impl AppContext {
wallet
.unused_asset_locks
.retain(|(tx, _, _, _, _)| tx.txid() != tx_id);
+ wallet.identities.insert(wallet_identity_index, identity);
}
self.db
diff --git a/src/cpu_compatibility.rs b/src/cpu_compatibility.rs
index 20a736284..f9078d060 100644
--- a/src/cpu_compatibility.rs
+++ b/src/cpu_compatibility.rs
@@ -13,7 +13,9 @@ pub fn check_cpu_compatibility() {
MessageDialog::new()
.set_type(native_dialog::MessageType::Error)
.set_title("Compatibility Error")
- .set_text("Your CPU does not support AVX instructions. Please use a compatible CPU.")
+ .set_text(
+ "Your CPU does not support AVX instructions. Please use a compatible CPU.",
+ )
.show_alert()
.unwrap();
std::process::exit(1);
@@ -25,7 +27,9 @@ pub fn check_cpu_compatibility() {
MessageDialog::new()
.set_type(native_dialog::MessageType::Error)
.set_title("Compatibility Error")
- .set_text("Your CPU does not support AVX2 instructions. Please use a compatible CPU.")
+ .set_text(
+ "Your CPU does not support AVX2 instructions. Please use a compatible CPU.",
+ )
.show_alert()
.unwrap();
std::process::exit(1);
diff --git a/src/model/wallet/asset_lock_transaction.rs b/src/model/wallet/asset_lock_transaction.rs
index 4b9d18d06..769e8b86c 100644
--- a/src/model/wallet/asset_lock_transaction.rs
+++ b/src/model/wallet/asset_lock_transaction.rs
@@ -16,13 +16,14 @@ impl Wallet {
&mut self,
network: Network,
amount: u64,
+ allow_take_fee_from_amount: bool,
identity_index: u32,
register_addresses: Option<&AppContext>,
) -> Result<
(
Transaction,
PrivateKey,
- Address,
+ Option
,
BTreeMap,
),
String,
@@ -37,53 +38,72 @@ impl Wallet {
let one_time_key_hash = asset_lock_public_key.pubkey_hash();
let fee = 3_000;
- let (utxos, change) = self
- .take_unspent_utxos_for(amount + fee)
+
+ let (utxos, change_option) = self
+ .take_unspent_utxos_for(amount, fee, allow_take_fee_from_amount)
.ok_or("take_unspent_utxos_for() returned None".to_string())?;
- let change_address = self.change_address(network, register_addresses)?;
+ let actual_amount = if change_option.is_none() && allow_take_fee_from_amount {
+ // The amount has been adjusted by taking the fee from the amount
+ // Calculate the adjusted amount based on the total value of the UTXOs minus the fee
+ let total_input_value: u64 = utxos.iter().map(|(_, (tx_out, _))| tx_out.value).sum();
+ total_input_value - fee
+ } else {
+ amount
+ };
let payload_output = TxOut {
- value: amount,
+ value: actual_amount,
script_pubkey: ScriptBuf::new_p2pkh(&one_time_key_hash),
};
let burn_output = TxOut {
- value: amount,
+ value: actual_amount,
script_pubkey: ScriptBuf::new_op_return(&[]),
};
- if change < fee {
- return Err("Change < Fee in asset_lock_transaction()".to_string());
- }
- let change_output = TxOut {
- value: change - fee,
- script_pubkey: change_address.script_pubkey(),
+
+ let (change_output, change_address) = if let Some(change) = change_option {
+ let change_address = self.change_address(network, register_addresses)?;
+ (
+ Some(TxOut {
+ value: change,
+ script_pubkey: change_address.script_pubkey(),
+ }),
+ Some(change_address),
+ )
+ } else {
+ (None, None)
};
+
let payload = AssetLockPayload {
version: 1,
credit_outputs: vec![payload_output],
};
- // we need to get all inputs from utxos to add them to the transaction
-
+ // Collect inputs from UTXOs
let inputs = utxos
.iter()
- .map(|(utxo, _)| {
- let mut tx_in = TxIn::default();
- tx_in.previous_output = utxo.clone();
- tx_in
+ .map(|(utxo, _)| TxIn {
+ previous_output: utxo.clone(),
+ ..Default::default()
})
.collect();
- let sighash_u32 = 1u32;
-
- let mut tx: Transaction = Transaction {
+ let mut tx = Transaction {
version: 3,
lock_time: 0,
input: inputs,
- output: vec![burn_output, change_output],
+ output: {
+ let mut outputs = vec![burn_output];
+ if let Some(change_output) = change_output {
+ outputs.push(change_output);
+ }
+ outputs
+ },
special_transaction_payload: Some(TransactionPayload::AssetLockPayloadType(payload)),
};
+ let sighash_u32 = 1u32;
+
let cache = SighashCache::new(&tx);
// Next, collect the sighashes for each input since that's what we need from the
diff --git a/src/model/wallet/mod.rs b/src/model/wallet/mod.rs
index 199c6eb78..d642115db 100644
--- a/src/model/wallet/mod.rs
+++ b/src/model/wallet/mod.rs
@@ -242,7 +242,11 @@ impl Wallet {
}
pub fn max_balance(&self) -> u64 {
- self.address_balances.values().sum::()
+ self.utxos
+ .values()
+ .map(|outpoints_to_tx_out| outpoints_to_tx_out.values().map(|tx_out| tx_out.value))
+ .flatten()
+ .sum::()
}
fn seed_bytes(&self) -> Result<&[u8; 64], String> {
diff --git a/src/model/wallet/utxos.rs b/src/model/wallet/utxos.rs
index 35e67b6b0..1ee13ccfe 100644
--- a/src/model/wallet/utxos.rs
+++ b/src/model/wallet/utxos.rs
@@ -8,11 +8,13 @@ impl Wallet {
pub fn take_unspent_utxos_for(
&mut self,
amount: u64,
- ) -> Option<(BTreeMap, u64)> {
+ fee: u64,
+ allow_take_fee_from_amount: bool,
+ ) -> Option<(BTreeMap, Option)> {
// Ensure UTXOs exist
let utxos = &mut self.utxos;
- let mut required: i64 = amount as i64;
+ let mut required: i64 = (amount + fee) as i64;
let mut taken_utxos = BTreeMap::new();
let mut utxos_to_remove = Vec::new();
@@ -31,23 +33,58 @@ impl Wallet {
}
}
- // If not enough UTXOs were found, return None
+ // If not enough UTXOs were found, try to adjust if allowed
if required > 0 {
- return None;
- }
-
- // Remove the collected UTXOs from the wallet's UTXO map
- for (address, outpoint) in utxos_to_remove {
- if let Some(outpoints) = utxos.get_mut(&address) {
- outpoints.remove(&outpoint);
- if outpoints.is_empty() {
- utxos.remove(&address);
+ if allow_take_fee_from_amount {
+ let total_collected = (amount + fee) as i64 - required;
+ if total_collected >= amount as i64 {
+ // We have enough to cover the amount, but not the fee
+ // So we can reduce the amount by the missing fee
+ let missing_fee = required; // required > 0
+ let adjusted_amount = amount as i64 - missing_fee;
+ if adjusted_amount <= 0 {
+ // Cannot adjust amount to cover missing fee
+ return None;
+ }
+ // Remove UTXOs from wallet
+ for (address, outpoint) in utxos_to_remove {
+ if let Some(outpoints) = utxos.get_mut(&address) {
+ outpoints.remove(&outpoint);
+ if outpoints.is_empty() {
+ utxos.remove(&address);
+ }
+ }
+ }
+ // Return collected UTXOs and None for change
+ Some((taken_utxos, None))
+ } else {
+ // Not enough to cover amount even after adjusting
+ return None;
}
+ } else {
+ // Not enough UTXOs and not allowed to take fee from amount
+ return None;
}
- }
+ } else {
+ // Remove the collected UTXOs from the wallet's UTXO map
+ for (address, outpoint) in utxos_to_remove {
+ if let Some(outpoints) = utxos.get_mut(&address) {
+ outpoints.remove(&outpoint);
+ if outpoints.is_empty() {
+ utxos.remove(&address);
+ }
+ }
+ }
+ // Calculate change amount
+ let total_input = (amount + fee) as i64 - required; // total input collected
+ let change = total_input as u64 - amount - fee;
- // Return the collected UTXOs and the remaining amount (which should be zero or positive)
- Some((taken_utxos, required.abs() as u64))
+ // If change is zero, return None
+ let change_option = if change > 0 { Some(change) } else { None };
+
+ // Return the collected UTXOs and the change amount
+ Some((taken_utxos, change_option))
+ }
}
pub fn reload_utxos(
diff --git a/src/ui/identities/add_new_identity_screen/by_using_unused_balance.rs b/src/ui/identities/add_new_identity_screen/by_using_unused_balance.rs
index 4ded5f9b3..3d67aea6e 100644
--- a/src/ui/identities/add_new_identity_screen/by_using_unused_balance.rs
+++ b/src/ui/identities/add_new_identity_screen/by_using_unused_balance.rs
@@ -30,13 +30,15 @@ impl AddNewIdentityScreen {
self.show_wallet_balance(ui);
- step_number += 1;
+ ui.add_space(10.0);
ui.heading(format!(
"{}. How much of your wallet balance would you like to transfer?",
step_number
));
+ step_number += 1;
+
self.render_funding_amount_input(ui);
// Extract the step from the RwLock to minimize borrow scope
diff --git a/src/ui/identities/add_new_identity_screen/mod.rs b/src/ui/identities/add_new_identity_screen/mod.rs
index 3eff547cd..e99943dc4 100644
--- a/src/ui/identities/add_new_identity_screen/mod.rs
+++ b/src/ui/identities/add_new_identity_screen/mod.rs
@@ -517,19 +517,24 @@ impl AddNewIdentityScreen {
*step = AddNewIdentityWalletFundedScreenStep::ReadyToCreate;
}
}
- // if has_balance {
- // if ui
- // .selectable_value(
- // &mut *funding_method,
- // FundingMethod::UseWalletBalance,
- // "Use Wallet Balance",
- // )
- // .changed()
- // {
- // let mut step = self.step.write().unwrap(); // Write lock on step
- // *step = AddNewIdentityWalletFundedScreenStep::ReadyToCreate;
- // }
- // }
+ if has_balance {
+ if ui
+ .selectable_value(
+ &mut *funding_method,
+ FundingMethod::UseWalletBalance,
+ "Use Wallet Balance",
+ )
+ .changed()
+ {
+ if let Some(wallet) = &self.selected_wallet {
+ let wallet = wallet.read().unwrap(); // Read lock on the wallet
+ let max_amount = wallet.max_balance();
+ self.funding_amount = format!("{:.4}", max_amount as f64 * 1e-8);
+ }
+ let mut step = self.step.write().unwrap(); // Write lock on step
+ *step = AddNewIdentityWalletFundedScreenStep::ReadyToCreate;
+ }
+ }
if ui
.selectable_value(
&mut *funding_method,
diff --git a/src/ui/identities/withdraw_from_identity_screen.rs b/src/ui/identities/withdraw_from_identity_screen.rs
index f51738ef4..b2e389545 100644
--- a/src/ui/identities/withdraw_from_identity_screen.rs
+++ b/src/ui/identities/withdraw_from_identity_screen.rs
@@ -105,7 +105,7 @@ impl WithdrawalScreen {
ui.text_edit_singleline(&mut self.withdrawal_amount);
if ui.button("Max").clicked() {
- let expected_max_amount = self.max_amount.saturating_sub(5000000) as f64 * 1e-8;
+ let expected_max_amount = self.max_amount.saturating_sub(5000000) as f64 * 1e-11;
// Use flooring and format the result with 4 decimal places
let floored_amount = (expected_max_amount * 10_000.0).floor() / 10_000.0;
diff --git a/src/ui/wallet/wallets_screen/mod.rs b/src/ui/wallet/wallets_screen/mod.rs
index 94a267b6e..16d05b1b4 100644
--- a/src/ui/wallet/wallets_screen/mod.rs
+++ b/src/ui/wallet/wallets_screen/mod.rs
@@ -392,7 +392,7 @@ impl WalletsBalancesScreen {
.resizable(true)
.cell_layout(egui::Layout::left_to_right(egui::Align::Center))
.column(Column::auto()) // Address
- // .column(Column::initial(100.0)) // Balance
+ .column(Column::initial(100.0)) // Balance
.column(Column::initial(60.0)) // UTXOs
.column(Column::initial(150.0)) // Total Received
.column(Column::initial(100.0)) // Type
@@ -412,19 +412,19 @@ impl WalletsBalancesScreen {
self.toggle_sort(SortColumn::Address);
}
});
- // header.col(|ui| {
- // let label = if self.sort_column == SortColumn::Balance {
- // match self.sort_order {
- // SortOrder::Ascending => "Balance (DASH) ^",
- // SortOrder::Descending => "Balance (DASH) v",
- // }
- // } else {
- // "Balance (DASH)"
- // };
- // if ui.button(label).clicked() {
- // self.toggle_sort(SortColumn::Balance);
- // }
- // });
+ header.col(|ui| {
+ let label = if self.sort_column == SortColumn::Balance {
+ match self.sort_order {
+ SortOrder::Ascending => "Total Received (DASH) ^",
+ SortOrder::Descending => "Total Received (DASH) v",
+ }
+ } else {
+ "Total Received (DASH)"
+ };
+ if ui.button(label).clicked() {
+ self.toggle_sort(SortColumn::Balance);
+ }
+ });
header.col(|ui| {
let label = if self.sort_column == SortColumn::UTXOs {
match self.sort_order {
@@ -497,10 +497,10 @@ impl WalletsBalancesScreen {
row.col(|ui| {
ui.label(data.address.to_string());
});
- // row.col(|ui| {
- // let dash_balance = data.balance as f64 * 1e-8;
- // ui.label(format!("{:.8}", dash_balance));
- // });
+ row.col(|ui| {
+ let dash_balance = data.balance as f64 * 1e-8;
+ ui.label(format!("{:.8}", dash_balance));
+ });
row.col(|ui| {
ui.label(format!("{}", data.utxo_count));
});