Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/platform/contested_names/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod vote_on_dpns_name;

use crate::app::TaskResult;
use crate::context::AppContext;
use crate::model::qualified_identity::QualifiedIdentity;
use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice;
use dash_sdk::Sdk;
use std::sync::Arc;
Expand All @@ -14,7 +15,7 @@ use tokio::sync::mpsc;
pub(crate) enum ContestedResourceTask {
QueryDPNSContestedResources,
QueryDPNSVoteContenders(String),
VoteOnDPNSName(String, ResourceVoteChoice),
VoteOnDPNSName(String, ResourceVoteChoice, Vec<QualifiedIdentity>),
}

impl AppContext {
Expand All @@ -32,8 +33,8 @@ impl AppContext {
ContestedResourceTask::QueryDPNSVoteContenders(name) => {
self.query_dpns_vote_contenders(name, sdk, sender).await
}
ContestedResourceTask::VoteOnDPNSName(name, vote_choice) => {
self.vote_on_dpns_name(name, *vote_choice, sdk, sender)
ContestedResourceTask::VoteOnDPNSName(name, vote_choice, voters) => {
self.vote_on_dpns_name(name, *vote_choice, voters.to_vec(), sdk, sender)
.await
} // ContestedResourceTask::VoteOnContestedResource(vote_poll, vote_choice) => {
// let mut vote = Vote::default();
Expand Down
25 changes: 20 additions & 5 deletions src/platform/contested_names/vote_on_dpns_name.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::app::TaskResult;
use crate::context::AppContext;
use crate::model::qualified_identity::QualifiedIdentity;
use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters;
use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters;
use dash_sdk::dpp::identity::accessors::IdentityGettersV0;
Expand All @@ -19,34 +20,42 @@ impl AppContext {
self: &Arc<Self>,
name: &String,
vote_choice: ResourceVoteChoice,
voters: Vec<QualifiedIdentity>,
sdk: Sdk,
sender: mpsc::Sender<TaskResult>,
_sender: mpsc::Sender<TaskResult>,
) -> Result<(), String> {
let qualified_identities = self.load_local_qualified_identities().unwrap_or_default();

// Fetch DPNS contract and document type information
let data_contract = self.dpns_contract.as_ref();
let document_type = data_contract
.document_type_for_name("domain")
.expect("expected document type");

let Some(contested_index) = document_type.find_contested_index() else {
return Err("No contested index on dpns domains".to_string());
};
let index_values = [Value::from("dash"), Value::Text(name.clone())]; // hardcoded for dpns

// Hardcoded values for DPNS
let index_values = [Value::from("dash"), Value::Text(name.clone())];

// Create the vote poll to use in the vote
let vote_poll = ContestedDocumentResourceVotePoll {
index_name: contested_index.name.clone(),
index_values: index_values.to_vec(),
document_type_name: document_type.name().to_string(),
contract_id: data_contract.id(),
};

for qualified_identity in qualified_identities.iter().take(1) {
// Iterate over the provided voters (QualifiedIdentity)
for qualified_identity in voters.iter() {
if let Some((_, public_key)) = &qualified_identity.associated_voter_identity {
// Create the resource vote
let resource_vote = ResourceVoteV0 {
vote_poll: vote_poll.clone().into(),
resource_vote_choice: vote_choice,
};
let vote = Vote::ResourceVote(ResourceVote::V0(resource_vote));

// Submit the vote to the platform and await a response
vote.put_to_platform_and_wait_for_response(
qualified_identity.identity.id(),
public_key,
Expand All @@ -56,8 +65,14 @@ impl AppContext {
)
.await
.map_err(|e| format!("Error voting: {}", e))?;
} else {
return Err(format!(
"No associated voter identity for qualified identity: {:?}",
qualified_identity.identity.id()
));
}
}

Ok(())
}
}
1 change: 1 addition & 0 deletions src/ui/document_query_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ impl DocumentQueryScreen {
ContestedResourceTask::VoteOnDPNSName(
contested_name.normalized_contested_name.clone(),
ResourceVoteChoice::Abstain,
vec![],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Masternode selection UI is not implemented.

The addition of vec![] as the third parameter to ContestedResourceTask::VoteOnDPNSName suggests that masternode selection functionality is intended. However, no UI components for selecting masternodes were found in the codebase. This may result in users being unable to select specific masternodes for voting as intended.

  • Implement the UI for masternode selection to enable users to choose specific masternodes.
  • Ensure that the selection process populates the vector passed to VoteOnDPNSName.
🔗 Analysis chain

Verify the implementation of masternode selection for voting.

The addition of vec![] as the third parameter to ContestedResourceTask::VoteOnDPNSName aligns with the PR objective of allowing users to select specific masternodes for voting. However, there are a few points to consider:

  1. The empty vector suggests that no masternodes are selected by default. Is this the intended behavior?
  2. There's no visible UI element in this file for selecting masternodes. Ensure that the masternode selection is implemented correctly in the relevant UI component.

Consider the following improvements:

  • If a default selection is desired, populate the vector with appropriate default values.
  • Add a comment explaining the purpose of this parameter for better code readability.
  • Verify that the masternode selection UI is properly integrated with this voting action.

To ensure the feature is fully implemented, let's check for the presence of masternode selection UI and its integration:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for UI components related to masternode selection
rg --type rust "fn.*select.*masternode" src
# Check for updates to the ContestedResourceTask enum
rg --type rust "enum ContestedResourceTask" src
# Verify the usage of VoteOnDPNSName with the new parameter
rg --type rust "VoteOnDPNSName.*vec!" src

Length of output: 999

),
));
}
Expand Down
108 changes: 91 additions & 17 deletions src/ui/dpns_contested_names_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ use crate::ui::components::top_panel::add_top_panel;
use crate::ui::{MessageType, RootScreenType, ScreenLike};
use chrono::{DateTime, LocalResult, TimeZone, Utc};
use chrono_humanize::HumanTime;
use dash_sdk::dpp::identity::accessors::IdentityGettersV0;
use dash_sdk::dpp::platform_value::string_encoding::Encoding;
use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice;
use egui::{Context, Frame, Margin, Ui};
use egui_extras::{Column, TableBuilder};
use itertools::Itertools;
use std::sync::{Arc, Mutex};

use super::ScreenType;
Expand All @@ -36,7 +39,7 @@ pub struct DPNSContestedNamesScreen {
error_message: Option<(String, MessageType, DateTime<Utc>)>,
sort_column: SortColumn,
sort_order: SortOrder,
show_vote_popup: Option<(String, ContestedResourceTask)>,
show_vote_popup_info: Option<(String, ContestedResourceTask)>,
}

impl DPNSContestedNamesScreen {
Expand All @@ -50,7 +53,7 @@ impl DPNSContestedNamesScreen {
error_message: None,
sort_column: SortColumn::ContestedName,
sort_order: SortOrder::Ascending,
show_vote_popup: None,
show_vote_popup_info: None,
}
}

Expand All @@ -75,14 +78,14 @@ impl DPNSContestedNamesScreen {
};

if ui.button(text).clicked() {
self.show_vote_popup = Some((
self.show_vote_popup_info = Some((
format!(
"Confirm Voting for Contestant {} for name \"{}\"",
"Confirm Voting for Contestant {} for name \"{}\".\n\nSelect the identity to vote with:",
contestant.id, contestant.name
),
ContestedResourceTask::VoteOnDPNSName(
contested_name.normalized_contested_name.clone(),
ResourceVoteChoice::TowardsIdentity(contestant.id),
ResourceVoteChoice::TowardsIdentity(contestant.id),vec![]
),
));
}
Expand Down Expand Up @@ -140,24 +143,95 @@ impl DPNSContestedNamesScreen {

fn show_vote_popup(&mut self, ui: &mut Ui) -> AppAction {
let mut app_action = AppAction::None;
if let Some((message, action)) = self.show_vote_popup.clone() {

if let Some((message, action)) = self.show_vote_popup_info.clone() {
ui.label(message);

let local_qualified_identities = self
.app_context
.db
.get_local_qualified_identities(&self.app_context)
.unwrap_or_default();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle potential errors when fetching local qualified identities

Currently, errors from get_local_qualified_identities are ignored with unwrap_or_default(), which may mask underlying issues. Consider handling the Result properly to ensure robustness.

Here's a suggested change:

 let local_qualified_identities = self
     .app_context
     .db
     .get_local_qualified_identities(&self.app_context)
-    .unwrap_or_default();
+    .unwrap_or_else(|err| {
+        // Handle the error, e.g., log it or display a message
+        eprintln!("Error fetching identities: {:?}", err);
+        Vec::new()
+    });

You might also consider displaying an error message to the user if fetching identities fails.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let local_qualified_identities = self
.app_context
.db
.get_local_qualified_identities(&self.app_context)
.unwrap_or_default();
let local_qualified_identities = self
.app_context
.db
.get_local_qualified_identities(&self.app_context)
.unwrap_or_else(|err| {
// Handle the error, e.g., log it or display a message
eprintln!("Error fetching identities: {:?}", err);
Vec::new()
});

let voting_identities = local_qualified_identities
.iter()
.filter_map(|id| {
if id.associated_voter_identity.is_some() {
Some(id)
} else {
None
}
})
.collect_vec();

ui.horizontal(|ui| {
if ui.button("Vote Immediate").clicked() {
app_action = AppAction::BackendTask(BackendTask::ContestedResourceTask(action));
self.show_vote_popup = None;
} else if ui.button("Vote Deferred").clicked() {
app_action = AppAction::BackendTask(BackendTask::ContestedResourceTask(action));
self.show_vote_popup = None;
} else if ui.button("Cancel").clicked() {
self.show_vote_popup = None;
// Only modify `voters` if `action` is `VoteOnDPNSName`
if let ContestedResourceTask::VoteOnDPNSName(
contested_name,
vote_choice,
mut voters,
) = action
{
// Iterate over the voting identities and create a button for each one
for identity in voting_identities.iter() {
let button_label = format!(
"{}",
identity
.alias
.clone()
.unwrap_or(identity.identity.id().to_string(Encoding::Base58))
);
if ui.button(button_label).clicked() {
// Add the selected identity to the `voters` field
voters.push(identity.clone().clone());

// Create a new `VoteOnDPNSName` task with updated voters
let updated_action = ContestedResourceTask::VoteOnDPNSName(
contested_name.clone(),
vote_choice.clone(),
voters.clone(), // Updated voters
);

// Pass updated action to BackendTask
app_action = AppAction::BackendTask(
BackendTask::ContestedResourceTask(updated_action),
);
self.show_vote_popup_info = None;
}
}

// Vote with all identities
if ui.button("All").clicked() {
for identity in voting_identities.iter() {
voters.push(identity.clone().clone());
}

// Create a new `VoteOnDPNSName` task with all voters
let updated_action = ContestedResourceTask::VoteOnDPNSName(
contested_name.clone(),
vote_choice.clone(),
voters.clone(), // Updated voters
);

// Pass updated action to BackendTask
app_action = AppAction::BackendTask(BackendTask::ContestedResourceTask(
updated_action,
));
self.show_vote_popup_info = None;
}
}

// Add the "Cancel" button
if ui.button("Cancel").clicked() {
self.show_vote_popup_info = None;
}
});
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Check for empty voting identities and handle accordingly

If voting_identities is empty, the UI will not display any buttons for the user to select an identity, potentially causing confusion.

Consider adding a message to inform the user when no voting identities are available:

if voting_identities.is_empty() {
    ui.label("No voting identities available to vote with.");
} else {
    // Existing code to display voting buttons
}

app_action
}
}

impl ScreenLike for DPNSContestedNamesScreen {
fn refresh(&mut self) {
let mut contested_names = self.contested_names.lock().unwrap();
Expand Down Expand Up @@ -231,7 +305,7 @@ impl ScreenLike for DPNSContestedNamesScreen {
}

// Show vote popup if active
if self.show_vote_popup.is_some() {
if self.show_vote_popup_info.is_some() {
egui::Window::new("Vote Confirmation")
.collapsible(false)
.show(ui.ctx(), |ui| {
Expand Down Expand Up @@ -328,7 +402,7 @@ impl ScreenLike for DPNSContestedNamesScreen {
};
// Vote button logic for locked votes
if ui.button(label_text).clicked() {
self.show_vote_popup = Some((format!("Confirm Voting to Lock the name \"{}\"", contested_name.normalized_contested_name.clone()), ContestedResourceTask::VoteOnDPNSName(contested_name.normalized_contested_name.clone(), ResourceVoteChoice::Lock)));
self.show_vote_popup_info = Some((format!("Confirm Voting to Lock the name \"{}\".\n\nSelect the identity to vote with:", contested_name.normalized_contested_name.clone()), ContestedResourceTask::VoteOnDPNSName(contested_name.normalized_contested_name.clone(), ResourceVoteChoice::Lock, vec![])));
}
});
row.col(|ui| {
Expand All @@ -340,7 +414,7 @@ impl ScreenLike for DPNSContestedNamesScreen {
"Fetching".to_string()
};
if ui.button(label_text).clicked() {
self.show_vote_popup = Some((format!("Confirm Voting to Abstain on distribution of \"{}\"", contested_name.normalized_contested_name.clone()), ContestedResourceTask::VoteOnDPNSName(contested_name.normalized_contested_name.clone(), ResourceVoteChoice::Abstain)));
self.show_vote_popup_info = Some((format!("Confirm Voting to Abstain on distribution of \"{}\".\n\nSelect the identity to vote with:", contested_name.normalized_contested_name.clone()), ContestedResourceTask::VoteOnDPNSName(contested_name.normalized_contested_name.clone(), ResourceVoteChoice::Abstain, vec![])));
}
});
row.col(|ui| {
Expand Down