Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
14 changes: 6 additions & 8 deletions src-tauri/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,17 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use serde::Serialize;
use std::{
collections::HashMap,
hash::{Hash, Hasher},
};

use crate::{
internal_wallet::TariAddressType,
mining::gpu::miners::GpuCommonInformation,
node::{node_adapter::NodeIdentity, node_manager::NodeType},
setup::{listeners::AppModule, setup_manager::SetupPhase},
wallet::wallet_types::TransactionInfo,
};

use serde::Serialize;
use std::{
collections::HashMap,
hash::{Hash, Hasher},
};

#[derive(Clone, Debug, Serialize)]
Expand Down Expand Up @@ -150,7 +149,6 @@ pub struct Event<T, E> {
#[derive(Clone, Debug, Serialize)]
pub struct NewBlockHeightPayload {
pub block_height: u64,
pub coinbase_transaction: Option<TransactionInfo>,
}

#[derive(Debug, Serialize, Clone)]
Expand Down
18 changes: 6 additions & 12 deletions src-tauri/src/events_emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::LOG_TARGET_APP_LOGIC;
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::configs::config_ui::WalletUIMode;
use crate::events::{
ConnectionStatusPayload, CriticalProblemPayload, DisabledPhasesPayload,
ConnectionStatusPayload, CriticalProblemPayload, DisabledPhasesPayload, NewBlockHeightPayload,
UpdateAppModuleStatusPayload, WalletScanningProgressUpdatePayload,
};
use crate::internal_wallet::TariAddressType;
Expand All @@ -34,16 +34,16 @@ use crate::mining::pools::PoolStatus;
use crate::mining::MinerControlsState;
#[cfg(target_os = "windows")]
use crate::system_dependencies::UniversalSystemDependency;
use crate::wallet::wallet_types::{TransactionInfo, WalletBalance};
use crate::wallet::wallet_types::WalletBalance;
use crate::{
configs::{
config_core::ConfigCoreContent, config_mining::ConfigMiningContent,
config_ui::ConfigUIContent, config_wallet::ConfigWalletContent,
},
events::{
DetectedAvailableGpuEnginesPayload, DetectedDevicesPayload, Event, EventType,
NetworkStatusPayload, NewBlockHeightPayload, NodeTypeUpdatePayload,
ProgressTrackerUpdatePayload, ShowReleaseNotesPayload, TariAddressUpdatePayload,
NetworkStatusPayload, NodeTypeUpdatePayload, ProgressTrackerUpdatePayload,
ShowReleaseNotesPayload, TariAddressUpdatePayload,
},
hardware::hardware_status_monitor::PublicDeviceGpuProperties,
setup::setup_manager::SetupPhase,
Expand Down Expand Up @@ -471,17 +471,11 @@ impl EventsEmitter {
}
}

pub async fn emit_new_block_mined(
block_height: u64,
coinbase_transaction: Option<TransactionInfo>,
) {
pub async fn emit_new_block_mined(block_height: u64) {
let _unused = FrontendReadyChannel::current().wait_for_ready().await;
let event = Event {
event_type: EventType::NewBlockHeight,
payload: NewBlockHeightPayload {
block_height,
coinbase_transaction,
},
payload: NewBlockHeightPayload { block_height },
};
if let Err(e) = Self::get_app_handle()
.await
Expand Down
84 changes: 2 additions & 82 deletions src-tauri/src/events_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,93 +20,13 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// use std::time::Duration;

use log::info;
// use tari_transaction_components::tari_amount::MicroMinotari;
use tauri::{AppHandle, Manager};

// use crate::airdrop::send_new_block_mined;
// use crate::configs::config_core::ConfigCore;
// use crate::configs::trait_config::ConfigImpl;
use crate::setup::listeners::SetupFeature;
use crate::setup::setup_manager::SetupManager;
use crate::LOG_TARGET_APP_LOGIC;
use crate::{
events::NodeTypeUpdatePayload, events_emitter::EventsEmitter, tasks_tracker::TasksTrackers,
UniverseAppState,
};
use crate::{events::NodeTypeUpdatePayload, events_emitter::EventsEmitter, UniverseAppState};

pub struct EventsManager;

impl EventsManager {
pub async fn handle_new_block_height(app: &AppHandle, block_height: u64) {
let state = app.state::<UniverseAppState>();
let in_memory_config = state.in_memory_config.read().await;
if SetupManager::get_instance()
.features
.read()
.await
.is_feature_enabled(SetupFeature::SeedlessWallet)
{
info!(target: LOG_TARGET_APP_LOGIC, "Firing new block height {block_height} event but skipping wallet scan for seedless wallet feature");
EventsEmitter::emit_new_block_mined(block_height, None).await;

return;
}
drop(in_memory_config);
// let app_clone = app.clone();
// let wallet_manager = state.wallet_manager.clone();

TasksTrackers::current()
.wallet_phase
.get_task_tracker()
.await
.spawn(async move {
// Event does not need to be fired immediately since frontend uses block height from explorer
// match wallet_manager.wait_for_scan_to_height(block_height, Some(Duration::from_secs(20))).await {
// Ok(scanned_wallet_state) => {
// if let Some(balance) = scanned_wallet_state.balance {
// EventsEmitter::emit_wallet_balance_update(balance.clone()).await;
// // Check for coinbase transaction if there's pending balance
// let coinbase_tx = if balance.pending_incoming_balance.gt(&MicroMinotari::zero()) {
// wallet_manager.find_coinbase_transaction_for_block(block_height).await.unwrap_or_else(|e| {
// error!(target: LOG_TARGET_APP_LOGIC, "Failed to get coinbase transaction: {e:?}");
// None
// })
// } else {
// None
// };

// EventsEmitter::emit_new_block_mined(
// block_height,
// coinbase_tx.clone(),
// )
// .await;
// let allow_notifications = *ConfigCore::content().await.allow_notifications();
// if coinbase_tx.is_some() && allow_notifications {
// send_new_block_mined(app_clone.clone(), block_height).await;
// }
// } else {
// error!(target: LOG_TARGET_APP_LOGIC, "Wallet balance is None after new block height #{block_height}");
// EventsEmitter::emit_new_block_mined(
// block_height,
// None,
// )
// .await;
// }
// },
// Err(e) => {
// error!(target: LOG_TARGET_APP_LOGIC, "Error waiting for wallet scan: {e}");
// EventsEmitter::emit_new_block_mined(
// block_height,
// None,
// )
// .await;
// }
// }
});
}

pub async fn handle_node_type_update(app_handle: &AppHandle) {
let node_manager = &app_handle.state::<UniverseAppState>().node_manager;
let node_type = Some(node_manager.get_node_type().await);
Expand Down
3 changes: 2 additions & 1 deletion src-tauri/src/setup/phase_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,15 +294,16 @@ impl SetupPhaseImpl for NodeSetupPhase {
let is_syncing = MinotariWalletManager::is_syncing().await;



if !is_syncing && node_synced && latest_updated_block_height == 0 {
latest_updated_block_height = node_status.block_height;
}

if node_status.block_height > latest_updated_block_height && !is_syncing && node_synced {
while latest_updated_block_height < node_status.block_height {
latest_updated_block_height += 1;
let _ = EventsManager::handle_new_block_height(&app_handle_clone, latest_updated_block_height).await;
}
EventsEmitter::emit_new_block_mined(latest_updated_block_height).await;
}
EventsEmitter::emit_base_node_update(node_status).await;
if node_status.block_height > latest_updated_block_height && is_syncing {
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/src/wallet/wallet_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ impl WalletBalance {
res.map(Self::from_response)
}
}

#[allow(dead_code)]
#[derive(Debug, Serialize, Clone)]
pub struct TransactionInfo {
pub tx_id: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,25 +99,6 @@ const HistoryListItem = memo(function HistoryListItem({
? `***`
: formatNumber(transaction.amount, FormatPreset.XTM_COMPACT).toLowerCase();

/*
// note re. isPositiveValue:
// amounts in the tx response are always positive numbers but
// if the transaction is Outbound, the value is negative
const isPositiveValue = item.walletTransactionDetails.direction === TransactionDirection.Inbound;
const displayTitle = itemTitle.length > 26 ? truncateMiddle(itemTitle, 8) : itemTitle;

const getValueMarkup = (fullValue = false) => (
<ValueWrapper>
{!hideWalletBalance && (
<ValueChangeWrapper $isPositiveValue={isPositiveValue}>
{isPositiveValue ? `+` : `-`}
</ValueChangeWrapper>
)}
{fullValue ? earningsFull : earningsFormatted}
<CurrencyText>{`XTM`}</CurrencyText>
</ValueWrapper>
);
*/
const baseItem = (
<BaseItem
title={itemTitle}
Expand Down
4 changes: 2 additions & 2 deletions src/containers/main/Dashboard/MiningView/components/Ruler.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useTheme } from 'styled-components';
import { useLayoutEffect, useRef } from 'react';
import { useEffect, useRef } from 'react';
import { useMotionValue } from 'motion/react';
import { useBlockTip } from '@app/hooks/mining/useBlockTip.ts';
import { Column, MarkGroup, RulerMark, RulerMarkGroup, Wrapper } from './Ruler.styles.ts';
Expand Down Expand Up @@ -58,7 +58,7 @@ export function Ruler() {
);
});

useLayoutEffect(() => {
useEffect(() => {
function handleResize() {
windowWidth.set(window.innerWidth);
}
Expand Down
9 changes: 5 additions & 4 deletions src/hooks/app/useTauriEventsListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,10 @@ const useTauriEventsListener = () => {
case 'GpuPoolsStatsUpdate':
setGpuPoolStats(event.payload);
break;

case 'NewBlockHeight': {
const current = useBlockchainVisualisationStore.getState().latestBlockPayload?.block_height;
if (!current || current < event.payload.block_height) {
const current = useBlockchainVisualisationStore.getState().latestBlockHeight;
if (!current || current < event.payload) {
await handleNewBlockPayload(event.payload);
}
break;
Expand Down Expand Up @@ -269,13 +270,13 @@ const useTauriEventsListener = () => {
setIsShuttingDown(true);
break;
case 'WalletTransactionsFound':
handleWalletTransactionsFound(event.payload);
await handleWalletTransactionsFound(event.payload);
break;
case 'WalletTransactionsCleared':
handleWalletTransactionsCleared();
break;
case 'WalletTransactionUpdated':
handleWalletTransactionUpdated(event.payload);
await handleWalletTransactionUpdated(event.payload);
break;
case 'SetShowBatteryAlert':
setShowBatteryAlert(event.payload);
Expand Down
52 changes: 39 additions & 13 deletions src/hooks/mining/useBlockTip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { useQuery } from '@tanstack/react-query';
import { BlockTip } from '@app/types/mining/blocks.ts';
import { getExplorerUrl } from '@app/utils/network.ts';
import { defaultHeaders } from '@app/utils';
import { processNewBlock, useBlockchainVisualisationStore } from '@app/store';
import { processNewBlock, useBlockchainVisualisationStore, useMiningStore } from '@app/store';
import { KEY_EXPLORER } from '@app/hooks/mining/useFetchExplorerData.ts';
import { useEffect, useRef } from 'react';
import { getIsMining } from '@app/store/selectors/minningStoreSelectors.ts';

async function getTipHeight(): Promise<BlockTip> {
const explorerUrl = getExplorerUrl();
Expand All @@ -14,18 +16,42 @@ async function getTipHeight(): Promise<BlockTip> {
return r.json();
}
export function useBlockTip() {
const latestBlock = useBlockchainVisualisationStore((s) => s.latestBlockPayload);
return useQuery<BlockTip>({
queryKey: [KEY_EXPLORER, 'block_tip'],
queryFn: async () => {
const data = await getTipHeight();
if (latestBlock && data?.height !== latestBlock?.block_height) {
await processNewBlock(latestBlock);
}
return data;
},
const isMining = useMiningStore((s) => getIsMining(s));
const latestNodeBlockHeight = useBlockchainVisualisationStore((s) => s.latestBlockHeight);

const cancelRefetch = useRef(false);
const cancelProcess = useRef(false);

const { data, isLoading, refetch, isRefetching } = useQuery<BlockTip>({
queryKey: [KEY_EXPLORER, 'tip_height'],
queryFn: async () => await getTipHeight(),
notifyOnChangeProps: ['data'],
refetchIntervalInBackground: true,
refetchInterval: 20 * 1000,
staleTime: 1000 * 60,
refetchInterval: 1000 * 60 * 1.5,
});

const nodeSync = Boolean(latestNodeBlockHeight && data && latestNodeBlockHeight <= data?.height);
const shouldProccess = nodeSync && !isMining && !isLoading && !isRefetching && !cancelProcess.current;
const explorerDelayed = Boolean(latestNodeBlockHeight && data && latestNodeBlockHeight > data?.height);

useEffect(() => {
if (explorerDelayed && !cancelRefetch.current && !isRefetching) {
cancelRefetch.current = true;
refetch().then(() => {
cancelRefetch.current = false;
});
}
}, [explorerDelayed, isRefetching, refetch]);

useEffect(() => {
if (!shouldProccess) return;
cancelProcess.current = true;
cancelRefetch.current = true;
processNewBlock().then(() => {
cancelProcess.current = false;
cancelRefetch.current = false;
});
}, [shouldProccess]);

return { data, isLoading };
}
2 changes: 2 additions & 0 deletions src/store/selectors/minningStoreSelectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ export const getSelectedMiner = (state: MiningStoreState): GpuMiner | undefined

return state.availableMiners[state.selectedMiner];
};

export const getIsMining = (s: MiningStoreState): boolean => s.isCpuMiningInitiated || s.isGpuMiningInitiated;
Loading
Loading