forked from vizplus/my-viz-plus
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
9953 lines (9463 loc) · 464 KB
/
Copy pathapp.js
File metadata and controls
9953 lines (9463 loc) · 464 KB
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
/* jQuery→cash.js compat shim (#49). cash covers selectors/DOM/events/namespaces/offset 1:1; it lacks
only the four jQuery APIs this app uses: $.ajax, $.extend, $.fn.animate({scrollTop}), $.fn.scrollTop.
Shimming them here keeps every call site (~1300) byte-identical and drops jQuery (~87KB → cash ~16KB). */
(function($){
if(typeof $==='undefined'||$.ajax) return; // no-op under real jQuery
window.jQuery=window.jQuery||$; // some code / plugins use the jQuery global by name
$.extend=$.extend||Object.assign;
$.ajax=function(o){
o=o||{};
var m=(o.type||o.method||'GET').toUpperCase();
var q=new URLSearchParams();
if(o.data) for(var k in o.data){ var v=o.data[k]; if(v!==undefined&&v!==null) q.append(k,v); }
var url=o.url||'', opt={method:m,headers:{}};
if(m==='GET'){ if(q.toString()) url+=(url.indexOf('?')<0?'?':'&')+q.toString(); }
else { opt.body=q.toString(); opt.headers['Content-Type']='application/x-www-form-urlencoded; charset=UTF-8'; }
fetch(url,opt).then(function(r){return r.text();})
.then(function(t){ if(o.success)o.success(t); })
.catch(function(e){ if(o.error)o.error(e); else if(window.console)console.log('ajax',e); });
return {}; // jqXHR placeholder — no call site chains it
};
if($.fn){
$.fn.scrollTop=$.fn.scrollTop||function(v){ if(v===undefined)return window.pageYOffset; window.scrollTo(0,v); return this; };
$.fn.animate=$.fn.animate||function(props,ms){ if(props&&'scrollTop'in props) window.scrollTo({top:props.scrollTop,behavior:(ms>0?'smooth':'auto')}); return this; };
$.fn.ready=$.fn.ready||function(fn){ if(document.readyState!=='loading')fn(); else document.addEventListener('DOMContentLoaded',fn); return this; };
// jQuery shorthand event methods (cash has none): with a handler → bind; no-arg → trigger, using the
// native method (focus/blur/select/click/submit) where it has a real side-effect, else a bubbling Event.
var NATIVE={focus:1,blur:1,select:1,click:1,submit:1};
['resize','scroll','click','dblclick','change','focus','blur','keyup','keydown','keypress','input','select','submit','load'].forEach(function(ev){
if($.fn[ev]) return;
$.fn[ev]=function(fn){
if(typeof fn==='function') return this.on(ev,fn);
return this.each(function(i,el){
if(NATIVE[ev]&&typeof el[ev]==='function') el[ev]();
else if(el.dispatchEvent) el.dispatchEvent(new Event(ev,{bubbles:true}));
});
};
});
// jQuery legacy event aliases cash lacks: .bind/.unbind → .on/.off (same signatures).
$.fn.bind=$.fn.bind||function(ev,fn){ return this.on(ev,fn); };
$.fn.unbind=$.fn.unbind||function(ev,fn){ return fn?this.off(ev,fn):this.off(ev); };
}
})(window.$);
var api_nodes=[
'https://api.viz.world/',
'https://node.viz.cx/',
'https://viz.lexai.top/',
'https://mirror.viz.world/',
];
var default_api_node=api_nodes[0];
var api_nodes_addon={'list':[]};
// A copy opened straight from disk is the one shipped next to a node the user runs
// themselves (the desktop bundle), and file:// is one of the few origins a browser
// lets reach 127.0.0.1 at all -- the hosted wallet is blocked from doing so by
// Local Network Access. Offer that node there, first in the list and preselected.
// A node the user picked earlier still wins: api_nodes_addon is read further below.
var local_api_node='http://127.0.0.1:8090/';
if('file:'==window.location.protocol){
api_nodes.unshift(local_api_node);
default_api_node=local_api_node;
}
var dao_request_ranges=[[1,999999]];
var invite_user='invite';
var invite_active_key='5KcfoRuDfkhrLCxVcE9x51J6KN9aM9fpb78tLrvvFckxVV6FyFW';
/* Free account registration via the start.viz.world proof-of-work open API. The account
is created on the VIZ MAINNET (the faucet), independent of the node this wallet points at. */
var reg_base='https://start.viz.world';
var reg_pow_offset=3; // must match config.pow.offset on the server
var reg_pow_prefix='51'; // must match config.pow.prefix
var reg_grind_chunk=400;
var standalone=false;
var standalone_fullpath='';
var standalone_path='';
var standalone_search='';
function parse_standalone_fullpath(){
standalone_fullpath=window.location.hash.substr(1);
standalone_path='';
standalone_search='';
if(-1==standalone_fullpath.indexOf('?')){
standalone_path=standalone_fullpath;
}
else{
standalone_path=standalone_fullpath.substring(0,standalone_fullpath.indexOf('?'));
standalone_search=standalone_fullpath.substring(standalone_fullpath.indexOf('?'));
}
if(''==standalone_path){
standalone_path='/';
}
}
if(null!=localStorage.getItem('api_nodes_addon')){
api_nodes_addon=JSON.parse(localStorage.getItem('api_nodes_addon'));
for(i in api_nodes_addon.list){
if(null!=api_nodes_addon.list[i]){
if(-1==api_nodes.indexOf(api_nodes_addon.list[i])){
api_nodes.push(api_nodes_addon.list[i]);
}
}
else{
delete api_nodes_addon.list[i];
}
}
if(typeof api_nodes_addon.default != 'undefined'){
if('https://viz.lexai.host/'==api_nodes_addon.default){
api_nodes_addon.default='https://viz.lexai.top/';
}
default_api_node=api_nodes_addon.default;
}
}
console.log('using node',default_api_node);
viz.config.set('websocket',default_api_node);
start_node_down_check();
// Testnet indicator: if the active node URL looks like a testnet, mark the header so users can
// visually tell they are NOT on the real chain (owner 2026-07-11). Called on load + node switch.
function update_testnet_badge(){
var testnet=/testnet/i.test(''+default_api_node);
if(testnet){
$('.testnet-badge').css('display','');
$('.header').addClass('testnet-mode');
$('body').addClass('testnet-mode');
}
else{
$('.testnet-badge').css('display','none');
$('.header').removeClass('testnet-mode');
$('body').removeClass('testnet-mode');
}
}
$(function(){ update_testnet_badge(); });
// Стандартное сообщение об отказе говорит про «публичную ноду» и советует зайти позже. Для ноды,
// которую пользователь поднял у себя (десктоп-бандл рядом с vizd), неверно и то и другое: нода не
// публичная, а ждать бессмысленно — обычно она просто не запущена. Читаем текст через функцию, а
// не напрямую из ltmp_arr, потому что при смене языка ltmp_arr переприсваивается целиком.
function node_error_text(){
var local=/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/i.test(''+default_api_node);
return (local&<mp_arr.local_node_error)?ltmp_arr.local_node_error:ltmp_arr.default_node_error;
}
function select_api_node(node){
node=typeof node==='undefined'?api_nodes[0]:node;
default_api_node=node;
api_nodes_addon.default=default_api_node;
console.log('using node',default_api_node);
viz.config.set('websocket',default_api_node);
update_testnet_badge();
save_session();
hide_node_down_notice();
start_node_down_check();
if(standalone){
parse_standalone_fullpath();
change_state(standalone_path+encodeURIComponent(standalone_search),{},false);
}
else{
change_state(document.location.pathname+document.location.search,{},false);
}
}
function approved_api_node(node,latency){
clearTimeout(check_node_timer);
let i=api_nodes_addon.list.indexOf(node);
if(-1==i){
api_nodes_addon.list.push(node);
let j=api_nodes.indexOf(node);
if(-1==j){
api_nodes.push(node);
}
}
default_api_node=node;
api_nodes_addon.default=default_api_node;
viz.config.set('websocket',default_api_node);
update_testnet_badge();
save_session();
hide_node_down_notice();
start_node_down_check();
if(standalone){
parse_standalone_fullpath();
change_state(standalone_path+encodeURIComponent(standalone_search),{},false);
}
else{
change_state(document.location.pathname+document.location.search,{},false);
}
}
/* Localisation Template*/
function ltmp(ltmp_str,ltmp_args){
let ltmp_includes_pattern = /%%([a-zA-Z_0-9]*)%%/gi;
let ltmp_includes=ltmp_str.match(ltmp_includes_pattern);
if(null!=ltmp_includes){
for(let ltmp_i in ltmp_includes){
let var_name=ltmp_includes[ltmp_i].substr(2);
var_name=var_name.substr(0,var_name.length - 2);
if(typeof ltmp_arr[var_name] !== 'undefined'){
ltmp_str=ltmp_str.split(ltmp_includes[ltmp_i]).join(ltmp(ltmp_arr[var_name]));
}
}
}
for(let ltmp_i in ltmp_args){
ltmp_str=ltmp_str.split('{'+ltmp_i+'}').join(ltmp_args[ltmp_i]);
}
//remove empty args
let ltmp_prop_arr=ltmp_str.match(/\{[a-z_\-]*\}/gm);
for(let ltmp_i in ltmp_prop_arr){
ltmp_str=ltmp_str.split(ltmp_prop_arr[ltmp_i]).join('');
}
return ltmp_str;
}
function select_lang(lang){
if(typeof available_langs[lang] !== 'undefined'){
selected_lang=lang;
localStorage.setItem('lang',selected_lang);
ltmp_arr=window['ltmp_'+lang+'_arr'];
preset_template(function(){
dom_bindings(function(){
if(standalone){
parse_standalone_fullpath();
// standalone_search уже содержит literal "?..." из хэша — передаём как есть.
// encodeURIComponent здесь ломал "?" → change_state не парсил параметры, путь
// вида /login/%3Fback%3D... не матчил view → серый экран (баг смены языка на /login/?back=).
change_state(standalone_path+standalone_search,{},false);
}
else{
change_state(document.location.pathname+document.location.search,{},false);
}
});
});
}
}
var langs_arr={
'en-US':'en',
'en-GB':'en',
'en':'en',
'ru-RU':'ru',
'ru':'ru',
'zh-CN':'zh',//китайский язык (упрощенное письмо), Китай
'zh-TW':'zh',//китайский язык (традиционное письмо), Тайвань
'zh-HK':'zh',//китайский язык (традиционное письмо), Гонконг
'zh-SG':'zh',//китайский язык (упрощенное письмо), Сингапур
'zh':'zh'
};
var available_langs={
'en':'English',
'ru':'Русский',
'zh':'中文',
};
var default_lang='en';
var selected_lang=default_lang;
if(null!=localStorage.getItem('lang')){
if(typeof available_langs[localStorage.getItem('lang')] !== 'undefined'){
selected_lang=langs_arr[localStorage.getItem('lang')];
}
}
else{
for(let i in window.navigator.languages){
if(typeof langs_arr[window.navigator.languages[i]] !== 'undefined'){
let try_lang=langs_arr[window.navigator.languages[i]];
if(typeof available_langs[try_lang] !== 'undefined'){
selected_lang=langs_arr[try_lang];
break;
}
}
}
}
var ltmp_arr=window['ltmp_'+selected_lang+'_arr'];
function plural_str(number,one,two,five){
let n=Math.abs(number);
n%=100;
if(n>=5&&n<=20){
return five;
}
n%=10;
if(n===1) {
return one;
}
if(n>=2&&n<=4){
return two;
}
return five;
}
var check_node_timer=0;
function add_api_node(node){
$('.nodes .add-api-node-error').html('');
if(''!=node){
let protocol='none';
let node_protocol=node.substring(0,node.indexOf(':'));
//console.log('node_protocol',node_protocol);
if('http'==node_protocol||'https'==node_protocol){
protocol='http';
}
if('ws'==node_protocol||'wss'==node_protocol){
protocol='websocket';
}
if('websocket'==protocol){
$('.nodes .add-api-node-error').html(ltmp_arr.node_request);
let socket=new WebSocket(node);
clearTimeout(check_node_timer);
check_node_timer=setTimeout(function(){
$('.nodes .add-api-node-error').html(ltmp_arr.node_not_respond);
},1000);
let latency_start=new Date().getTime();
let latency=-1;
socket.onmessage=function(event){
latency=new Date().getTime() - latency_start;
//console.log(event);
try{
json=JSON.parse(event.data);
if((typeof json.result!='undefined')&&(typeof json.result.head_block_number!='undefined')){
approved_api_node(node,latency);
}
else{
$('.nodes .add-api-node-error').html(ltmp_arr.node_wrong_response);
console.log(json);
}
}
catch(err){
$('.nodes .add-api-node-error').html(ltmp_arr.node_wrong_response);
console.log(err);
}
socket.close();
}
socket.onopen=function(){
socket.send('{"id":1,"method":"call","jsonrpc":"2.0","params":["database_api","get_dynamic_global_properties",[]]}');
};
}
if('http'==protocol){
$('.nodes .add-api-node-error').html(ltmp_arr.node_request);
let xhr=new XMLHttpRequest();
clearTimeout(check_node_timer);
check_node_timer=setTimeout(function(){
$('.nodes .add-api-node-error').html(ltmp_arr.node_not_respond);
},1000);
let latency_start=new Date().getTime();
let latency=-1;
xhr.overrideMimeType('text/plain');
xhr.open('POST',node);
xhr.setRequestHeader('accept','application/json, text/plain, */*');
xhr.setRequestHeader('content-type','application/json');
xhr.onreadystatechange = function() {
if(4==xhr.readyState && 200==xhr.status){
latency=new Date().getTime() - latency_start;
try{
json=JSON.parse(xhr.responseText);
if((typeof json.result!='undefined')&&(typeof json.result.head_block_number!='undefined')){
approved_api_node(node,latency);
}
else{
$('.nodes .add-api-node-error').html(ltmp_arr.node_wrong_response);
console.log(json);
console.log(xhr);
}
}
catch(err){
$('.nodes .add-api-node-error').html(ltmp_arr.node_wrong_response);
console.log(err);
}
}
}
xhr.send('{"id":1,"method":"call","jsonrpc":"2.0","params":["database_api","get_dynamic_global_properties",[]]}');
}
if('none'==protocol){
$('.nodes .add-api-node-error').html(ltmp_arr.node_protocol_error);
}
}
else{
$('.nodes .add-api-node-error').html(ltmp_arr.node_empty_error);
}
}
function remove_api_node(node){
if(''!=node){
let i=api_nodes_addon.list.indexOf(node);
if(-1!=i){
delete api_nodes_addon.list[i];
let j=api_nodes.indexOf(node);
if(-1!=j){
delete api_nodes[j];
}
}
if(default_api_node==node){
default_api_node=api_nodes[0];
}
api_nodes_addon.default=default_api_node;
viz.config.set('websocket',default_api_node);
update_testnet_badge();
save_session();
if(standalone){
parse_standalone_fullpath();
change_state(standalone_path+encodeURIComponent(standalone_search),{},false);
}
else{
change_state(document.location.pathname+document.location.search,{},false);
}
}
}
function pass_gen(length,to_wif){
length=typeof length==='undefined'?100:length;
to_wif=typeof to_wif==='undefined'?true:to_wif;
let charset='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-=_:;.,@!^&*$';
let ret='';
for (var i=0,n=charset.length;i<length;++i){
ret+=charset.charAt(Math.floor(Math.random()*n));
}
if(!to_wif){
return ret;
}
let wif=viz.auth.toWif('',ret,'');
return wif;
}
var keys=[];
keys=viz.auth.getPrivateKeys('',pass_gen(100),['master','active','regular','memo']);
var validator_props_captions={
'account_creation_fee':ltmp_arr.validator_props_captions.account_creation_fee,
'create_account_delegation_ratio':ltmp_arr.validator_props_captions.create_account_delegation_ratio,
'create_account_delegation_time':ltmp_arr.validator_props_captions.create_account_delegation_time,
'bandwidth_reserve_percent':ltmp_arr.validator_props_captions.bandwidth_reserve_percent,
'bandwidth_reserve_below':ltmp_arr.validator_props_captions.bandwidth_reserve_below,
'committee_request_approve_min_percent':ltmp_arr.validator_props_captions.committee_request_approve_min_percent,
'min_delegation':ltmp_arr.validator_props_captions.min_delegation,
'vote_accounting_min_rshares':ltmp_arr.validator_props_captions.vote_accounting_min_rshares,
'maximum_block_size':ltmp_arr.validator_props_captions.maximum_block_size,
'inflation_validator_percent':ltmp_arr.validator_props_captions.inflation_validator_percent,
'inflation_ratio_committee_vs_reward_fund':ltmp_arr.validator_props_captions.inflation_ratio_committee_vs_reward_fund,
'inflation_recalc_period':ltmp_arr.validator_props_captions.inflation_recalc_period,
'data_operations_cost_additional_bandwidth':ltmp_arr.validator_props_captions.data_operations_cost_additional_bandwidth,
'validator_miss_penalty_percent':ltmp_arr.validator_props_captions.validator_miss_penalty_percent,
'validator_miss_penalty_duration':ltmp_arr.validator_props_captions.validator_miss_penalty_duration,
'create_invite_min_balance':ltmp_arr.validator_props_captions.create_invite_min_balance,
'committee_create_request_fee':ltmp_arr.validator_props_captions.committee_create_request_fee,
'create_paid_subscription_fee':ltmp_arr.validator_props_captions.create_paid_subscription_fee,
'account_on_sale_fee':ltmp_arr.validator_props_captions.account_on_sale_fee,
'subaccount_on_sale_fee':ltmp_arr.validator_props_captions.subaccount_on_sale_fee,
'validator_declaration_fee':ltmp_arr.validator_props_captions.validator_declaration_fee,
'withdraw_intervals':ltmp_arr.validator_props_captions.withdraw_intervals,
'distribution_epoch_length':ltmp_arr.validator_props_captions.distribution_epoch_length,
};
var validator_props_percent=['bandwidth_reserve_percent','committee_request_approve_min_percent','inflation_validator_percent','inflation_ratio_committee_vs_reward_fund','data_operations_cost_additional_bandwidth','validator_miss_penalty_percent',
//HF14 prediction-market basis-point params (10000 = 100% on chain; shown/edited as %).
//Only params the node bounds by <=10000 belong here — NOT whole-percent (<=100) leverage/coverage
//params (rendered raw) nor ppm params, to keep display and re-broadcast byte-consistent with C++.
'pm_max_oracle_fee_percent','pm_default_time_penalty_percent','pm_dispute_approve_min_percent','pm_oracle_penalty_percent','pm_no_contest_penalty_percent','pm_commit_no_reveal_penalty_percent','pm_lazy_alloc_percent','pm_lazy_max_total_alloc_percent','pm_lazy_recall_step_percent','pm_lazy_emergency_penalty_percent','pm_lazy_min_liquidity_fee_percent','pm_leverage_max_per_position_bp'];
var validator_props_hf13_defaults={'distribution_epoch_length':28800};
// #689: the four vote caps (committee + dispute) live in chain_properties_pm (HF14), but the two
// committee fields are NOT pm_-prefixed. The pm_-prefix checks would drop them from the form, from
// the seed-from-live-defaults step and from the validator list. This set marks the full pm-section
// so they stay grouped with the other HF14 params everywhere the pm_ prefix is tested.
var validator_pm_section_extra_fields=['committee_votes_per_request','committee_vote_min_vesting'];
function is_pm_section_field(k){
k=''+k;
return ('pm_'===k.substring(0,3))||(-1!==validator_pm_section_extra_fields.indexOf(k));
}
var request_status_arr={
'0':ltmp_arr.request_status_arr['0'],
'1':ltmp_arr.request_status_arr['1'],
'2':ltmp_arr.request_status_arr['2'],
'3':ltmp_arr.request_status_arr['3'],
'4':ltmp_arr.request_status_arr['4'],
'5':ltmp_arr.request_status_arr['5'],
}
var dgp={};
var update_dgp_timer=0;
function update_dgp(auto){
auto=typeof auto==='undefined'?false:auto;
viz.api.getDynamicGlobalProperties(function(err,response){
if(!err){
dgp=response;
if('block'==$('.page-award').css('display')){
$('.page-award .range-slider-input').change();
}
if('block'==$('.page-fund-requests').css('display')){
$('.page-fund-requests .fund-balance').html(number_thousands(show_balance_in_tokens(dgp.committee_fund,true)));
}
}
});
if(auto){
clearTimeout(update_dgp_timer);
update_dgp_timer=setTimeout("update_dgp(true)",3000);
}
}
var update_chain_properties_timer=0;
var node_down_check_timer=0;
var node_down_fallback_primary='https://api.viz.world/';
var node_down_fallback_secondary='https://mirror.viz.world/';
function get_fallback_node(){
if(default_api_node==node_down_fallback_primary){
return node_down_fallback_secondary;
}
return node_down_fallback_primary;
}
function show_node_down_notice(){
let fallback=get_fallback_node();
let fallback_host=fallback.replace(/https?:\/\//,'').replace(/\/+$/,'');
$('.node-down-notice .node-down-text').html(ltmp_arr.node_down_notice);
$('.node-down-notice .switch-node-btn').html(ltmp(ltmp_arr.node_down_switch_btn,{node:fallback_host}));
$('.node-down-notice .switch-node-btn').attr('rel',fallback);
$('.node-down-notice').css('display','block');
}
function hide_node_down_notice(){
$('.node-down-notice').css('display','none');
}
function check_node_alive(){
let xhr=new XMLHttpRequest();
xhr.overrideMimeType('text/plain');
xhr.open('POST',default_api_node);
xhr.setRequestHeader('accept','application/json, text/plain, */*');
xhr.setRequestHeader('content-type','application/json');
xhr.timeout=5000;
xhr.onreadystatechange=function(){
if(4==xhr.readyState){
if(200==xhr.status){
try{
let json=JSON.parse(xhr.responseText);
if((typeof json.result!='undefined')&&(typeof json.result.head_block_number!='undefined')){
hide_node_down_notice();
return;
}
}
catch(err){
console.log('node health check parse error',err);
}
}
show_node_down_notice();
}
};
xhr.ontimeout=function(){
show_node_down_notice();
};
xhr.onerror=function(){
show_node_down_notice();
};
xhr.send('{"id":1,"method":"call","jsonrpc":"2.0","params":["database_api","get_dynamic_global_properties",[]]}');
}
function start_node_down_check(){
clearTimeout(node_down_check_timer);
check_node_alive();
node_down_check_timer=setTimeout(function(){
start_node_down_check();
},30000);
}
function update_chain_properties(){
viz.api.getChainProperties(function(err,response){
if(!err){
if('block'==$('.section-fund-request').css('display')){
$('.section-fund-request .chain-properties[rel=committee_request_approve_min_percent]').html(parseInt(response.committee_request_approve_min_percent)/100);
}
if('block'==$('.page-checks').css('display')){
$('.page-checks .create-invite-min-balance').html(show_balance_in_tokens(response.create_invite_min_balance,true));
}
}
});
}
var check_invite_timer=0;
var check_invite=function(code,el){
el.css('display','block');
if(viz.auth.isWif(code)){
el.find('.invites-claim-code-balance').removeClass('red');
el.find('.invites-claim-code-balance').html('…');
let public_key=viz.auth.wifToPublic(code);
viz.api.getInviteByKey(public_key,function(err,response){
if(!err){
if(0==response.status){
el.find('.invites-claim-code-balance').html(show_balance_in_tokens(response.balance,true));
}
else{
el.find('.invites-claim-code-balance').addClass('red');
el.find('.invites-claim-code-balance').html(ltmp(ltmp_arr.invites_code_already_claimed,{amount:show_balance_in_tokens(response.claimed_balance,true),receiver:response.receiver}));
}
}
else{
el.find('.invites-claim-code-balance').addClass('red');
el.find('.invites-claim-code-balance').html(ltmp_arr.invites_code_not_found);
console.log(err);
}
});
}
else{
if(viz.auth.isPubkey(code)){
el.find('.invites-claim-code-balance').removeClass('red');
el.find('.invites-claim-code-balance').html('…');
viz.api.getInviteByKey(code,function(err,response){
if(!err){
if(0==response.status){
el.find('.invites-claim-code-balance').html(show_balance_in_tokens(response.balance,true));
}
else{
el.find('.invites-claim-code-balance').addClass('red');
el.find('.invites-claim-code-balance').html(ltmp(ltmp_arr.invites_code_already_claimed,{amount:show_balance_in_tokens(response.claimed_balance,true),receiver:response.receiver}));
}
}
else{
el.find('.invites-claim-code-balance').addClass('red');
el.find('.invites-claim-code-balance').html(ltmp_arr.invites_code_not_found);
console.log(err);
}
});
}
else{
el.find('.invites-claim-code-balance').addClass('red');
el.find('.invites-claim-code-balance').html(ltmp_arr.invites_invalid_code);
}
}
}
var check_login_timer=0;
var check_login=function(el,el2){
var account_login=el.val();
if(account_login.length>2){
var first_char=account_login.substr(0,1);
var last_char=account_login.substr(-1,1);
var parent_login='';
if(-1!=account_login.indexOf('.')){
parent_login=account_login.substr(account_login.indexOf('.')+1);
}
if(''!=parent_login && parent_login!=current_user){
el.css('border-color','#ef1c1c');
el2.html(ltmp(ltmp_arr.check_login_subaccount_error,{account:current_user}));
}
else
if(!/^([a-z])$/.test(first_char)){
el.css('border-color','#ef1c1c');
el2.html(ltmp_arr.check_login_starting_error);
}
else
if(!/^([a-z0-9])$/.test(last_char)){
el.css('border-color','#ef1c1c');
el2.html(ltmp_arr.check_login_ending_error);
}
else{
viz.api.getAccounts([account_login],function(err,response){
if(response[0]){
el.css('border-color','#ef1c1c');
el2.html(ltmp_arr.check_login_already_exist);
}
else{
el.css('border-color','#0db11e');
el2.html('');
}
});
}
}
else{
el.css('border-color','#ccc');
el2.html('');
}
}
jQuery.fn.selText = function() {
var obj=this[0];
if(document.body.createTextRange){
var range=obj.offsetParent.createTextRange();
range.moveToElementText(obj);
range.select();
}
else
if(window.getSelection){
var selection=obj.ownerDocument.defaultView.getSelection();
var range=obj.ownerDocument.createRange();
range.selectNodeContents(obj);
selection.removeAllRanges();
selection.addRange(range);
}
else{
var selection=obj.ownerDocument.defaultView.getSelection();
selection.setBaseAndExtent(obj,0,obj,1);
}
return this;
}
function escape_html(text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g,function(m){return map[m];});
}
$(window).on('hashchange',function(e){
e.preventDefault();
if(''!=window.location.hash){
// hash can be a route ("#/send/"), not a valid selector — query the anchor safely (jQuery/Sizzle
// tolerated $('#/send/'); cash/native qsa throws), then scroll to it if it exists.
var _anchor=null; try{ _anchor=document.querySelector('.index[data-index="'+window.location.hash+'"]'); }catch(e){}
if(_anchor){
$('body,html').animate({scrollTop:parseInt($(_anchor).offset().top) - 64 - 10},1000);
}
}
else{
$(window).scrollTop(0);
}
});
function app_keyboard(e){
if(!e)e=window.event;
var key=(e.charCode)?e.charCode:((e.keyCode)?e.keyCode:((e.which)?e.which:0));
let char=String.fromCharCode(key);
var target=e.target || e.srcElement;
if((key==13 || key==32) && target && $(target).attr('role')=='button') {
e.preventDefault();
$(target).click();
}
//console.log(key,char);
/*
if(key==27){
e.preventDefault();
}
*/
}
function app_a11y_enhance(){
$('html').attr('lang',selected_lang||default_lang||'en');
$('[data-href]').each(function(i,el){
var href=$(el).attr('data-href');
if(el.tagName&&el.tagName.toLowerCase()==='a' && href && !$(el).attr('href')){
$(el).attr('href',standalone?('#'+href):href);
}
});
$('a:not([href])').each(function(i,el){
if($(el).attr('role')!=='button') $(el).attr('role','button');
if(!$(el).attr('tabindex')) $(el).attr('tabindex','0');
});
$('.menu-button-action').attr('aria-expanded',$('.absolute-view.menu-list').css('display')==='block'?'true':'false');
$('.absolute-view.menu-list').attr('aria-hidden',$('.absolute-view.menu-list').css('display')==='block'?'false':'true');
$('.drop-down').attr('aria-expanded',$('.users-drop-down').css('display')==='block'?'true':'false');
$('.user-buttons .add-account').attr({'aria-label':ltmp_arr.header_add_account||'Add account','title':ltmp_arr.header_add_account||'Add account'});
$('.user-buttons .drop-down').attr({'aria-label':ltmp_arr.header_switch_account||'Switch account','title':ltmp_arr.header_switch_account||'Switch account'});
$('.user-buttons .logout').attr({'aria-label':ltmp_arr.header_logout||'Log out','title':ltmp_arr.header_logout||'Log out'});
$('.wallet-lock-btn').attr({'aria-label':ltmp_arr.header_lock_wallet||'Lock wallet','title':ltmp_arr.header_lock_wallet||'Lock wallet'});
$('.error, [class$="-error"], [class*="-error "], .success, [class$="-success"], [class*="-success "], .node-down-notice, .node-down-text').attr({'role':'status','aria-live':'polite','aria-atomic':'true'});
$('.submit-button-ring, .icon-check').attr('aria-hidden','true');
$('.select-user, .remove-user, .view-account, .view-percent, .view-memo, .view-tokens, .view-key, .go-top, [class$="-action"], [class*="-action "]').each(function(i,el){
var tag=(el.tagName||'').toLowerCase();
if(tag==='a' || tag==='button' || tag==='input' || tag==='select' || tag==='textarea' || tag==='img' || tag==='svg') return;
if(!$(el).attr('role')) $(el).attr('role','button');
if(!$(el).attr('tabindex')) $(el).attr('tabindex','0');
});
}
function number_thousands(n){
str=''+n;
str_arr=str.split('.');
let minus=false;
if(n<0){
str_arr[0]=str_arr[0].substr(1);
minus=true;
}
lstr_len=str_arr[0].length;
for(i=lstr_len;i>0;--i){
if(0==(-lstr_len+i)%3){
str_arr[0]=str_arr[0].substr(0,i)+' '+str_arr[0].substr(i);
}
}
str_arr[0]=str_arr[0].trim();
return (minus?'−':'')+str_arr[0]+(str_arr[1]?'.'+str_arr[1]:'');
}
function download(filename,text) {
var link = document.createElement('a');
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
link.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
link.dispatchEvent(event);
}
else {
link.click();
}
}
function ipfs_link(cid){
return 'https://cloudflare-ipfs.com/ipfs/'+cid;
}
function sia_link(skylink){
return 'https://siasky.net/'+skylink;
}
function safe_image(link){
let result='';
let error=false;
if(0==link.indexOf('https://')){
result=link;
}
else
if(0==link.indexOf('ipfs://')){
result=ipfs_link(link.substring(7));
}
else
if(0==link.indexOf('sia://')){
result=sia_link(link.substring(6));
}
else
if(0==link.indexOf('http://')){
error=true;//no http
}
else
if(0==link.indexOf('data:')){
error=true;//no encoded
}
else{
error=true;//unknown
}
if(error){
return false;
}
return result;
}
var users={};
var current_user='';
var current_user_active_paid_subscribes=[];
var current_view='';
var calc_max_delegation_timer=0;
function calc_max_delegation(){
let max_delegation=parseFloat($('.page-delegate-shares .shares-balance .vesting-shares').data('available-vesting-shares')).toFixed(2);
max_delegation-=parseFloat($('.page-delegate-shares .shares-balance .vesting-shares').data('withdraw-amount')).toFixed(2);
max_delegation=Math.max(0,max_delegation);
$('.page-delegate-shares .delegate-shares-max-tokens-amount').html(number_thousands(show_balance_in_tokens(max_delegation,true)));
$('.page-delegate-shares .delegate-shares-max-tokens-amount').attr('data-vesting-shares',max_delegation);
let delegatee=$('.page-delegate-shares input[name=delegate-shares-account]').val();
viz.api.getVestingDelegations(current_user,delegatee,1,0,function(err,response){
if(!err){
console.log(response);
if(typeof response[0] !== 'undefined'){
if(delegatee==response[0].delegatee){
max_delegation-=parseFloat(response[0].vesting_shares).toFixed(2);
max_delegation=Math.max(0,max_delegation);
$('.page-delegate-shares .delegate-shares-max-tokens-amount').html(number_thousands(show_balance_in_tokens(max_delegation,true)));
$('.page-delegate-shares .delegate-shares-max-tokens-amount').attr('data-vesting-shares',max_delegation);
}
}
}
});
}
function update_delegations_tables(){
viz.api.getVestingDelegations(current_user,0,1000,0,function(err,response){
if(!err){
let result='';
if(0==response.length){
result+='<div class="columns-view"><div class="column-view column-1">'+ltmp_arr.default_no_items+'</div></div>';
}
for(delegation in response){
result+='<div class="columns-view">'
+'<div class="column-view column-3"><span class="adaptive-show">'+ltmp_arr.delegations_account_adaptive_caption+' </span>'+response[delegation].delegatee+'</div>'
+'<div class="column-view column-3"><span class="adaptive-show">'+ltmp_arr.delegations_social_capital_adaptive_caption+' </span>'+number_thousands(show_balance_in_tokens(parseFloat(response[delegation].vesting_shares),true))+'</div>'
+'<div class="column-view column-flex">'+(new Date().getTime()>Date.parse(response[delegation].min_delegation_time)?'<a class="inline-button no-margin undelegate-shares-action" data-account="'+response[delegation].delegatee+'">'+ltmp_arr.delegations_revocation_button+'</a>':ltmp(ltmp_arr.delegations_revocation_info,{date:show_date(response[delegation].min_delegation_time,true)+ltmp_arr.default_date_utc}))+'</div>'
+'</div>';
}
$('.page-delegate-shares .outcome-delegations .table-data').html(result);
viz.api.getExpiringVestingDelegations(current_user,new Date().toISOString().substr(0,19),1000,function(err,response){
if(!err){
let result='';
let summary_expiring_shares=0;
for(expiration in response){
summary_expiring_shares+=parseFloat(response[expiration].vesting_shares);
}
if(0<summary_expiring_shares){
result+='<div class="columns-view">'
+'<div class="column-view column-3">'+ltmp_arr.delegations_awaiting_return+'</div>'
+'<div class="column-view column-3">'+number_thousands(show_balance_in_tokens(summary_expiring_shares,true))+'</div>'
+'<div class="column-view column-flex">—</div>'
+'</div>';
$('.page-delegate-shares .outcome-delegations .table-data').append(result);
}
}
});
}
else{
$('.page-delegate-shares .outcome-delegations .table-data').html('<p>'+node_error_text()+'</p>');
}
});
viz.api.getVestingDelegations(current_user,0,1000,1,function(err,response){
if(!err){
let result='';
if(0==response.length){
result+='<div class="columns-view"><div class="column-view column-1">'+ltmp_arr.default_no_items+'</div></div>';
}
for(delegation in response){
result+='<div class="columns-view">'
+'<div class="column-view column-3"><span class="adaptive-show">'+ltmp_arr.delegations_account_adaptive_caption+' </span>'+response[delegation].delegator+'</div>'
+'<div class="column-view column-flex"><span class="adaptive-show">'+ltmp_arr.delegations_social_capital_adaptive_caption+' </span>'+number_thousands(show_balance_in_tokens(parseFloat(response[delegation].vesting_shares),true))+'</div>'
//+'<div class="column-view column-flex">'+response[delegation].min_delegation_time+ltmp_arr.default_date_utc+'</div>'
+'</div>';
}
$('.page-delegate-shares .income-delegations .table-data').html(result);
}
else{
$('.page-delegate-shares .income-delegations .table-data').html('<div class="columns-view"><div class="column-view column-1">'+node_error_text()+'</div></div>');
}
});
}
function update_shares_balance(el,data){
let true_balance=parseFloat(data.balance);
let floor_balance=Math.floor(100*true_balance)/100;
let vesting_shares=parseFloat(data.vesting_shares);
let floor_vesting_shares=Math.floor(100*vesting_shares)/100;
let delegated_vesting_shares=parseFloat(data.delegated_vesting_shares);
let floor_delegated_vesting_shares=Math.floor(100*delegated_vesting_shares)/100;
let received_vesting_shares=parseFloat(data.received_vesting_shares);
let floor_received_vesting_shares=Math.floor(100*received_vesting_shares)/100;
let effective_vesting_shares=vesting_shares + received_vesting_shares - delegated_vesting_shares;
let floor_effective_vesting_shares=Math.floor(100*effective_vesting_shares)/100;
let available_vesting_shares=vesting_shares - delegated_vesting_shares;
let floor_available_vesting_shares=Math.floor(100*available_vesting_shares)/100;
let withdrawn=parseFloat(data.withdrawn);
let to_withdraw=parseFloat(data.to_withdraw);
let withdraw_amount=to_withdraw-withdrawn;
let last_vote_time=Date.parse(data.last_vote_time);
let delta_time=parseInt((new Date().getTime() - last_vote_time+(new Date().getTimezoneOffset()*60000))/1000);
let energy=data.energy;
let new_energy=parseInt(energy+(delta_time*10000/432000));//CHAIN_ENERGY_REGENERATION_SECONDS 5 days
if(new_energy>10000){
new_energy=10000;
}
el.find('.vesting-shares').html('');
el.find('.delegated-vesting-shares').html('');
el.find('.received-vesting-shares').html('');
el.find('.effective-vesting-shares').html('');
el.find('.vesting-shares').data('vesting-shares',(floor_vesting_shares).toFixed(2));
el.find('.vesting-shares').data('available-vesting-shares',(floor_available_vesting_shares).toFixed(2));
el.find('.vesting-shares').data('withdraw-amount',(withdraw_amount/1000000).toFixed(2));
el.find('.vesting-shares').append('<span class="adaptive-show">'+ltmp_arr.social_capital_own_adaptive_caption+' </span>'+number_thousands((floor_vesting_shares).toFixed(2))+' viz');
el.find('.delegated-vesting-shares').data('delegated-vesting-shares',(floor_delegated_vesting_shares).toFixed(2));
if(floor_delegated_vesting_shares>0){
el.find('.delegated-vesting-shares').append('<div><span class="adaptive-show">'+ltmp_arr.social_capital_delegated_adaptive_caption+' </span>−'+number_thousands((floor_delegated_vesting_shares).toFixed(2))+' viz</div>');
}
el.find('.received-vesting-shares').data('received-vesting-shares',(floor_received_vesting_shares).toFixed(2));
if(floor_received_vesting_shares>0){
el.find('.received-vesting-shares').append('<div><span class="adaptive-show">'+ltmp_arr.social_capital_received_adaptive_caption+' </span>+'+number_thousands((floor_received_vesting_shares).toFixed(2))+' viz</div>');
}
if(''==el.find('.received-vesting-shares').html()){
el.find('.received-vesting-shares').html('—');
}
el.find('.effective-vesting-shares').data('effective-vesting-shares',(floor_effective_vesting_shares).toFixed(2));
el.find('.effective-vesting-shares').append('<span class="adaptive-show">'+ltmp_arr.social_capital_effective_adaptive_caption+' </span>'+number_thousands((floor_effective_vesting_shares).toFixed(2))+' viz');
}
// true if the private WIF's public key satisfies the given account authority (weight >= threshold)
function wif_meets_authority(wif,authority){
try{
let pub=viz.auth.wifToPublic(wif);
let weight=0;
for(let i in authority.key_auths){
if(authority.key_auths[i][0]==pub){ weight+=authority.key_auths[i][1]; }
}
return weight>=authority.weight_threshold;
}
catch(e){ return false; }
}
function view_login(path,params,title){
title=ltmp_arr.login_title+' - '+title;
document.title=title;
$('.view').css('display','none');
if(''==current_user){
$('.header').css('display','none');
}
else{
$('.header').css('display','block');
}
$('.view-login').css('display','block');
$('.view-login input[name=back]').val('');
$('.view-login input[name=login]').val(typeof params.login != 'undefined' ? params.login : '');
$('.view-login input[name=active-key]').val('');
$('.view-login input[name=master-key]').val('');
$('.view-login input[name=regular-key]').val('');
$('.view-login input[name=memo-key]').val('');
$('.view-login .authorized').css('display','none');
if(typeof params.back != 'undefined'){
$('.view-login input[name=back]').val(params.back);
}
if(Object.keys(users).length>0){
$('.view-login .authorized span').html('');
$('.view-login .authorized span').html(Object.keys(users).sort().join(', '));
$('.view-login .authorized').css('display','block');
}
}