Repository navigation
feat: fund with wallet balance #92
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<Address>, | ||
| BTreeMap<OutPoint, (TxOut, Address)>, | ||
| ), | ||
| 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 | ||
| }, | ||
|
Comment on lines
+95
to
+101
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The transaction outputs currently include Apply this diff to include let mut outputs = vec![burn_output];
+ outputs.push(payload_output);
if let Some(change_output) = change_output {
outputs.push(change_output);
}
|
||
| 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 | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,11 +8,13 @@ impl Wallet { | |
| pub fn take_unspent_utxos_for( | ||
| &mut self, | ||
| amount: u64, | ||
| ) -> Option<(BTreeMap<OutPoint, (TxOut, Address)>, u64)> { | ||
| fee: u64, | ||
| allow_take_fee_from_amount: bool, | ||
| ) -> Option<(BTreeMap<OutPoint, (TxOut, Address)>, Option<u64>)> { | ||
| // Ensure UTXOs exist | ||
| let utxos = &mut self.utxos; | ||
|
|
||
| let mut required: i64 = amount as i64; | ||
| let mut required: i64 = (amount + fee) as i64; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Avoid casting from Casting Apply the following changes to use - let mut required: i64 = (amount + fee) as i64;
+ let mut required: u128 = amount + fee as u128;
...
- required -= tx_out.value as i64;
+ required = required.saturating_sub(tx_out.value as u64);
...
- if required > 0 {
+ if required > 0 {
...
- let total_collected = (amount + fee) as i64 - required;
+ let total_collected = (amount + fee) as u128 - required;
...
- let adjusted_amount = amount as i64 - missing_fee;
+ let adjusted_amount = amount as u128 - missing_fee;
...
- let total_input = (amount + fee) as i64 - required;
+ let total_input = (amount + fee) as u128 - required;
...
// Adjust all subsequent calculations and conditionals to use `u128`.Also applies to: 28-28, 39-39, 44-44, 79-79 |
||
| 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( | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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; | ||
| } | ||
| } | ||
|
Comment on lines
+520
to
+537
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Consider improving wallet balance handling and validation. The wallet balance funding implementation could be enhanced in several ways:
Consider applying these improvements: 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();
let max_amount = wallet.max_balance();
- self.funding_amount = format!("{:.4}", max_amount as f64 * 1e-8);
+ // Reserve some balance for transaction fees
+ let reserved_for_fees = 1_000_000; // 0.01 DASH
+ let available_amount = max_amount.saturating_sub(reserved_for_fees);
+ const SATS_PER_DASH: f64 = 100_000_000.0;
+ self.funding_amount = format!("{}", available_amount as f64 / SATS_PER_DASH);
}
let mut step = self.step.write().unwrap();
*step = AddNewIdentityWalletFundedScreenStep::ReadyToCreate;
}
}
|
||
| if ui | ||
| .selectable_value( | ||
| &mut *funding_method, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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); | ||
| } | ||
| }); | ||
|
Comment on lines
+415
to
+427
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix inconsistencies in column headers and sorting logic There are several issues in the column header implementation:
Consider applying these changes: - let label = if self.sort_column == SortColumn::Balance {
+ let label = if self.sort_column == SortColumn::Balance {
match self.sort_order {
- SortOrder::Ascending => "Total Received (DASH) ^",
- SortOrder::Descending => "Total Received (DASH) v",
+ SortOrder::Ascending => "Balance (DASH) ^",
+ SortOrder::Descending => "Balance (DASH) v",
}
} else {
- "Total Received (DASH)"
+ "Balance (DASH)"
};Also, consider updating the enum SortColumn {
Address,
- Balance,
+ CurrentBalance,
UTXOs,
TotalReceived,
// ... rest of the enum
}
|
||
| 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)); | ||
| }); | ||
|
Comment on lines
+500
to
+503
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Improve balance conversion implementation The current implementation has several potential issues:
Consider implementing a dedicated conversion function: + const DUFFS_PER_DASH: f64 = 1e8;
+
+ /// Converts an amount from Duffs to DASH
+ /// Returns None if the conversion would overflow
+ fn duffs_to_dash(duffs: u64) -> Option<f64> {
+ let dash = (duffs as f64) / DUFFS_PER_DASH;
+ if dash.is_finite() {
+ Some(dash)
+ } else {
+ None
+ }
+ }
+
row.col(|ui| {
- let dash_balance = data.balance as f64 * 1e-8;
- ui.label(format!("{:.8}", dash_balance));
+ match duffs_to_dash(data.balance) {
+ Some(dash_balance) => ui.label(format!("{:.8}", dash_balance)),
+ None => ui.label("Error: Invalid balance"),
+ }
});
|
||
| row.col(|ui| { | ||
| ui.label(format!("{}", data.utxo_count)); | ||
| }); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ensure
total_input_valueis greater than or equal tofeeto prevent underflowWhen calculating
actual_amount, iftotal_input_valueis less thanfee, subtractingfeecould cause an underflow. Consider adding a check to ensuretotal_input_value >= feebefore performing the subtraction.Apply this diff to add the check:
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(); + if total_input_value < fee { + return Err("Total input value is less than the fee.".to_string()); + } total_input_value - fee } else { amount };📝 Committable suggestion