@@ -82,46 +82,72 @@ export function CreateInvoice() {
8282 }
8383
8484 React . useEffect ( ( ) => {
85+ if ( ! invoice ) {
86+ return ;
87+ }
88+
8589 let polling = true ;
86- let pollCount = 0 ;
87- let prevTransaction : Nip47Transaction | undefined ;
90+ let unsubscribe : ( ( ) => void ) | undefined ;
91+ const nwcClient = useAppStore . getState ( ) . nwcClient ;
92+
93+ const handlePaymentReceived = ( transaction : Nip47Transaction ) => {
94+ if ( ! polling ) {
95+ return ;
96+ }
97+ polling = false ;
98+ unsubscribe ?.( ) ;
99+ router . dismissAll ( ) ;
100+ router . navigate ( {
101+ pathname : "/receive/success" ,
102+ params : { invoice : transaction . invoice } ,
103+ } ) ;
104+ } ;
105+
88106 ( async ( ) => {
107+ if ( ! nwcClient ) {
108+ return ;
109+ }
110+
111+ try {
112+ const info = await nwcClient . getWalletServiceInfo ( ) ;
113+ if ( info . notifications ?. includes ( "payment_received" ) ) {
114+ unsubscribe = await nwcClient . subscribeNotifications (
115+ ( notification ) => {
116+ if (
117+ notification . notification_type === "payment_received" &&
118+ notification . notification . invoice === invoice
119+ ) {
120+ handlePaymentReceived ( notification . notification ) ;
121+ }
122+ } ,
123+ [ "payment_received" ] ,
124+ ) ;
125+ return ;
126+ }
127+ } catch ( error ) {
128+ console . error ( "Failed to subscribe to payment notifications" , error ) ;
129+ }
130+
89131 while ( polling ) {
90132 try {
91- const transactions = await useAppStore
92- . getState ( )
93- . nwcClient ?. listTransactions ( {
94- limit : 1 ,
95- type : "incoming" ,
96- } ) ;
97- const receivedTransaction = transactions ?. transactions [ 0 ] ;
98- if ( receivedTransaction ) {
99- if (
100- polling &&
101- pollCount > 0 &&
102- receivedTransaction . payment_hash !== prevTransaction ?. payment_hash
103- ) {
104- if ( invoice && receivedTransaction . invoice === invoice ) {
105- router . dismissAll ( ) ;
106- router . navigate ( {
107- pathname : "/receive/success" ,
108- params : { invoice : receivedTransaction . invoice } ,
109- } ) ;
110- } else {
111- console . info ( "Received another payment" ) ;
112- }
113- }
114- prevTransaction = receivedTransaction ;
133+ const transaction = await nwcClient . lookupInvoice ( {
134+ invoice,
135+ } ) ;
136+ if ( transaction . state === "settled" ) {
137+ handlePaymentReceived ( transaction ) ;
138+ }
139+ if ( ! polling ) {
140+ break ;
115141 }
116- ++ pollCount ;
117142 } catch ( error ) {
118- console . error ( "Failed to poll for incoming transaction " , error ) ;
143+ console . error ( "Failed to poll invoice status " , error ) ;
119144 }
120- await new Promise ( ( resolve ) => setTimeout ( resolve , 1000 ) ) ;
145+ await new Promise ( ( resolve ) => setTimeout ( resolve , 3000 ) ) ;
121146 }
122147 } ) ( ) ;
123148 return ( ) => {
124149 polling = false ;
150+ unsubscribe ?.( ) ;
125151 } ;
126152 } , [ invoice ] ) ;
127153
0 commit comments