@@ -607,15 +607,14 @@ impl Wallet {
607607 Arc :: clone ( & logger) ,
608608 ) ) ;
609609
610- // Spawn a background thread that every second, we see if we should initiate a rebalance
611- // This will withdraw from the trusted balance to our LN balance, possibly opening a channel.
610+ // Spawn a background thread to initiate a rebalance if needed.
611+ // We only do this once as we generally rebalance in response to
612+ // `Event`s which indicated our balance has changed.
612613 let rb = Arc :: clone ( & rebalancer) ;
613614 runtime. spawn_cancellable_background_task ( async move {
614- loop {
615- rb. do_rebalance_if_needed ( ) . await ;
616-
617- tokio:: time:: sleep ( Duration :: from_secs ( 1 ) ) . await ;
618- }
615+ // Wait a second to get caught up, then try to rebalance.
616+ tokio:: time:: sleep ( Duration :: from_secs ( 1 ) ) . await ;
617+ rb. do_rebalance_if_needed ( ) . await ;
619618 } ) ;
620619
621620 let inner = Arc :: new ( WalletImpl {
@@ -1333,12 +1332,20 @@ impl Wallet {
13331332 ///
13341333 /// **Note:** This **MUST** be called after each event has been handled.
13351334 pub fn event_handled ( & self ) -> Result < ( ) , ( ) > {
1336- self . inner . runtime . block_on ( self . inner . event_queue . event_handled ( ) ) . map_err ( |e| {
1335+ let res = self . inner . runtime . block_on ( self . inner . event_queue . event_handled ( ) ) . map_err ( |e| {
13371336 log_error ! (
13381337 self . inner. logger,
13391338 "Couldn't mark event handled due to persistence failure: {e}"
13401339 ) ;
1341- } )
1340+ } ) ;
1341+ if res. is_ok ( ) {
1342+ // If an event was handled, probably our balances changed and we may need to rebalance.
1343+ let inner_ref = Arc :: clone ( & self . inner ) ;
1344+ self . inner . runtime . spawn_cancellable_background_task ( async move {
1345+ inner_ref. rebalancer . do_rebalance_if_needed ( ) . await ;
1346+ } ) ;
1347+ }
1348+ res
13421349 }
13431350
13441351 /// Stops the wallet, which will stop the underlying LDK node and any background tasks.
0 commit comments