-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathassets_js_bitrequest_sockets.js
1387 lines (1346 loc) · 57.6 KB
/
assets_js_bitrequest_sockets.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ** Core WebSocket Initialization & Management: **
//init_socket
//socket_info
//close_socket
//handle_socket_fails
//handle_socket_close
//reconnect_websocket
//try_next_socket
// ** Lightning Network & NFC Handling: **
//lightning_socket
//process_nfc_payment
//handle_nfc_api_error
//show_nfc_error
//setup_nfc_controller
//stop_nfc_scan
//lnd_poll_data
//lnd_poll_invoice
//lnd_poll_data_fail
//update_boltcard
// ** Bitcoin & Bitcoin-like Cryptocurrencies: **
//blockcypherws
//blockcypher_websocket
//blockchain_btc_socket
//blockchain_bch_socket
//mempoolspace_btc_socket
//sochain_socket
//poll_dash_network
// ** Ethereum & Layer-2 Networks: **
//init_eth_sockets
//alchemy_eth_websocket
//web3_eth_websocket
//web3_erc20_websocket
// ** Other Cryptocurrencies: **
//nano_socket
//poll_nimiq_network
//kaspa_websocket
//kaspa_fyi_websocket
// ** Core WebSocket Initialization & Management: **
// Establishes WebSocket connections for cryptocurrency payment monitoring based on payment type and node configuration
function init_socket(socket_node, wallet_address, retry) {
if (glob_let.offline) {
notify(tl("youareoffline") + ". " + tl("notmonitored"));
return
}
glob_let.rpc_attempts = {};
const payment_type = request.payment;
let node_name;
if (socket_node) {
node_name = socket_node.name;
if (node_name === "poll_fallback") {
start_address_monitor(null, null, true);
return
} else {
glob_let.socket_attempt[sha_sub(socket_node.url, 15)] = true;
}
}
if (payment_type === "bitcoin") {
if (wallet_address === "lnurl") {
// lightning only
} else {
if (node_name === "mempool.space websocket" || socket_node.default === false) {
mempoolspace_btc_socket(socket_node, wallet_address);
} else if (node_name === "blockcypher wss") {
blockcypher_websocket(socket_node, wallet_address);
} else if (node_name === "blockcypher ws") {
blockcypherws(socket_node, wallet_address);
} else if (node_name === "blockchain.info websocket") {
blockchain_btc_socket(socket_node, wallet_address);
} else {
sochain_socket(socket_node, wallet_address, "BTC");
}
}
if (helper.lnd_status) {
if (retry) {
return
}
lightning_socket(helper.lnd);
}
return
}
if (payment_type === "litecoin") {
if (node_name === "mempool.space websocket" || socket_node.default === false) {
mempoolspace_btc_socket(socket_node, wallet_address);
return
}
if (node_name === "blockcypher wss") {
blockcypher_websocket(socket_node, wallet_address);
return
}
if (node_name === "blockcypher ws") {
blockcypherws(socket_node, wallet_address);
return
}
if (node_name === "sochain api") {
sochain_socket(socket_node, wallet_address, "LTC");
return
}
blockcypher_websocket(socket_node, wallet_address);
return
}
if (payment_type === "dogecoin") {
if (node_name === "mempool.space websocket" || socket_node.default === false) {
mempoolspace_btc_socket(socket_node, wallet_address);
return
}
if (node_name === "blockcypher wss") {
blockcypher_websocket(socket_node, wallet_address);
return
}
if (node_name === "blockcypher ws") {
blockcypherws(socket_node, wallet_address);
return
}
if (node_name === "sochain api") {
sochain_socket(socket_node, wallet_address, "DOGE");
return
}
blockcypher_websocket(socket_node, wallet_address);
return
}
if (payment_type === "dash") {
if (node_name === "dash.org") {
poll_dash_network();
return
}
if (node_name === "blockcypher wss") {
blockcypher_websocket(socket_node, wallet_address);
return
}
if (node_name === "blockcypher ws") {
blockcypherws(socket_node, wallet_address);
return
}
return
}
if (payment_type === "bitcoin-cash") {
if (node_name === "mempool.space websocket" || socket_node.default === false) {
mempoolspace_btc_socket(socket_node, wallet_address);
return
}
if (node_name === "blockchain.info websocket") {
blockchain_bch_socket(socket_node, wallet_address);
return
}
blockchain_bch_socket(socket_node, wallet_address);
return
}
if (payment_type === "nano") {
nano_socket(socket_node, wallet_address);
return
}
if (payment_type === "nimiq") {
poll_nimiq_network();
return
}
if (payment_type === "ethereum" || request.erc20) {
init_eth_sockets(payment_type, socket_node, wallet_address, retry);
return
}
if (payment_type === "monero") {
const viewkey = request.viewkey || get_vk(wallet_address);
if (viewkey) {
const monero_requests = get_requestli("payment", "monero"),
pending_txs = filter_list(monero_requests, "pending", "scanning");
if (pending_txs.length) { // update pending xmr tx's to prevent tx duplication
scan_pending_requests(true, pending_txs);
}
const xmr_account = viewkey.account || wallet_address,
xmr_key = viewkey.vk;
request.monitored = true;
request.viewkey = viewkey;
closenotify();
connect_monero_node(9, xmr_account, xmr_key);
return
}
request.monitored = false;
request.viewkey = false;
notify(tl("notmonitored"), 500000, "yes");
return
}
if (payment_type === "kaspa") {
if (node_name === glob_const.main_kas_wss) {
kaspa_websocket(socket_node, wallet_address);
return
}
if (node_name === glob_const.sec_kas_wss) {
kaspa_fyi_websocket(socket_node, wallet_address);
return
}
kaspa_websocket(socket_node, wallet_address);
return
}
notify(tl("notmonitored"), 500000, "yes")
}
// Updates UI elements to reflect WebSocket connection status and handles L1/L2 state transitions
function socket_info(socket_node, is_connected, is_polling) {
if (!is_openrequest()) {
return
}
if (socket_node.network) {
initialize_network_status(socket_node, is_connected);
return
}
let node_url = socket_node.url;
const node_name = socket_node.name,
custom = socket_node.custom;
if (custom && (node_name == "alchemy" || node_name == "infura")) {
node_url = strip_key_from_url(node_url);
}
const node_identifier = node_url || node_name,
status_icon = is_connected ? " <span class='pulse'></span>" : " <span class='icon-wifi-off'></span>",
connection_type = is_polling ? "polling" : "websocket",
status_text = connection_type + ": " + node_identifier + status_icon,
payment_address = $("#paymentaddress");
$("#current_socket").html(status_text);
if (is_connected) {
console.log("Connected: " + node_identifier);
helper.l1_status = true;
payment_address.addClass("live");
glob_const.paymentpopup.addClass("live");
glob_const.paymentdialogbox.removeClass("switching");
closenotify();
return
}
if (glob_const.paymentdialogbox.hasClass("switching")) return // prevents offline modus when switching addresses
if (glob_const.paymentdialogbox.hasClass("transacting")) return
if (!is_openrequest()) return
payment_address.removeClass("live");
helper.l1_status = false;
if (helper.l2_status === false) {
glob_const.paymentpopup.removeClass("live");
notify(tl("websocketoffline"), 500000, "yes");
}
}
// Terminates specific or all active WebSocket connections and cleans up socket registry
function close_socket(socket_id) {
if (socket_id) { // close this socket
if (glob_let.sockets[socket_id]) {
glob_let.sockets[socket_id].close();
delete glob_let.sockets[socket_id];
}
} else { // close all sockets
$.each(glob_let.sockets, function(key, socket) {
if (socket) {
socket.close();
}
});
glob_let.sockets = {};
}
}
// Manages WebSocket failures by attempting reconnection through fallback nodes with L1/L2 network handling
function handle_socket_fails(socket_node, wallet_address, socket_id, is_layer2) {
if (is_openrequest()) { // only when request is visible
if (request.currencysymbol === "bch" && glob_const.paymentdialogbox.hasClass("transacting")) { // temp fix for bch socket
return
}
const ws_id = socket_id || wallet_address;
force_close_socket(ws_id);
const fallback_node = try_next_socket(socket_node, is_layer2);
if (fallback_node) {
if (is_layer2) {
const token_contracts = contracts(request.currencysymbol);
if (token_contracts && socket_id) {
stop_monitors(socket_id);
setup_layer2_monitoring(is_layer2, fallback_node, wallet_address, token_contracts, true);
}
return
}
init_socket(fallback_node, wallet_address, true);
return
}
if (is_layer2) {
// No poll fallback for L2
} else {
const coin_config = get_coinsettings(request.payment),
has_poll_fallback = q_obj(coin_config, "websockets.poll_fallback");
if (has_poll_fallback) {
init_socket({
"name": "poll_fallback",
"display": false
}, wallet_address, true);
return
}
}
socket_info(socket_node, false);
console.error("Socket error:", "unable to connect to " + socket_node.name);
}
}
// Updates connection state and resets WebSocket timer on connection closure
function handle_socket_close(socket_node) {
socket_info(socket_node, false);
console.log("Disconnected from " + socket_node.url);
glob_let.ws_timer = 0;
}
// Implements delayed reconnection logic for Kaspa WebSocket with rate limiting and state validation
function reconnect_websocket(recon_data) {
if (!recon_data) return
const close_code = recon_data.trigger,
wallet_address = recon_data.address;
if (close_code !== 1000 || !wallet_address || glob_const.paymentdialogbox.attr("data-status") !== "new") return
const elapsed_time = now() - glob_let.ws_timer;
if (elapsed_time < 10000) return
const retry_timeout = setTimeout(function() {
if (is_openrequest()) {
recon_data.function(recon_data.node, wallet_address);
}
}, 2000, function() {
clearTimeout(retry_timeout);
});
}
// Selects next available WebSocket endpoint from configuration with overflow protection and duplicate attempt prevention
function try_next_socket(current_node, is_layer2) {
if (!current_node) return false
if (block_overflow("socket")) return false // prevent overflow
const current_url = current_node.url,
socket_config = is_layer2 ? q_obj(get_coinsettings(request.payment), "layer2.options." + current_node.network + ".websockets") : helper.socket_list,
available_nodes = socket_config.options ? $.merge(socket_config.apis, socket_config.options) : socket_config.apis;
if (!available_nodes.length) return false
let current_index;
$.each(available_nodes, function(i, node) {
if (node.url == current_url) {
current_index = i;
}
});
if (current_index > -1) {
const next_node = available_nodes[current_index + 1],
fallback_node = next_node || available_nodes[0],
network_prefix = is_layer2 || "";
if (glob_let.socket_attempt[sha_sub(fallback_node.url + network_prefix, 15)] === true) {
return false
}
if (fallback_node) {
return fallback_node;
}
}
}
// ** Lightning Network & NFC Handling: **
// Establishes WebSocket connection to Lightning Network node for real-time payment monitoring
function lightning_socket(lnd) {
glob_let.lnd_confirm = false;
const proxy_data = lnurl_deform(lnd.proxy_host),
proxy_url = proxy_data.url,
proxy_key = (lnd.pw) ? lnd.pw : proxy_data.k,
payment_id = lnd.pid,
node_id = lnd.nid,
invoice_mode = lnd.imp;
if (glob_let.sockets[payment_id]) {
return
}
const socket = glob_let.sockets[payment_id] = new WebSocket(glob_const.ln_socket);
socket.onopen = function(e) {
console.log("Connected: " + glob_const.ln_socket);
glob_const.paymentpopup.addClass("live");
const ping_msg = JSON.stringify({
"id": payment_id
});
socket.send(ping_msg);
glob_let.pinging[payment_id] = setInterval(function() {
socket.send(ping_msg);
poll_animate();
}, 55000);
};
socket.onmessage = function(e) {
const socket_data = JSON.parse(e.data);
if (socket_data.pid == payment_id) {
if (socket_data.status === "pending" && socket_data.bolt11) {
stop_monitors(payment_id);
close_socket(payment_id);
update_boltcard(false);
lnd_poll_invoice(proxy_url, proxy_key, invoice_mode, socket_data, payment_id, node_id);
glob_let.pinging[socket_data.hash] = setInterval(function() {
lnd_poll_invoice(proxy_url, proxy_key, invoice_mode, socket_data, payment_id, node_id);
}, 5000);
}
if (socket_data.status === "confirm" && !glob_let.lnd_confirm) {
glob_let.lnd_confirm = true;
glob_const.paymentdialogbox.addClass("accept_lnd");
notify(tl("acceptthepayment"), 500000);
vibrate();
play_audio(glob_const.blip);
}
set_dialog_timeout();
return
}
};
socket.onclose = function(e) {
console.log("Disconnected");
};
socket.onerror = function(e) {
glob_let.lnd_confirm = false;
glob_const.paymentpopup.addClass("live");
update_boltcard(false);
glob_let.pinging[payment_id] = setInterval(function() {
lnd_poll_data(proxy_url, proxy_key, payment_id, node_id, invoice_mode);
}, 5000);
};
process_nfc_payment(proxy_url, proxy_key, payment_id, node_id, invoice_mode);
}
// Processes NFC tap events for Lightning Network card payments with LNURL-withdraw protocol
async function process_nfc_payment(proxy_host, proxy_key, payment_id, node_id, invoice_mode) {
if (!glob_const.ndef) return
glob_let.ndef_processing = false;
try {
setup_nfc_controller();
await glob_const.ndef.scan({
"signal": glob_let.ctrl.signal
});
glob_const.ndef.onreading = event => {
if ((now() - 6000) < glob_let.ndef_timer) { // prevent too many taps
play_audio(glob_const.funk);
notify(tl("ndeftablimit"), 6000);
return
}
glob_let.ndef_timer = now();
closenotify();
const nfc_message = event.message;
if (nfc_message) {
const nfc_records = nfc_message.records;
if (nfc_records) {
const first_record = nfc_records[0];
if (first_record) {
const card_data = first_record.data;
if (card_data) {
const lnurl_withdraw = utf8_decoder.decode(card_data);
if (lnurl_withdraw) {
if (lnurl_withdraw.indexOf("p=") && lnurl_withdraw.indexOf("c=")) {
const url_parts = lnurl_withdraw.split("urlw://");
if (url_parts[0] == "ln") {
const amount_rel = $("#open_wallet").attr("data-rel"),
crypto_amount = amount_rel.length ? parseFloat(amount_rel) : 0,
milli_sats = (crypto_amount * 100000000000).toFixed(0);
if (crypto_amount <= 0) {
play_audio(glob_const.funk);
notify(tl("enteramount"), 5000);
return
}
if (glob_let.ndef_processing) {
play_audio(glob_const.funk);
console.error("error", "already processing");
return
}
play_audio(glob_const.blip);
notify("Processing...", 50000);
glob_const.paymentdialogbox.addClass("accept_lnd");
set_dialog_timeout();
const lnurl_endpoint = "https://" + url_parts[1];
glob_let.ndef_processing = true;
api_proxy({
"api_url": lnurl_endpoint,
"params": {
"method": "GET",
"cache": false
}
}, proxy_host).done(function(e) {
const api_response = br_result(e).result;
if (!api_response) { // catch lightning node connection failure
play_audio(glob_const.funk);
notify(tl("unabletoconnectln"), 5000);
glob_const.paymentdialogbox.removeClass("accept_lnd");
glob_let.ndef_processing = false;
return
}
if (api_response.status === "ERROR") {
play_audio(glob_const.funk);
const error_message = api_response.reason;
notify(error_message, 5000);
glob_const.paymentdialogbox.removeClass("accept_lnd");
glob_let.ndef_processing = false;
return
}
if (api_response.error) {
play_audio(glob_const.funk);
fail_dialogs(null, {
"error": api_response.error
});
glob_const.paymentdialogbox.removeClass("accept_lnd");
closenotify();
glob_let.ndef_processing = false;
return
}
if (milli_sats > api_response.maxWithdrawable) {
play_audio(glob_const.funk);
notify(tl("cardmax"), 5000);
glob_const.paymentdialogbox.removeClass("accept_lnd");
glob_let.ndef_processing = false;
return
}
if (milli_sats < api_response.minWithdrawable) {
play_audio(glob_const.funk);
notify(tl("minamount", {
"min": api_response.minWithdrawable
}), 5000);
glob_const.paymentdialogbox.removeClass("accept_lnd");
glob_let.ndef_processing = false;
return
}
const callback_url = api_response.callback;
if (callback_url) {
const auth_key = api_response.k1;
if (auth_key) {
const memo_text = $("#paymentdialog input#requesttitle").val(),
final_memo = (memo_text && memo_text.length > 1) ? memo_text + " (Boltcard)" :
(api_response.defaultDescription) ? api_response.defaultDescription : "bitrequest " + payment_id + " (Boltcard)",
request_type = request.requesttype,
invoice_data = {
"imp": invoice_mode,
"fn": "ln-create-invoice",
"amount": milli_sats,
"memo": final_memo,
"id": payment_id,
"nid": node_id,
"expiry": 60,
"boltcard": true,
"x-api": proxy_key
};
if (request_type === "incoming") {
invoice_data.b11 = true;
}
$.ajax({
"method": "POST",
"cache": false,
"timeout": 5000,
"url": proxy_host + "/proxy/v1/ln/api/",
"data": invoice_data
}).done(function(invoice_result) {
const bolt11 = invoice_result.bolt11;
if (bolt11) {
glob_const.paymentdialogbox.addClass("transacting blockd").attr("data-status", "pending");
$("#paymentdialogbox .brstatuspanel #confnumber").text("1");
notify("Monitoring...", 50000);
const url_separator = callback_url.includes("?") ? "&" : "?",
final_url = callback_url + url_separator + "k1=" + auth_key + "&pr=" + bolt11;
api_proxy({
"proxy": false,
"api_url": final_url,
"params": {
"method": "GET",
"cache": false,
"timeout": 15000
}
}, proxy_host).done(function(e) {
const callback_response = br_result(e).result;
if (callback_response.status === "ERROR") {
show_nfc_error(callback_response.reason);
return
}
if (callback_response.status === "OK") {
stop_monitors(payment_id);
close_socket(payment_id);
stop_nfc_scan();
update_boltcard(true);
lnd_poll_invoice(proxy_host, proxy_key, invoice_mode, invoice_result, payment_id, node_id, true);
glob_let.pinging[invoice_result.hash] = setInterval(function() {
lnd_poll_invoice(proxy_host, proxy_key, invoice_mode, invoice_result, payment_id, node_id);
}, 3000);
return
}
}).fail(function(xhr, stat, err) {
handle_nfc_api_error(xhr, stat, err);
});
return
}
show_nfc_error("failed to create invoice");
}).fail(function(xhr, stat, err) {
handle_nfc_api_error(xhr, stat, err);
}).always(function() {
glob_let.ndef_processing = false;
});
return
}
}
glob_let.ndef_processing = false;
}).fail(function(xhr, stat, err) {
handle_nfc_api_error(xhr, stat, err);
});
return
}
}
notify("invalid lnurlw", 5000);
return
}
}
}
}
}
notify("lnurlw not found", 5000);
}
} catch (error) {
notify(error, 5000);
}
}
// Handles API request failures during NFC card payment processing
function handle_nfc_api_error(xhr, status, error) {
const error_data = xhr || status || error;
fail_dialogs(null, {
"error": error_data
});
glob_const.paymentdialogbox.removeClass("accept_lnd transacting");
closenotify();
glob_let.ndef_processing = false;
}
// Displays temporary error messages in payment dialog during NFC operations
function show_nfc_error(error_text) {
const payment_dialog = $("#paymentdialogbox"),
status_panel = payment_dialog.find(".brstatuspanel"),
status_header = status_panel.find("h2");
status_header.text(error_text);
payment_dialog.addClass("accept_lnd transacting pd_error");
play_audio(glob_const.funk);
closenotify();
setTimeout(function() {
payment_dialog.removeClass("accept_lnd transacting pd_error");
status_header.text(tl("waitingforpayment"));
}, 5000);
}
// Initializes NFC controller with abort signal for scan operations
function setup_nfc_controller() {
glob_let.ctrl = new AbortController();
console.log("Waiting for NDEF messages.");
glob_let.ctrl.signal.onabort = () => {
console.log("Done waiting for NDEF messages.");
};
}
// Terminates active NFC scanning operation and cleans up controller
function stop_nfc_scan() {
if (glob_const.ndef && glob_let.ctrl) {
glob_let.ctrl.abort();
glob_let.ctrl = null;
}
}
// Polls Lightning Network node for payment request status with automatic retry
function lnd_poll_data(proxy_host, proxy_key, payment_id, node_id, invoice_mode) {
if (is_openrequest()) { // only when request is visible
const default_error = tl("unabletoconnect");
$.ajax({
"method": "POST",
"cache": false,
"timeout": 5000,
"url": proxy_host + "/proxy/v1/ln/api/",
"data": {
"fn": "ln-request-status",
"id": payment_id,
"x-api": proxy_key
}
}).done(function(response) {
poll_animate();
const error = response.error;
if (error) {
const error_message = error.message || (typeof error === "string" ? error : default_error);
}
const proxy_version = response.version;
if (proxy_version < glob_const.proxy_version) {
proxy_alert(proxy_version);
}
if (response.pid == payment_id) {
if (response.status == "pending" && response.bolt11) {
stop_monitors(payment_id);
set_dialog_timeout();
glob_let.pinging[response.hash] = setInterval(function() {
lnd_poll_invoice(proxy_host, proxy_key, invoice_mode, response, payment_id, node_id);
}, 5000);
return
}
if (response.status == "confirm" && !glob_let.lnd_confirm) {
glob_let.lnd_confirm = true;
glob_const.paymentdialogbox.addClass("accept_lnd");
notify(tl("acceptthepayment"), 500000);
play_audio(glob_const.blip);
}
return
}
lnd_poll_data_fail(payment_id);
}).fail(function(xhr, status, error) {
lnd_poll_data_fail(payment_id);
});
return
}
force_close_socket();
}
// Monitors Lightning Network invoice payment status with callback handling
function lnd_poll_invoice(proxy_host, proxy_key, invoice_mode, invoice_data, payment_id, node_id) {
if (is_openrequest()) { // only when request is visible
const default_error = "unable to connect";
$.ajax({
"method": "POST",
"cache": false,
"timeout": 5000,
"url": proxy_host + "/proxy/v1/ln/api/",
"data": {
"fn": "ln-invoice-status",
"imp": invoice_mode,
"hash": invoice_data.hash,
"id": payment_id,
"nid": node_id,
"callback": "yes",
"type": request.requesttype,
"x-api": proxy_key
}
}).done(function(response) {
poll_animate();
const payment_status = response.status;
if (payment_status) {
request.address = "lnurl"; // make it a lightning request
notify(tl("waitingforpayment"), 500000);
helper.lnd.invoice = response;
const tx_data = lnd_tx_data(response);
validate_confirmations(tx_data, true, true);
glob_const.paymentdialogbox.removeClass("blockd");
if (payment_status === "paid") {
stop_monitors(invoice_data.hash);
helper.currencylistitem.removeData("url");
br_remove_local("editurl");
br_remove_session("lndpid");
closenotify();
return
}
}
});
return
}
force_close_socket();
}
// Handles connection failures during Lightning Network payment status polling
function lnd_poll_data_fail(payment_id) {
stop_monitors(payment_id);
notify(tl("notmonitored"), 500000, "yes");
}
// Update boltcard status
function update_boltcard(status) {
const fetch_id = get_request_id();
if (fetch_id) {
update_request({
"requestid": fetch_id,
"boltcard": status
}, false);
}
request.boltcard = status;
}
// ** Bitcoin & Bitcoin-like Cryptocurrencies: **
// Attempts WebSocket connection to BlockCypher API with fallback to local WebSocket if running locally
function blockcypherws(socket_node, wallet_address) {
if (glob_let.local === true) {
blockcypher_websocket(socket_node, wallet_address);
return
}
handle_socket_fails(socket_node, wallet_address);
}
// Establishes WebSocket connection to BlockCypher API for transaction confirmation monitoring with automatic ping maintenance
function blockcypher_websocket(socket_node, wallet_address) {
if (glob_let.sockets[wallet_address]) {
return
}
const ws_endpoint = socket_node.url + request.currencysymbol + "/main",
socket = glob_let.sockets[wallet_address] = new WebSocket(ws_endpoint);
socket.onopen = function(e) {
socket_info(socket_node, true);
socket.send(JSON.stringify({
"event": "tx-confirmation",
"address": wallet_address,
"token": get_blockcypher_apikey()
}));
glob_let.pinging[wallet_address] = setInterval(function() {
socket.send(JSON.stringify({
"event": "ping"
}));
poll_animate();
}, 55000);
};
socket.onmessage = function(e) {
const tx_data = JSON.parse(e.data);
if (tx_data.event === "pong") return
const tx_hash = tx_data.hash;
if (!tx_hash) return
close_socket();
const required_confirms = request.set_confirmations || 0,
tx_details = blockcypher_poll_data(tx_data, required_confirms, request.currencysymbol, wallet_address);
if (tx_details.double_spend) {
const alert_content = "<h2 class='icon-warning'>Double spend detected</h2>";
popdialog(alert_content, "canceldialog");
return
}
close_socket();
start_transaction_monitor(tx_details);
};
socket.onclose = function(e) {
handle_socket_close(socket_node);
};
socket.onerror = function(e) {
handle_socket_fails(socket_node, wallet_address);
return
};
}
// Establishes WebSocket connection to Blockchain.info for Bitcoin address monitoring with transaction validation
function blockchain_btc_socket(socket_node, wallet_address) {
if (glob_let.sockets[wallet_address]) {
return
}
const ws_endpoint = socket_node.url,
socket = glob_let.sockets[wallet_address] = new WebSocket(ws_endpoint);
socket.onopen = function(e) {
socket_info(socket_node, true);
socket.send(JSON.stringify({
"op": "addr_sub",
"addr": wallet_address
}));
glob_let.pinging[wallet_address] = setInterval(function() {
socket.send(JSON.stringify({
"op": "ping"
}));
poll_animate();
}, 55000);
};
socket.onmessage = function(e) {
try {
const tx_data = JSON.parse(e.data).x,
tx_hash = tx_data.hash;
if (!tx_hash) return
const required_confirms = request.set_confirmations || 0,
tx_details = blockchain_ws_data(tx_data, required_confirms, request.currencysymbol, wallet_address);
if (tx_details) {
close_socket();
start_transaction_monitor(tx_details);
}
} catch (error) {
console.error("Error parsing WebSocket message:", error);
}
};
socket.onclose = function(e) {
handle_socket_close(socket_node);
};
socket.onerror = function(e) {
handle_socket_fails(socket_node, wallet_address);
return
};
}
// Establishes WebSocket connection to Blockchain.info for BCH address monitoring with CashAddr format handling
function blockchain_bch_socket(socket_node, wallet_address) {
if (glob_let.sockets[wallet_address]) {
return
}
const ws_endpoint = socket_node.url,
socket = glob_let.sockets[wallet_address] = new WebSocket(ws_endpoint);
socket.onopen = function(e) {
socket_info(socket_node, true);
const clean_address = (wallet_address.indexOf("bitcoincash:") > -1) ? wallet_address.split("bitcoincash:").pop() : wallet_address;
socket.send(JSON.stringify({
"op": "addr_sub",
"addr": "bitcoincash:" + clean_address
}));
glob_let.pinging[wallet_address] = setInterval(function() {
socket.send(JSON.stringify({
"op": "ping"
}));
poll_animate();
}, 55000);
};
socket.onmessage = function(e) {
try {
const tx_data = JSON.parse(e.data).x,
tx_hash = tx_data.hash;
if (!tx_hash) return
const legacy_format = bch_legacy(wallet_address),
required_confirms = request.set_confirmations || 0,
tx_details = blockchain_ws_data(tx_data, required_confirms, request.currencysymbol, wallet_address, legacy_format);
if (tx_details) {
close_socket();
start_transaction_monitor(tx_details);
}
} catch (error) {
console.error("Error parsing WebSocket message:", error);
}
};
socket.onclose = function(e) {
handle_socket_close(socket_node);
};
socket.onerror = function(e) {
handle_socket_fails(socket_node, wallet_address);
return
};
}
// Establishes WebSocket connection to mempool.space for real-time Bitcoin transaction monitoring with address tracking
function mempoolspace_btc_socket(socket_node, wallet_address) {
if (glob_let.sockets[wallet_address]) {
return
}
const ws_endpoint = socket_node.url,
mempool_socket = glob_let.sockets[wallet_address] = new WebSocket(ws_endpoint);
mempool_socket.onopen = function(e) {
socket_info(socket_node, true);
mempool_socket.send(JSON.stringify({
"track-address": wallet_address
}));
glob_let.pinging[wallet_address] = setInterval(function() {
mempool_socket.send(JSON.stringify({
"action": "ping"
}));
poll_animate();
}, 55000);
};
mempool_socket.onmessage = function(e) {
try {
const ws_data = JSON.parse(e.data),
tx_batch = ws_data["address-transactions"];
if (tx_batch) {
const tx_data = tx_batch[0];
if (tx_data) {
const tx_hash = tx_data.txid;
if (!tx_hash) return
const required_confirms = request.set_confirmations || 0,
tx_details = mempoolspace_ws_data(tx_data, required_confirms, request.currencysymbol, wallet_address);
if (tx_details) {
close_socket();
start_transaction_monitor(tx_details);
}
}
}
} catch (error) {
console.error("Error parsing WebSocket message:", error);
}
};
mempool_socket.onclose = function(e) {
handle_socket_close(socket_node);
};
mempool_socket.onerror = function(e) {
handle_socket_fails(socket_node, wallet_address);
return
};
}
// Establishes WebSocket connection to chain.so for Bitcoin, Litecoin, Dogecoin address monitoring with transaction validation
function sochain_socket(socket_node, wallet_address, network) {
if (glob_let.sockets[wallet_address]) {
return
}
const ws_endpoint = socket_node.url,
socket = glob_let.sockets[wallet_address] = new WebSocket(ws_endpoint);
socket.onopen = function(e) {
socket_info(socket_node, true);
socket.send(JSON.stringify({
"type": "address",
network,
"data": wallet_address
}));
glob_let.pinging[wallet_address] = setInterval(function() {
socket.send(JSON.stringify({
"type": "keepalive"
}));
poll_animate();
}, 20000);
};
socket.onmessage = function(e) {
try {
const msg_data = JSON.parse(e.data),
tx_data = msg_data.data;
if (tx_data.update_available) {
start_address_monitor(null, null, true);
}
} catch (error) {
console.error("Error parsing WebSocket message:", error);
}
};
socket.onclose = function(e) {
handle_socket_close(socket_node);
};
socket.onerror = function(e) {
handle_socket_fails(socket_node, wallet_address);
return
};
}
// Initiates polling interval for Dash blockchain status with 5-second frequency