@@ -6,9 +6,11 @@ use super::ClnConfig;
66use crate :: types:: NodeInfo ;
77use crate :: {
88 calculate_fee_msats, ApiError , InvoiceType , PayCode , PayInvoiceParams , PayInvoiceResponse ,
9- Transaction ,
9+ Transaction , OnInvoiceEventCallback , OnInvoiceEventParams ,
1010} ;
1111use reqwest:: header;
12+ use std:: thread;
13+ use std:: time:: Duration ;
1214
1315// https://docs.corelightning.org/reference/get_list_methods_resource
1416
@@ -561,3 +563,59 @@ pub fn list_transactions(
561563 Err ( e) => Err ( e) ,
562564 }
563565}
566+
567+
568+ // Core logic shared by both implementations
569+ pub fn poll_invoice_events < F > ( config : & ClnConfig , params : OnInvoiceEventParams , mut callback : F )
570+ where
571+ F : FnMut ( String , Option < Transaction > ) ,
572+ {
573+ let mut start_time = std:: time:: Instant :: now ( ) ;
574+ loop {
575+ if start_time. elapsed ( ) > Duration :: from_secs ( params. max_polling_sec as u64 ) {
576+ // timeout
577+ callback ( "failure" . to_string ( ) , None ) ;
578+ break ;
579+ }
580+
581+ let ( status, transaction) = match lookup_invoice ( config, Some ( params. payment_hash . clone ( ) ) , None , None ) {
582+ Ok ( transaction) => {
583+ if transaction. settled_at > 0 {
584+ ( "settled" . to_string ( ) , Some ( transaction) )
585+ } else {
586+ ( "pending" . to_string ( ) , Some ( transaction) )
587+ }
588+ }
589+ Err ( _) => ( "error" . to_string ( ) , None ) ,
590+ } ;
591+
592+ match status. as_str ( ) {
593+ "settled" => {
594+ callback ( "success" . to_string ( ) , transaction) ;
595+ break ;
596+ }
597+ "error" => {
598+ callback ( "failure" . to_string ( ) , transaction) ;
599+ break ;
600+ }
601+ _ => {
602+ callback ( "pending" . to_string ( ) , transaction) ;
603+ }
604+ }
605+
606+ thread:: sleep ( Duration :: from_secs ( params. polling_delay_sec as u64 ) ) ;
607+ }
608+ }
609+
610+ pub fn on_invoice_events (
611+ config : ClnConfig ,
612+ params : OnInvoiceEventParams ,
613+ callback : Box < dyn OnInvoiceEventCallback > ,
614+ ) {
615+ poll_invoice_events ( & config, params, move |status, tx| match status. as_str ( ) {
616+ "success" => callback. success ( tx) ,
617+ "pending" => callback. pending ( tx) ,
618+ "failure" => callback. failure ( tx) ,
619+ _ => { }
620+ } ) ;
621+ }
0 commit comments