/
wsui_main.js
2920 lines (2648 loc) · 95.9 KB
/
wsui_main.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
/*jshint bitwise: false*/
/* globals iqwerty */
/* globals List */
const os = require('os');
const path = require('path');
const fs = require('fs');
const {clipboard, remote, ipcRenderer, shell} = require('electron');
const Store = require('electron-store');
const Mousetrap = require('./extras/mousetrap.min.js');
const autoComplete = require('./extras/auto-complete');
const wsutil = require('./ws_utils');
const WalletShellSession = require('./ws_session');
const WalletShellManager = require('./ws_manager');
const config = require('./ws_config');
const Chart = require('chart.js');
const log = require('electron-log');
const wsmanager = new WalletShellManager();
const wsession = new WalletShellSession();
const settings = new Store({ name: 'Settings' });
const abook = new Store({
name: 'AddressBook',
encryptionKey: config.addressBookObfuscateEntries ? config.addressBookObfuscationKey : null
});
const win = remote.getCurrentWindow();
const Menu = remote.Menu;
const WS_VERSION = settings.get('version', 'unknown');
const DEFAULT_WALLET_PATH = remote.app.getPath('documents');
let WALLET_OPEN_IN_PROGRESS = false;
//let FUSION_IN_PROGRESS = false;
let TXLIST_OBJ = null;
let COMPLETION_PUBNODES;
let COMPLETION_ADDRBOOK;
/* dom elements vars; */
// body
let body;
// main section link
let sectionButtons;
// generics
let genericBrowseButton;
let genericFormMessage;
let genericEnterableInputs;
let genericEditableInputs;
let firstTab;
// about page
let aboutButtonBack;
// settings page
let settingsInputDaemonAddress;
let settingsInputDaemonPort;
let settingsInputServiceBin;
let settingsInputMinToTray;
let settingsInputCloseToTray;
let settingsButtonSave;
let settingsButtonBack;
// overview page
let overviewWalletAddress;
let overviewWalletCopyButton;
let overviewWalletCloseButton;
let overviewPaymentIdGen;
let overviewIntegratedAddressGen;
// addressbook page
let addressBookInputName;
let addressBookInputWallet;
let addressBookInputPaymentId;
let addressBookInputUpdate;
let addressBookButtonSave;
let addressBookSelectOrder;
// open wallet page
let walletOpenInputPath;
let walletOpenInputPassword;
let walletOpenButtonOpen;
let walletOpenButtons;
// show/export keys page
let overviewShowKeyButton;
let showkeyButtonExportKey;
let showkeyInputViewKey;
let showkeyInputSpendKey;
let showkeyInputSeed;
// send page
let sendInputAddress;
let sendInputAmount;
let sendInputPaymentId;
let sendInputFee;
let sendButtonSend;
let sendMaxAmount;
let sendOptimize;
// create wallet
let overviewButtonCreate;
let zoomQrCode;
let walletCreateInputPath;
let walletCreateInputPassword;
// import wallet keys
let importKeyButtonImport;
let importKeyInputPath;
let importKeyInputPassword;
let importKeyInputViewKey;
let importKeyInputSpendKey;
let importKeyInputScanHeight;
// import wallet seed
let importSeedButtonImport;
let importSeedInputPath;
let importSeedInputPassword;
let importSeedInputMnemonic;
let importSeedInputScanHeight;
// transaction
let txButtonRefresh;
let txButtonSortAmount;
let txButtonSortDate;
let txInputUpdated;
let txInputNotify;
let txButtonExport;
// misc
let sswitch;
let kswitch;
let iswitch;
// exchange
let chartConfig;
let chartInstance;
function populateElementVars(){
// misc
sswitch = document.getElementById('sswitch');
kswitch = document.getElementById('kswitch');
iswitch = document.getElementById('iswitch');
firstTab = document.querySelector('.navbar-button');
// generics
genericBrowseButton = document.querySelectorAll('.path-input-button:not(.d-opened)');
genericFormMessage = document.getElementsByClassName('form-ew');
genericEnterableInputs = document.querySelectorAll('.section input:not(.noenter)');
genericEditableInputs = document.querySelectorAll('textarea:not([readonly]), input:not([readonly]');
// body
body = document.getElementsByTagName('body');
// main section link
sectionButtons = document.querySelectorAll('[data-section]');
// main section link
aboutButtonBack = document.getElementById('button-about-back');
// settings input & elements
settingsInputDaemonAddress = document.getElementById('input-settings-daemon-address');
settingsInputDaemonPort = document.getElementById('input-settings-daemon-port');
settingsInputServiceBin = document.getElementById('input-settings-path');
settingsInputMinToTray = document.getElementById('checkbox-tray-minimize');
settingsInputCloseToTray = document.getElementById('checkbox-tray-close');
settingsButtonSave = document.getElementById('button-settings-save');
settingsButtonBack = document.getElementById('button-settings-back');
// overview pages
overviewWalletAddress = document.getElementById('wallet-address');
overviewWalletCopyButton = document.getElementById('copy-wallet-address');
overviewWalletCloseButton = document.getElementById('button-overview-closewallet');
overviewPaymentIdGen = document.getElementById('payment-id-gen');
overviewIntegratedAddressGen = document.getElementById('integrated-wallet-gen');
// addressbook page
addressBookInputName = document.getElementById('input-addressbook-name');
addressBookInputWallet = document.getElementById('input-addressbook-wallet');
addressBookInputPaymentId = document.getElementById('input-addressbook-paymentid');
addressBookInputUpdate = document.getElementById('input-addressbook-update');
addressBookButtonSave = document.getElementById('button-addressbook-save');
addressBookSelectOrder = document.getElementById('button-addressbook-order');
// open wallet page
walletOpenInputPath = document.getElementById('input-load-path');
walletOpenInputPassword = document.getElementById('input-load-password');
walletOpenButtonOpen = document.getElementById('button-load-load');
walletOpenButtons = document.getElementById('walletOpenButtons');
// show/export keys page
overviewShowKeyButton = document.getElementById('button-show-reveal');
showkeyButtonExportKey = document.getElementById('button-show-export');
showkeyInputViewKey = document.getElementById('key-show-view');
showkeyInputSpendKey = document.getElementById('key-show-spend');
showkeyInputSeed = document.getElementById('seed-show');
// send page
sendInputAddress = document.getElementById('input-send-address');
sendInputAmount = document.getElementById('input-send-amount');
sendInputPaymentId = document.getElementById('input-send-payid');
sendInputFee = document.getElementById('input-send-fee');
sendButtonSend = document.getElementById('button-send-send');
// maxSendFormHelp = document.getElementById('sendFormHelp');
sendMaxAmount = document.getElementById('sendMaxAmount');
sendOptimize = document.getElementById('button-send-optimize');
// create wallet
overviewButtonCreate = document.getElementById('button-create-create');
zoomQrCode = document.getElementById('zoom-qr-code');
walletCreateInputPath = document.getElementById('input-create-path');
walletCreateInputPassword = document.getElementById('input-create-password');
// import wallet keys
importKeyButtonImport = document.getElementById('button-import-import');
importKeyInputPath = document.getElementById('input-import-path');
importKeyInputPassword = document.getElementById('input-import-password');
importKeyInputViewKey = document.getElementById('key-import-view');
importKeyInputSpendKey = document.getElementById('key-import-spend');
importKeyInputScanHeight = document.getElementById('key-import-height');
// import wallet seed
importSeedButtonImport = document.getElementById('button-import-seed-import');
importSeedInputPath = document.getElementById('input-import-seed-path');
importSeedInputPassword = document.getElementById('input-import-seed-password');
importSeedInputMnemonic = document.getElementById('key-import-seed');
importSeedInputScanHeight = document.getElementById('key-import-seed-height');
// tx page
// transaction
txButtonRefresh = document.getElementById('button-transactions-refresh');
txButtonSortAmount = document.getElementById('txSortAmount');
txButtonSortDate = document.getElementById('txSortTime');
txInputUpdated = document.getElementById('transaction-updated');
txInputNotify = document.getElementById('transaction-notify');
txButtonExport = document.getElementById('transaction-export');
}
// crude/junk template :)
let jtfr = {
tFind: [
"WalletShell",
"https://github.com/furiousteam/BLOC-electron-wallet",
"TurtleCoin",
"TRTL",
"BLOC-service"
],
tReplace: [
config.appName,
config.appGitRepo,
config.assetName,
config.assetTicker,
config.walletServiceBinaryFilename
]
};
let junkTemplate = (text) => {
return jtfr.tFind.reduce((acc, item, i) => {
const regex = new RegExp(item, "g");
return acc.replace(regex, jtfr.tReplace[i]);
}, text);
};
function initSectionTemplates(){
const importLinks = document.querySelectorAll('link[rel="import"]');
for (var i = 0; i < importLinks.length; i++){
let template = importLinks[i].import.getElementsByTagName("template")[0];
let templateString = junkTemplate(template.innerHTML);
let templateNode = document.createRange().createContextualFragment(templateString);
//let clone = document.importNode(templateNode, true);
let clone = document.adoptNode(templateNode);
//let clone = document.importNode(template.content, true);
document.getElementById('main-div').appendChild(clone);
}
// once all elements in place, safe to populate dom vars
populateElementVars();
}
let keybindingTpl = `<div id="section-shortcuts">
<div class="transaction-panel">
<div class="div-title clearfix">
<img src="../assets/shortcuts/title.png" />
<h2 class="title">Available Keybindings</h2>
<div class="subtitle">BLOC wallet</div>
</div>
<table class="custom-table kb-table">
<tbody>
<tr class="odd">
<th scope="col"><kbd>Ctrl</kbd>+<kbd>Home</kbd></th>
<td class="fc"><img src="../assets/general/arrow-left-white.png" /></td>
<td>Switch to <strong>overview/welcome</strong> screen</td>
</tr>
<tr class="transparent">
<td colspan="2"></td>
</tr>
<tr class="even">
<th scope="col"><kbd>Ctrl</kbd>+<kbd>Tab</kbd></th>
<td><img src="../assets/general/arrow-left-white.png" /></td>
<td>Switch to <strong>next screen</strong></td>
</tr>
<tr class="transparent">
<td colspan="2"></td>
</tr>
<tr class="odd">
<th scope="col"><kbd>Ctrl</kbd>+<kbd>n</kbd></th>
<td><img src="../assets/general/arrow-left-white.png" /></td>
<td>Switch to <strong>Create new wallet</strong> screen</td>
</tr>
<tr class="transparent">
<td colspan="2"></td>
</tr>
<tr class="even">
<th scope="col"><kbd>Ctrl</kbd>+<kbd>o</kbd></th>
<td><img src="../assets/general/arrow-left-white.png" /></td>
<td>Switch to <strong>Open a wallet</strong> screen</td>
</tr>
<tr class="transparent">
<td colspan="2"></td>
</tr>
<tr class="odd">
<th scope="col"><kbd>Ctrl</kbd>+<kbd>i</kbd></th>
<td><img src="../assets/general/arrow-left-white.png" /></td>
<td>Switch to <strong>Import wallet from private keys</strong> screen</td>
</tr>
<tr class="transparent">
<td colspan="2"></td>
</tr>
<tr class="even">
<th scope="col"><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>i</kbd></th>
<td><img src="../assets/general/arrow-left-white.png" /></td>
<td>Switch to <strong>Import wallet from mnemonic seed</strong> screen</td>
</tr>
<tr class="transparent">
<td colspan="2"></td>
</tr>
<tr class="odd">
<th scope="col"><kbd>Ctrl</kbd>+<kbd>e</kbd></th>
<td><img src="../assets/general/arrow-left-white.png" /></td>
<td>Switch to <strong>Export private keys/seed</strong> screen (when wallet opened)</td>
</tr>
<tr class="transparent">
<td colspan="2"></td>
</tr>
<tr class="even">
<th scope="col"><kbd>Ctrl</kbd>+<kbd>t</kbd></th>
<td><img src="../assets/general/arrow-left-white.png" /></td>
<td>Switch to <strong>Transactions</strong> screen (when wallet opened)</td>
</tr>
<tr class="transparent">
<td colspan="2"></td>
</tr>
<tr class="odd">
<th scope="col"><kbd>Ctrl</kbd>+<kbd>s</kbd></th>
<td><img src="../assets/general/arrow-left-white.png" /></td>
<td>Switch to <strong>Send/Transfer</strong> screen (when wallet opened)</td>
</tr>
<tr class="transparent">
<td colspan="2"></td>
</tr>
<tr class="even">
<th scope="col"><kbd>Ctrl</kbd>+<kbd>x</kbd></th>
<td><img src="../assets/general/arrow-left-white.png" /></td>
<td>Close wallet</td>
</tr>
<tr class="transparent">
<td colspan="2"></td>
</tr>
<tr class="odd">
<th scope="col"><kbd>Ctrl</kbd>+<kbd>/</kbd></th>
<td><img src="../assets/general/arrow-left-white.png" /></td>
<td>Display shortcut key information (this dialog)</td>
</tr>
<tr class="transparent">
<td colspan="2"></td>
</tr>
<tr class="even">
<th scope="col"><kbd>Esc</kbd></th>
<td><img src="../assets/general/arrow-left-white.png" /></td>
<td>Close any opened dialog (like this dialog)</td>
</tr>
</tbody>
</table>
<div class="div-panel-buttons">
<button data-target="#ab-dialog" type="button" class="button-blue dialog-close-default">Close</button>
</div>
</div>
</div>
`;
function genPaymentId(ret){
ret = ret || false;
let payId = require('crypto').randomBytes(32).toString('hex');
if(ret) return payId;
let dialogTpl = `<div class="transaction-panel">
<h4>Generated Payment ID:</h4>
<textarea data-cplabel="Payment ID" title="click to copy" class="ctcl default-textarea" rows="1" readonly="readonly">${payId}</textarea>
<div class="div-panel-buttons">
<button data-target="#ab-dialog" type="button" class="button-gray dialog-close-default">Close</button>
</div>
`;
let dialog = document.getElementById('ab-dialog');
if(dialog.hasAttribute('open')) dialog.close();
dialog.innerHTML = dialogTpl;
dialog.showModal();
}
function showIntegratedAddressForm(){
let dialog = document.getElementById('ab-dialog');
let ownAddress = wsession.get('loadedWalletAddress');
if(dialog.hasAttribute('open')) dialog.close();
let iaform = `<div class="transaction-panel">
<h4>Generate Integrated Address:</h4>
<div class="input-wrap">
<label>Wallet Address</label>
<textarea id="genInputAddress" class="default-textarea" placeholder="Required, put any valid ${config.assetTicker} address..">${ownAddress}</textarea>
</div>
<div class="input-wrap">
<label>Payment Id (<a id="makePaymentId" class="wallet-tool inline-tool" title="generate random payment id...">generate</a>)</label>
<input id="genInputPaymentId" type="text" required="required" class="text-block" placeholder="Required, enter a valid payment ID, or click generate to get random ID" />
</div>
<div class="input-wrap">
<textarea data-cplabel="Integrated address" placeholder="Fill the form & click generate, integrated address will appear here..." rows="3" id="genOutputIntegratedAddress" class="default-textarea ctcl" readonly="readonly"></textarea>
</div>
<div class="input-wrap">
<span class="form-ew form-msg text-spaced-error hidden" id="text-gia-error"></span>
</div>
<div class="div-panel-buttons">
<button id="doGenIntegratedAddr" type="button" class="button-green dialog-close-default">Generate</button>
<button data-target="#ab-dialog" type="button" class="button-gray dialog-close-default">Close</button>
</div>
`;
dialog.innerHTML = iaform;
dialog.showModal();
}
function showKeyBindings(){
let dialog = document.getElementById('ab-dialog');
if(dialog.hasAttribute('open')) dialog.close();
dialog.innerHTML = keybindingTpl;
dialog.showModal();
}
function switchTab(){
if(WALLET_OPEN_IN_PROGRESS){
wsutil.showToast('Opening wallet in progress, please wait...');
return;
}
let isServiceReady = wsession.get('serviceReady') || false;
let activeTab = document.querySelector('.btn-active');
let nextTab = activeTab.nextElementSibling || firstTab;
let nextSection = nextTab.dataset.section.trim();
let skippedSections = [];
if(!isServiceReady){
skippedSections = ['section-send', 'section-transactions'];
if(nextSection === 'section-overview') nextSection = 'section-welcome';
} else if (wsession.get('fusionProgress')) {
skippedSections = ['section-send'];
}
while(skippedSections.indexOf(nextSection) >=0){
nextTab = nextTab.nextElementSibling;
nextSection = nextTab.dataset.section.trim();
}
changeSection(nextSection);
}
function setCssWalletOpened() {
body[0].classList.add('wallet-opened');
}
function setCssWalletClosed() {
body[0].classList.remove('wallet-opened');
}
function setIconSelected(btnActive) {
// remove the selected icon from all the items
let allButtons = document.querySelectorAll('.navbar button');
for(var i=0; i < allButtons.length;i++){
let img = allButtons[i].querySelector('img');
let normal = img.getAttribute('data-normal');
img.setAttribute('src', normal);
}
// add the selected icon to the current item
if (btnActive) {
let img = btnActive.querySelector('img');
let selected = img.getAttribute('data-selected');
img.setAttribute('src', selected);
}
}
function showNews(listNews){
listNews = listNews || settings.get('news_json', []);
let i = 1;
let itemNews = function(item) {
let created = (function() {
var d = new Date(item.created);
var m = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return d.getDate() + ' ' + m[d.getMonth()] + ' ' + d.getFullYear();
})();
item.content = item.content.replace('<br />', '|');
let title = item.title.substring(0, 50) + (item.title.length > 50 ? '...' : '');
let content = item.content.substring(0, 250) + (item.content.length > 250 ? '...' : '');
content = content.replace('|', '<br />');
let cont_start = (i === 1) || ((i - 1) % 3 == 0) ? '<div class="news-div-content">' : '';
let cont_end = (i % 3 == 0) || (i === listNews.length) ? '</div>' : '';
i++;
return `${cont_start}
<div class="box">
<div class="title clearfix">
<img src="../assets/news/item-icon.png" />
${title}
</div>
<div class="text">${content}</div>
<div class="bottom clearfix">
<span class="date">${created}</span>
<a href="${item.link}" class="external form-bt button-blue">Read more</a>
</div>
</div>
${cont_end}`;
};
let html = '';
for (let i = 0; i < listNews.length; i++) {
html += itemNews(listNews[i]);
}
document.querySelector('#section-news .list').innerHTML = html;
let d = document.getElementById('news-loading');
d.classList.add('hidden');
}
function getNews(){
try{
const news_time = settings.get('news_timestamp', 0);
let curr_time = new Date().getTime();
if ((curr_time - news_time) > (1000 * 60 * 5) || document.querySelector('#section-news .list').innerHTML == '') {
let d = document.getElementById('news-loading');
d.classList.remove('hidden');
require('https').get(config.newsUpdateUrl, (res) => {
var result = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
result += chunk;
});
res.on('end', () => {
try{
var newsList = JSON.parse(result);
settings.set('news_json', newsList);
settings.set('news_timestamp', new Date().getTime());
showNews(newsList);
}catch(e){
log.debug(`Failed to get the news: ${e.message}`);
showNews();
}
});
}).on('error', (e) => {
log.debug(`Failed to get the news: ${e.message}`);
showNews();
});
}
}catch(e){
log.error(`Failed to get the news: ${e.code} - ${e.message}`);
showNews();
}
}
function showOverviewBlocPrice(listBlocPrice){
listBlocPrice = listBlocPrice || settings.get('bloc_price_json', {});
if (!listBlocPrice.hasOwnProperty('bloc_price_btc')) return;
var evolutionWrapper = function(value) {
if (value < 0) {
return `<span class="fall">(${value}%)</span>`;
} else if (value > 0) {
return `<span class="rise">(${value}%)</span>`;
} else {
return `<span class="none">(${value}%)</span>`;
}
};
let d;
d = document.getElementById('bloc-price-btc');
d.innerHTML = listBlocPrice.bloc_price_btc + ' BTC ' + evolutionWrapper(listBlocPrice.bloc_price_btc_evolution);
d = document.getElementById('bloc-price-usd');
d.innerHTML = '$ ' + listBlocPrice.bloc_price_usd + ' USD ' + evolutionWrapper(listBlocPrice.bloc_price_usd_evolution);
d = document.getElementById('trading-volume-btc');
d.innerHTML = listBlocPrice['24_hours_volume_btc'] + ' BTC ' + evolutionWrapper(listBlocPrice['24_hours_volume_btc_evolution']);
d = document.getElementById('trading-volume-usd');
d.innerHTML = '$ ' + listBlocPrice['24_hours_volume_usd'] + ' USD ' + evolutionWrapper(listBlocPrice['24_hours_volume_usd_evolution']);
d = document.getElementById('market-cap-btc');
d.innerHTML = listBlocPrice.market_cap_btc + ' BTC ' + evolutionWrapper(listBlocPrice.market_cap_btc_evolution);
d = document.getElementById('market-cap-usd');
d.innerHTML = '$ ' + listBlocPrice.market_cap_usd + ' USD ' + evolutionWrapper(listBlocPrice.market_cap_usd_evolution);
d = document.getElementById('div-overview-markets-loading');
d.classList.add('hidden');
}
function getBlocPrice() {
try{
const bloc_price_time = settings.get('bloc_price_timestamp', 0);
let curr_time = new Date().getTime();
if ((curr_time - bloc_price_time) > (1000 * 60 * 5) || document.getElementById('bloc-price-btc').innerHTML == '0.00000000 BTC <span class="none">(0.00%)</span>') {
let d = document.getElementById('div-overview-markets-loading');
d.classList.remove('hidden');
require('https').get(config.blocPriceUpdateUrl, (res) => {
var result = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
result += chunk;
});
res.on('end', () => {
try{
var blocPrice = JSON.parse(result);
settings.set('bloc_price_json', blocPrice);
settings.set('bloc_price_timestamp', new Date().getTime());
showOverviewBlocPrice(blocPrice);
}catch(e){
log.debug(`Failed to get the BLOC price: ${e.message}`);
showOverviewBlocPrice();
}
});
}).on('error', (e) => {
log.debug(`Failed to get the BLOC price: ${e.message}`);
showOverviewBlocPrice();
});
}
}catch(e){
log.error(`Failed to get the BLOC price: ${e.code} - ${e.message}`);
showOverviewBlocPrice();
}
}
function showExchange(listExchange) {
listExchange = listExchange || settings.get('exchange_json', {});
if (!listExchange.hasOwnProperty('exchanges')) return;
// exchanges list
let i = 1;
let domainOnly = function(url) {
let domain = url;
domain = domain.replace('http://', '');
domain = domain.replace('https://', '');
domain = domain.split('/')[0];
return domain;
};
let itemExchange = function(item) {
let text = `Buy & sell BLOC on <upper>${item.name}</upper>`;
let domain = domainOnly(item.link);
let cont_start = (i === 1) || ((i - 1) % 4 == 0) ? '<div class="exchanges-div-content">' : '';
let cont_end = (i % 4 == 0) || (i === listExchange.exchanges.length) ? '</div>' : '';
i++;
return `${cont_start}
<div class="box">
<a href="${item.link}" class="external">
<img src="${item.image}" height="60" />
</a>
<div class="text">${text}</div>
<div class="link">
<a href="${item.link}" class="external">${domain}</a>
</div>
</div>
${cont_end}`;
};
let html = '';
for (let i = 0; i < listExchange.exchanges.length; i++) {
html += itemExchange(listExchange.exchanges[i]);
}
document.querySelector('#div-exchanges').innerHTML = html;
// price evolution stats
var evolutionWrapper = function(value) {
if (value < 0) {
return `<span class="fall">(${value}%)</span>`;
} else if (value > 0) {
return `<span class="rise">(${value}%)</span>`;
} else {
return `<span class="none">(${value}%)</span>`;
}
};
let d;
d = document.getElementById('exchange-bloc-price-btc');
d.innerHTML = listExchange.coingecko_stats.bloc_price_btc + ' BTC ' + evolutionWrapper(listExchange.coingecko_stats.bloc_price_btc_evolution);
d = document.getElementById('exchange-bloc-price-usd');
d.innerHTML = '$ ' + listExchange.coingecko_stats.bloc_price_usd + ' USD ' + evolutionWrapper(listExchange.coingecko_stats.bloc_price_usd_evolution);
d = document.getElementById('exchange-trading-volume-btc');
d.innerHTML = listExchange.coingecko_stats['24_hours_volume_btc'] + ' BTC ' + evolutionWrapper(listExchange.coingecko_stats['24_hours_volume_btc_evolution']);
d = document.getElementById('exchange-trading-volume-usd');
d.innerHTML = '$ ' + listExchange.coingecko_stats['24_hours_volume_usd'] + ' USD ' + evolutionWrapper(listExchange.coingecko_stats['24_hours_volume_usd_evolution']);
d = document.getElementById('exchange-market-cap-btc');
d.innerHTML = listExchange.coingecko_stats.market_cap_btc + ' BTC ' + evolutionWrapper(listExchange.coingecko_stats.market_cap_btc_evolution);
d = document.getElementById('exchange-market-cap-usd');
d.innerHTML = '$ ' + listExchange.coingecko_stats.market_cap_usd + ' USD ' + evolutionWrapper(listExchange.coingecko_stats.market_cap_usd_evolution);
// price evolution chart
// https://www.chartjs.org/samples/latest/scales/linear/step-size.html
chartConfig = {
type: 'line',
data: {
labels: [],
datasets: []
},
options: {
maintainAspectRatio: false,
responsive: true,
title: {
display: false,
text: ''
},
tooltips: {
mode: 'index',
intersect: false
},
hover: {
mode: 'nearest',
intersect: true
},
legend: {
labels: {
fontColor: wsutil.chartColors.white,
fontSize: 14,
fontFamily: "'Roboto Condensed', sans-serif"
},
position: 'bottom'
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: false
},
ticks: {
fontColor: wsutil.chartColors.white,
fontSize: 12,
fontFamily: "'Roboto Condensed', sans-serif"
},
gridLines: {
color: "rgba(125, 125, 125, 0.3)",
}
}],
yAxes: [{
id: 'price-btc-y-axis',
scaleLabel: {
display: false
},
ticks: {
display: false
},
gridLines: {
color: "rgba(125, 125, 125, 0.3)",
}
}, {
id: 'price-usd-y-axis',
scaleLabel: {
display: false
},
ticks: {
display: false
},
gridLines: {
display: false
}
}, {
id: 'volume-btc-y-axis',
scaleLabel: {
display: false
},
ticks: {
display: false
},
gridLines: {
display: false
}
}, {
id: 'volume-usd-y-axis',
scaleLabel: {
display: false
},
ticks: {
display: false
},
gridLines: {
display: false
}
}, {
id: 'cap-btc-y-axis',
scaleLabel: {
display: false
},
ticks: {
display: false
},
gridLines: {
display: false
}
}, {
id: 'cap-usd-y-axis',
type: 'linear',
position: 'right',
scaleLabel: {
display: false
},
ticks: {
/*fontColor: wsutil.chartColors.white,
fontSize: 12,
fontFamily: "'Roboto Condensed', sans-serif",
beginAtZero: true,*/
display: false
},
gridLines: {
display: false
}
}]
}
}
};
var ctx = document.getElementById('exchange-chart');
if (typeof chartInstance !== 'undefined') chartInstance.destroy();
chartInstance = new Chart(ctx.getContext('2d'), chartConfig);
// price evolution chart buttons
let cod = document.getElementById('chart-one-day');
let cow = document.getElementById('chart-one-week');
let com = document.getElementById('chart-one-month');
let coy = document.getElementById('chart-one-year');
function resetButtons() {
cod.classList.remove('selected');
cow.classList.remove('selected');
com.classList.remove('selected');
coy.classList.remove('selected');
}
if (!cod.hasAttribute("data-once")) {
cod.setAttribute("data-once", 1);
cod.addEventListener('click', function(){
if (!cod.classList.contains('selected')) {
resetButtons();
cod.classList.add('selected');
updateExchangeChart();
}
});
cow.addEventListener('click', function(){
if (!cow.classList.contains('selected')) {
resetButtons();
cow.classList.add('selected');
updateExchangeChart();
}
});
com.addEventListener('click', function(){
if (!com.classList.contains('selected')) {
resetButtons();
com.classList.add('selected');
updateExchangeChart();
}
});
coy.addEventListener('click', function(){
if (!coy.classList.contains('selected')) {
resetButtons();
coy.classList.add('selected');
updateExchangeChart();
}
});
}
updateExchangeChart();
let m = document.getElementById('exchange-loading');
m.classList.add('hidden');
}
function updateExchangeChart() {
let listExchange = settings.get('exchange_json');
// find the id of the selected button
const buttons = document.querySelectorAll('.div-section-exchange-chart .buttons button');
let id;
for (let i = 0; i < buttons.length; i++) {
if (buttons[i].classList.contains("selected")) {
id = buttons[i].getAttribute('id');
break;
}
}
if (typeof id === 'undefined') return;
// render the chart
function createDataset(label, color, key1, key2, id) {
let newDataset = {
label: label,
backgroundColor: color,
borderColor: color,
data: [],
fill: false,
yAxisID: id
};
listExchange.charts[key1][key2].forEach(function(value) {
newDataset.data.push(value);
});
chartConfig.data.datasets.push(newDataset);
}
const sets = ['day', 'week', 'month', 'year'];
for (let i = 0; i < sets.length; i++) {
if (id == 'chart-one-' + sets[i]) {
chartConfig.data.labels = listExchange.charts[sets[i]].labels;
chartConfig.data.datasets.splice(0, chartConfig.data.datasets.length);
createDataset('BLOC price BTC', wsutil.chartColors.red, sets[i], 'bloc_price_btc', 'price-btc-y-axis');
createDataset('BLOC price USD', wsutil.chartColors.blue, sets[i], 'bloc_price_usd', 'price-usd-y-axis');
createDataset('Volume 24h BTC', wsutil.chartColors.purple, sets[i], '24_hours_volume_btc', 'volume-btc-y-axis');
createDataset('Volume 24h USD', wsutil.chartColors.green, sets[i], '24_hours_volume_usd', 'volume-usd-y-axis');
createDataset('Market cap BTC', wsutil.chartColors.white, sets[i], 'market_cap_btc', 'cap-btc-y-axis');
createDataset('Market cap USD', wsutil.chartColors.yellow, sets[i], 'market_cap_usd', 'cap-usd-y-axis');
chartInstance.update();
}
}
}
function getExchange() {
try{
const exchange_time = settings.get('exchange_timestamp', 0);
let curr_time = new Date().getTime();
let d = document.getElementById('exchange-loading');
if ((curr_time - exchange_time) > (1000 * 60 * 2) || ('loaded' in d.dataset === false)) {
d.dataset.loaded = '1';
d.classList.remove('hidden');
require('https').get(config.exchangeUpdateUrl, (res) => {
var result = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
result += chunk;
});
res.on('end', () => {
try{
var exchangeList = JSON.parse(result);
settings.set('exchange_json', exchangeList);
settings.set('exchange_timestamp', new Date().getTime());
showExchange(exchangeList);
}catch(e){
log.debug(`Failed to get the exchange: ${e.message}`);
showExchange();
}
});
}).on('error', (e) => {
log.debug(`Failed to get the exchange: ${e.message}`);
showExchange();
});
}
}catch(e){
log.error(`Failed to get the exchange: ${e.code} - ${e.message}`);
showExchange();
}
}
// section switcher
function changeSection(sectionId, isSettingRedir) {
if(WALLET_OPEN_IN_PROGRESS){
wsutil.showToast('Opening wallet in progress, please wait...');
return;
}
formMessageReset();
isSettingRedir = isSettingRedir === true ? true : false;
let targetSection = sectionId.trim();
// when overview is loaded, show the sidebar nav
if(targetSection === 'section-welcome'){
sswitch.classList.remove('hidden');
iswitch.classList.remove('hidden');
}
// when settings is loaded, show the warning
if(targetSection === 'section-settings'){
let walletOpened = wsession.get('serviceReady') || false;
if (walletOpened) {
formMessageSet('settings','warning', `If you change the address or port, you will need to restart the wallet`);
settingsButtonBack.classList.add('hidden');
} else {
settingsButtonBack.classList.remove('hidden');
}
}
// when help is loaded, add the wiki link
if(targetSection === 'section-help'){
let d = document.getElementById('wiki-link');
d.setAttribute('href', config.blocWikiUrl);
}
// when about is loaded, add the links and the content
if(targetSection === 'section-about'){
let d = document.getElementById('github-link');
d.setAttribute('href', config.appGitRepo);
d = document.getElementById('app-version');
d.innerHTML = remote.app.getVersion();
d = document.getElementById('service-version');
d.innerHTML = config.walletServiceBinaryVersion;
let donationAddressesList = document.querySelector('#about-donation-addresses .list');
if (donationAddressesList.innerHTML == '') {
let itemDonation = function(item) {
return `<div class="item">
Donate to "${item.name}":<br />
<input tabindex="0" data-noclear="1" title="Click to copy" type="text" class="ctcl" value="${item.address}" readonly="readonly" />
</div>`;
};
let donationOpts = {
valueNames: [],