diff --git a/key-wallet-manager/src/wallet_manager/mod.rs b/key-wallet-manager/src/wallet_manager/mod.rs index 944a16b0c..b7d190180 100644 --- a/key-wallet-manager/src/wallet_manager/mod.rs +++ b/key-wallet-manager/src/wallet_manager/mod.rs @@ -1015,6 +1015,30 @@ impl WalletManager { } addresses } + + /// Snapshot the current balance of every managed wallet. + pub(crate) fn snapshot_balances(&self) -> Vec<(WalletId, WalletCoreBalance)> { + self.wallet_infos.iter().map(|(id, info)| (*id, info.balance())).collect() + } + + /// Emit `BalanceUpdated` events for wallets whose balance differs from the snapshot. + pub(crate) fn emit_balance_changes(&self, old_balances: &[(WalletId, WalletCoreBalance)]) { + for (wallet_id, old_balance) in old_balances { + if let Some(info) = self.wallet_infos.get(wallet_id) { + let new_balance = info.balance(); + if *old_balance != new_balance { + let event = WalletEvent::BalanceUpdated { + wallet_id: *wallet_id, + spendable: new_balance.spendable(), + unconfirmed: new_balance.unconfirmed(), + immature: new_balance.immature(), + locked: new_balance.locked(), + }; + let _ = self.event_sender.send(event); + } + } + } + } } /// Wallet manager errors diff --git a/key-wallet-manager/src/wallet_manager/process_block.rs b/key-wallet-manager/src/wallet_manager/process_block.rs index c86fbb760..14eebba78 100644 --- a/key-wallet-manager/src/wallet_manager/process_block.rs +++ b/key-wallet-manager/src/wallet_manager/process_block.rs @@ -114,25 +114,13 @@ impl WalletInterface for WalletM fn update_synced_height(&mut self, height: CoreBlockHeight) { self.synced_height = height; - // Update each wallet and emit BalanceUpdated events if balance changed - for (wallet_id, info) in self.wallet_infos.iter_mut() { - let old_balance = info.balance(); + let snapshot = self.snapshot_balances(); + + for (_wallet_id, info) in self.wallet_infos.iter_mut() { info.update_synced_height(height); - let new_balance = info.balance(); - - // Emit event if balance changed - #[cfg(feature = "std")] - if old_balance != new_balance { - let event = WalletEvent::BalanceUpdated { - wallet_id: *wallet_id, - spendable: new_balance.spendable(), - unconfirmed: new_balance.unconfirmed(), - immature: new_balance.immature(), - locked: new_balance.locked(), - }; - let _ = self.event_sender.send(event); - } } + + self.emit_balance_changes(&snapshot); } fn filter_committed_height(&self) -> CoreBlockHeight {