Skip to content
Binary file added icons/withdraws.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::ui::dpns_contested_names_screen::DPNSContestedNamesScreen;
use crate::ui::identities::identities_screen::IdentitiesScreen;
use crate::ui::network_chooser_screen::NetworkChooserScreen;
use crate::ui::transition_visualizer_screen::TransitionVisualizerScreen;
use crate::ui::withdraws_status_screen::WithdrawsStatusScreen;
use crate::ui::{MessageType, RootScreenType, Screen, ScreenLike, ScreenType};
use dash_sdk::dpp::dashcore::Network;
use derive_more::From;
Expand Down Expand Up @@ -120,6 +121,7 @@ impl AppState {
let mut transition_visualizer_screen =
TransitionVisualizerScreen::new(&mainnet_app_context);
let mut document_query_screen = DocumentQueryScreen::new(&mainnet_app_context);
let mut withdraws_status_screen = WithdrawsStatusScreen::new(&mainnet_app_context);
let mut network_chooser_screen = NetworkChooserScreen::new(
&mainnet_app_context,
testnet_app_context.as_ref(),
Expand All @@ -139,6 +141,7 @@ impl AppState {
dpns_contested_names_screen = DPNSContestedNamesScreen::new(testnet_app_context);
transition_visualizer_screen = TransitionVisualizerScreen::new(testnet_app_context);
document_query_screen = DocumentQueryScreen::new(testnet_app_context);
withdraws_status_screen = WithdrawsStatusScreen::new(testnet_app_context);
}
network_chooser_screen.current_network = chosen_network;
}
Expand Down Expand Up @@ -167,6 +170,10 @@ impl AppState {
RootScreenType::RootScreenDocumentQuery,
Screen::DocumentQueryScreen(document_query_screen),
),
(
RootScreenType::RootScreenWithdrawsStatus,
Screen::WithdrawsStatusScreen(withdraws_status_screen),
),
(
RootScreenType::RootScreenNetworkChooser,
Screen::NetworkChooserScreen(network_chooser_screen),
Expand Down Expand Up @@ -279,6 +286,9 @@ impl App for AppState {
BackendTaskSuccessResult::SuccessfulVotes(_) => {
self.visible_screen_mut().refresh();
}
BackendTaskSuccessResult::WithdrawalStatus(_) => {
self.visible_screen_mut().display_task_result(message);
}
Comment thread
ogabrielides marked this conversation as resolved.
Resolved
},
TaskResult::Error(message) => {
self.visible_screen_mut()
Expand Down
6 changes: 6 additions & 0 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub struct AppContext {
pub(crate) sdk: Sdk,
pub(crate) config: NetworkConfig,
pub(crate) dpns_contract: Arc<DataContract>,
pub(crate) withdraws_contract: Arc<DataContract>,
pub(crate) core_client: Client,
pub(crate) has_wallet: AtomicBool,
pub(crate) wallets: RwLock<Vec<Arc<RwLock<Wallet>>>>,
Expand Down Expand Up @@ -55,6 +56,10 @@ impl AppContext {
load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest())
.expect("expected to load dpns contract");

let withdrawal_contract =
load_system_data_contract(SystemDataContract::Withdrawals, PlatformVersion::latest())
.expect("expected to get withdrawal contract");

Comment thread
ogabrielides marked this conversation as resolved.
Resolved
let addr = format!(
"http://{}:{}",
network_config.core_host, network_config.core_rpc_port
Expand Down Expand Up @@ -83,6 +88,7 @@ impl AppContext {
sdk,
config: network_config,
dpns_contract: Arc::new(dpns_contract),
withdraws_contract: Arc::new(withdrawal_contract),
core_client,
has_wallet: (!wallets.is_empty()).into(),
wallets: RwLock::new(wallets),
Expand Down
7 changes: 7 additions & 0 deletions src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::platform::contract::ContractTask;
use crate::platform::core::{CoreItem, CoreTask};
use crate::platform::document::DocumentTask;
use crate::platform::identity::IdentityTask;
use crate::platform::withdrawals::{WithdrawStatusData, WithdrawalsTask};
use dash_sdk::dpp::voting::votes::Vote;
use dash_sdk::query_types::Documents;
use std::sync::Arc;
Expand All @@ -15,6 +16,7 @@ pub mod contract;
pub mod core;
mod document;
pub mod identity;
pub mod withdrawals;

#[derive(Debug, Clone, PartialEq)]
pub(crate) enum BackendTask {
Expand All @@ -23,6 +25,7 @@ pub(crate) enum BackendTask {
ContractTask(ContractTask),
ContestedResourceTask(ContestedResourceTask),
CoreTask(CoreTask),
WithdrawalTask(WithdrawalsTask),
}

#[derive(Debug, Clone, PartialEq)]
Expand All @@ -32,6 +35,7 @@ pub(crate) enum BackendTaskSuccessResult {
Documents(Documents),
CoreItem(CoreItem),
SuccessfulVotes(Vec<Vote>),
WithdrawalStatus(WithdrawStatusData),
}

impl BackendTaskSuccessResult {}
Expand Down Expand Up @@ -71,6 +75,9 @@ impl AppContext {
self.run_document_task(document_task, &sdk).await
}
BackendTask::CoreTask(core_task) => self.run_core_task(core_task).await,
BackendTask::WithdrawalTask(withdrawal_task) => {
self.run_withdraws_task(withdrawal_task, &sdk, sender).await
}
}
}
}
202 changes: 202 additions & 0 deletions src/platform/withdrawals/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
use std::sync::Arc;
use chrono::{DateTime, Local, Utc};
use dash_sdk::dashcore_rpc::dashcore::{Address, Network, ScriptBuf};
use dash_sdk::dpp::data_contracts::withdrawals_contract::v1::document_types::withdrawal::properties::{AMOUNT, OUTPUT_SCRIPT, STATUS};
use dash_sdk::dpp::data_contracts::withdrawals_contract::WithdrawalStatus;
use dash_sdk::dpp::document::DocumentV0Getters;
use dash_sdk::dpp::fee::Credits;
use dash_sdk::dpp::platform_value::btreemap_extensions::BTreeValueMapHelper;
use dash_sdk::dpp::platform_value::Value;
use dash_sdk::dpp::version::PlatformVersion;
use dash_sdk::dpp::withdrawal::daily_withdrawal_limit::daily_withdrawal_limit;
use dash_sdk::drive::drive::RootTree;
use dash_sdk::drive::grovedb::Element;
use dash_sdk::drive::grovedb::element::SumValue;
use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator};
use dash_sdk::platform::{Document, DocumentQuery, FetchMany, Identifier};
use dash_sdk::platform::fetch_current_no_parameters::FetchCurrent;
use dash_sdk::query_types::{KeysInPath, TotalCreditsInPlatform};
use dash_sdk::Sdk;
use tokio::sync::mpsc;
use crate::app::TaskResult;
use crate::context::AppContext;
use crate::platform::BackendTaskSuccessResult;

/// constant key for transaction counter
pub const WITHDRAWAL_TRANSACTIONS_NEXT_INDEX_KEY: [u8; 1] = [0];
/// constant id for subtree containing transactions queue
pub const WITHDRAWAL_TRANSACTIONS_QUEUE_KEY: [u8; 1] = [1];
/// constant id for subtree containing the sum of withdrawals
pub const WITHDRAWAL_TRANSACTIONS_SUM_AMOUNT_TREE_KEY: [u8; 1] = [2];
/// constant id for subtree containing the untied withdrawal transactions after they were broadcasted
pub const WITHDRAWAL_TRANSACTIONS_BROADCASTED_KEY: [u8; 1] = [3];

#[derive(Debug, Clone, PartialEq)]
pub(crate) enum WithdrawalsTask {
QueryWithdrawals,
}

#[derive(Debug, Clone, PartialEq)]
pub struct WithdrawRecord {
pub date_time: DateTime<Local>,
pub status: WithdrawalStatus,
pub amount: Credits,
pub owner_id: Identifier,
pub address: Address,
}

#[derive(Debug, Clone, PartialEq)]
pub struct WithdrawStatusData {
pub withdrawals: Vec<WithdrawRecord>,
pub total_amount: Credits,
pub recent_withdrawal_amounts: SumValue,
pub daily_withdrawal_limit: Credits,
pub total_credits_on_platform: Credits,
}
Comment thread
ogabrielides marked this conversation as resolved.
Resolved

impl AppContext {
pub async fn run_withdraws_task(
self: &Arc<Self>,
task: WithdrawalsTask,
sdk: &Sdk,
sender: mpsc::Sender<TaskResult>,
) -> Result<BackendTaskSuccessResult, String> {
Comment thread
ogabrielides marked this conversation as resolved.
Resolved
let sdk = sdk.clone();
match &task {
WithdrawalsTask::QueryWithdrawals => self.query_withdrawals(sdk, sender).await,
}
}

pub(super) async fn query_withdrawals(
self: &Arc<Self>,
sdk: Sdk,
sender: mpsc::Sender<TaskResult>,
) -> Result<BackendTaskSuccessResult, String> {
Comment thread
ogabrielides marked this conversation as resolved.
Resolved
Comment on lines +61 to +67

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.

🛠️ Refactor suggestion

Consider implementing custom error types instead of using String.

Converting all errors to strings loses type information and makes error handling less robust. Consider implementing a custom error type using thiserror or similar.

Example implementation:

#[derive(Debug, thiserror::Error)]
pub enum WithdrawalError {
    #[error("SDK error: {0}")]
    SdkError(#[from] dash_sdk::Error),
    #[error("Missing sum tree value")]
    MissingSumTreeValue,
    #[error("Invalid withdrawal data: {0}")]
    InvalidData(String),
}

Then update the return type:

-    ) -> Result<BackendTaskSuccessResult, String> {
+    ) -> Result<BackendTaskSuccessResult, WithdrawalError> {

let queued_document_query = DocumentQuery {
data_contract: self.withdraws_contract.clone(),
document_type_name: "withdrawal".to_string(),
where_clauses: vec![WhereClause {
field: "status".to_string(),
operator: WhereOperator::In,
value: Value::Array(vec![
Value::U8(WithdrawalStatus::QUEUED as u8),
Value::U8(WithdrawalStatus::POOLED as u8),
Value::U8(WithdrawalStatus::BROADCASTED as u8),
]),
}],
order_by_clauses: vec![
OrderClause {
field: "status".to_string(),
ascending: true,
},
OrderClause {
field: "transactionIndex".to_string(),
ascending: true,
},
],
limit: 100,
start: None,
};

match Document::fetch_many(&sdk, queued_document_query.clone()).await {
Ok(documents) => {
let keys_in_path = KeysInPath {
path: vec![vec![RootTree::WithdrawalTransactions as u8]],
keys: vec![WITHDRAWAL_TRANSACTIONS_SUM_AMOUNT_TREE_KEY.to_vec()],
};
match Element::fetch_many(&sdk, keys_in_path).await {
Ok(elements) => {
if let Some(Some(Element::SumTree(_, value, _))) =
elements.get(&WITHDRAWAL_TRANSACTIONS_SUM_AMOUNT_TREE_KEY.to_vec())
{
match TotalCreditsInPlatform::fetch_current(&sdk).await {
Ok(total_credits) => {
Ok(BackendTaskSuccessResult::WithdrawalStatus(
util_transform_withdrawal_documents_to_bare_info(
*value,
total_credits.0,
&documents.values().filter_map(|a| a.clone()).collect(),
sdk.network,
),
))
}
Err(e) => Err(e.to_string()),
}
} else {
Err(
"could not get sum tree value for current withdrawal maximum"
.to_string(),
)
}
}
Err(e) => Err(e.to_string()),
}
}
Err(e) => Err(e.to_string()),
}
}
Comment thread
ogabrielides marked this conversation as resolved.
Resolved
}

fn util_transform_withdrawal_documents_to_bare_info(
recent_withdrawal_amounts: SumValue,
total_credits_on_platform: Credits,
withdrawal_documents: &Vec<Document>,
network: Network,
) -> WithdrawStatusData {
let total_amount: Credits = withdrawal_documents
.iter()
.map(|document| {
document
.properties()
.get_integer::<Credits>(AMOUNT)
.expect("expected amount on withdrawal")
})
.sum();
let mut vec_withdraws = vec![];
for document in withdrawal_documents.iter() {
let index = document.created_at().expect("expected created at");
// Convert the timestamp to a DateTime in UTC
let utc_datetime =
DateTime::<Utc>::from_timestamp_millis(index as i64).expect("expected date time");
Comment thread
ogabrielides marked this conversation as resolved.
Resolved

// Convert the UTC time to the local time zone
let local_datetime: DateTime<Local> = utc_datetime.with_timezone(&Local);

let amount = document
.properties()
.get_integer::<Credits>(AMOUNT)
.expect("expected amount on withdrawal");
let status: WithdrawalStatus = document
.properties()
.get_integer::<u8>(STATUS)
.expect("expected amount on withdrawal")
Comment thread
ogabrielides marked this conversation as resolved.
Resolved
.try_into()
.expect("expected a withdrawal status");
let owner_id = document.owner_id();
let address_bytes = document
.properties()
.get_bytes(OUTPUT_SCRIPT)
.expect("expected output script");
let output_script = ScriptBuf::from_bytes(address_bytes);
let address = Address::from_script(&output_script, network).expect("expected an address");
Comment thread
ogabrielides marked this conversation as resolved.
Resolved
Comment thread
ogabrielides marked this conversation as resolved.
Resolved
let withdraw_record = WithdrawRecord {
date_time: local_datetime,
status,
amount,
owner_id,
address,
};
vec_withdraws.push(withdraw_record);
}
let daily_withdrawal_limit =
daily_withdrawal_limit(total_credits_on_platform, PlatformVersion::latest())
.expect("expected to get daily withdrawal limit");

WithdrawStatusData {
withdrawals: vec_withdraws,
total_amount,
recent_withdrawal_amounts,
daily_withdrawal_limit,
total_credits_on_platform,
}
}
Comment thread
ogabrielides marked this conversation as resolved.
Resolved
5 changes: 5 additions & 0 deletions src/ui/components/left_panel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ pub fn add_left_panel(
RootScreenType::RootScreenTransitionVisualizerScreen,
"tools.png",
),
(
"W",
RootScreenType::RootScreenWithdrawsStatus,
"withdraws.png",
),
("N", RootScreenType::RootScreenNetworkChooser, "config.png"),
];

Expand Down
Loading