/
20170909.js
4384 lines (3840 loc) · 200 KB
/
20170909.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
/*
All code below developed by pftq and distributed by Autodidactic I (www.autodidactic.ai).
Do not copy or re-distribute without permission.
© 2016 The World Exchange | contact@theworldexchange.net
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Servers added to the list are selected from at random to distribute load across the network
var servers = [
'wss://s1.ripple.com/',
'wss://s2.ripple.com/',
'wss://s-east.ripple.com/',
'wss://s-west.ripple.com/'
];
// Configurables
var dataAPI = "https://data.ripple.com";
var chatServer = "wss://s2.ripple.com/"; // server for pulling transaction history containing chat messages
var chatWallet = "rfaSyhoQmHQaFv8qNoWaALNPQf7pa7sm7Q"; // wallet used for storing chatroom messages, will just receive tons of failed sends
var namesServer = "wss://s2.ripple.com/"; // server for pulling transaction history containing chat messages
var namesWallet = "rpKi47qegs2uCrBJnvRay49KSBd8w569oK"; // wallet used for storing chatroom messages, will just receive tons of failed sends
var transactionServer = "wss://s2.ripple.com/"; // server for pulling transaction history of current account
var accuracy = 8;
var updateInterval = 2; // seconds
var chatUpdateInterval = 5; // seconds
var reconnectInterval = 600; // number of intervals before reconnecting to reset connection, reduces stale connections etc
var maxLedgerOffset = 100; // High number of maxLedger errors during heavy trading periods if we leave it at default
var maxFee = "2000"; // Would rather overpay than not see my order go through during heavy trading
var accountHistoryURL = "https://bithomp.com/explorer/"; // Site to use for account history
var transactionHistoryURL = "https://charts.ripple.com/#/transactions/"; // Site to use for transaction history
// Default Issuers to use; need to figure out how to match defaults on xrpcharts
var majorIssuers = {
"BTC": ["rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"],
"EUR": ["rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq"],
"USD": ["rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B", "rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq"]
};
// Known issuers; doesn't matter what you put here, updates dynamically via Ripple Data API
var issuers = {
"BTC": ["rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"],
"CNY": ["rKiCet8SdvWxPXnAgYarFUXMh1zCPz432Y"],
"ETH": ["rcA8X3TVMST1n3CJeAdGk1RdRCHii7N2h"],
"EUR": ["rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq"],
"GBP": ["rBycsjqxD8RVZP5zrrndiVtJwht7Z457A8"],
"JPY": ["r9ZFPSb1TFdnJwbTMYHvVwFK1bQPUCVNfJ"],
"KRW": ["rPxU6acYni7FcXzPCMeaPSwKcuS2GTtNVN"],
"USD": ["rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B", "rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq"],
"XAG": ["r9Dr5xwkeLegBeXq6ujinjSBLQzQ1zQGjH"],
"XAU": ["r9Dr5xwkeLegBeXq6ujinjSBLQzQ1zQGjH"],
"XRP": []
};
// Known issuer names; doesn't matter what you put here, updates dynamically via Ripple Data API
var issuerNames = {
"rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B":"Bitstamp",
"rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq":"Gatehub",
"rKiCet8SdvWxPXnAgYarFUXMh1zCPz432Y":"Ripplefox",
"rcA8X3TVMST1n3CJeAdGk1RdRCHii7N2h":"Gatehub Fifth",
"rBycsjqxD8RVZP5zrrndiVtJwht7Z457A8":"Ripula",
"r9ZFPSb1TFdnJwbTMYHvVwFK1bQPUCVNfJ":"Ripple Exch Tokyo",
"rPxU6acYni7FcXzPCMeaPSwKcuS2GTtNVN":"EXRP",
"r9Dr5xwkeLegBeXq6ujinjSBLQzQ1zQGjH":"Ripple Singapore",
"rDVdJ62foD1sn7ZpxtXyptdkBSyhsQGviT":"Ripple Dividend"
};
// Current state variables
var api;
var chatAPI;
var namesAPI;
var address = '';
var key = '';
var baseReserve = 20;
var baseIncrement = 5;
var baseFee = 5;
var baseCurrency = "XRP";
var baseToDollar = 0.2;
var minBaseCurrency = 40;
var fee = 0.012;
var symbol1="";
var symbol2="";
var issuer1="";
var issuer2="";
var bookdepth = 8;
var mktcapName1="";
var mktcapName2="";
var mktcap1=0;
var mktcap2=0;
var action = "";
var lastIssuer1 = "";
var lastSymbol1 = "";
var lastIssuer2 = "";
var lastSymbol2 = "";
var destTag = "";
var memo = "";
var showChat = false;
var lastChat = "";
var displayName = {}; // address: displayName
var displayNameDetails = {}; // displayName: {date:<date>, address: address}
//var failedLogin = "";
// For low-level stuff only, do not mess with
var numIntervals = -1;
var noDisconnecting = false;
var reconnecting = false;
var showOrderbook = false;
var errored = false;
var loggingIn = false;
var refreshImmediately = false;
var chatLoaded = false;
var disableScrollToAbout = false; // for when scrolling shouldn't open the about page
var scrolling = false;
var currentChatUpdateInterval = 1; // for speeding up after you've sent a message before increasing back to normal
var trustlines = {
};
// state variable for current account flags
var settings = {
"defaultRipple":false,
"disableMasterKey":false,
"disallowIncomingXRP":false,
"enableTransactionIDTracking":false,
"globalFreeze":false,
"noFreeze":false,
"passwordSpent":false,
"regularKey":null,
"requireAuthorization":false,
"requireDestinationTag":false,
"rippleServer":null
};
// default settings for each flag
var defaultSettings = {
"defaultRipple":false,
"disableMasterKey":false,
"disallowIncomingXRP":false,
"enableTransactionIDTracking":false,
"globalFreeze":false,
"noFreeze":false,
"passwordSpent":false,
"regularKey":null,
"requireAuthorization":false,
"requireDestinationTag":false,
"rippleServer":null
};
// Added settings not part of RippleAPI, such as what server to connect to
var addedSettings = [
"rippleServer"
];
// string: description for account flags that are strings
var stringSettings = {
"regularKey": "Account to use secret key of.",
"rippleServer": "Server to connect to Ripple."
};
var holdings = {
"XRP":0
};
// Select a server at random to distribute load across the network
function selectServer(selectedServer) {
if(selectedServer===undefined || selectedServer=='undefined' || selectedServer=="") {
settings["rippleServer"] = servers[Math.floor(Math.random()*servers.length)];
}
else settings["rippleServer"] = selectedServer;
console.log("Server selected: "+settings["rippleServer"]);
api = new ripple.RippleAPI({server:settings["rippleServer"]});
}
// Format long numbers to 100K, 10M, etc
function nFormatter(num, digits) {
try {
var si = [
{ value: 1E18, symbol: "E" },
{ value: 1E15, symbol: "P" },
{ value: 1E12, symbol: "T" },
{ value: 1E9, symbol: "B" },
{ value: 1E6, symbol: "M" },
//{ value: 1E3, symbol: "k" }
], rx = /\.0+$|(\.[0-9]*[1-9])0+$/, i;
for (i = 0; i < si.length; i++) {
if (num >= si[i].value) {
return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol;
}
}
return num.toFixed(digits).replace(rx, "$1");
}
catch (err) { return num; }
return num;
}
// For cleaning HTML from strings, especially chat messages
function stripHTML(dirtyString) {
var container = document.createElement('div');
var text = document.createTextNode($($.parseHTML(dirtyString)).text());
container.appendChild(text);
return container.innerHTML; // innerHTML will be a xss safe string
}
// Replace welcome message with login state or vice versa
function updateLoginMessage() {
if(address!="" && $("#yourAccount").css("display")!="block") {
$("#welcome").css("display", "none");
$("#yourAccount").css("display", "block");
$("#chatSettings").css("display", "block");
refreshChatLayout();
}
else if(address=="" && $("#yourAccount").css("display")!="none") {
$("#welcome").css("display", "block");
$("#yourAccount").css("display", "none");
$("#chatSettings").css("display", "none");
refreshChatLayout();
}
}
// Refresh account stats such as balances, orders, etc
function loadAccount(loadOrderbookNext) {
if(loadOrderbookNext===undefined || loadOrderbookNext=='undefined') loadOrderbookNext=false;
var baseCurrencyCount = 0;
var changeMiscMenu = false;
new Promise(function(resolve, reject) {
var temp = $("#account").val();
// Save the account address to cookie (do not touch secret keys)
if(temp!=address) {
address = $("#account").val();
Cookies.set('accountAddr', address, { expires: 7 });
console.log("Account address saved to cookie: "+address);
updateSymbol1();
changeMiscMenu = true;
}
updateLoginMessage();
// Reconnect if disconnected and not already reconnecting
if(!reconnecting) {
reconnecting = true;
try {
if(api.isConnected()) {
reconnecting = false;
resolve();
}
else {
console.log('Disconnected in loadAccount.');
try {
selectServer();
api.connect().then(function() {
console.log("Reconnected in loadAccount.");
reconnecting = false;
resolve();
}, function (err) {
console.log("Failed to reconnect in loadAccount: "+err);
reconnecting = false;
resolve();
});
}
catch (er) {
console.log("Failed to reconnect in loadAccount: "+er);
reconnecting = false;
resolve();
}
}
}
catch (erx) {
console.log("Error in loadAccount API: "+erx);
reconnecting = false;
resolve();
}
}
else setTimeout(resolve, 5000); // Pause a bit to wait for other reconnecting effort
}, function (err) {
console.log("Error in loadAccount: "+err);
}).then(function() {
if(address=="" || !api.isConnected()) {
if(minBaseCurrency!=0) changeMiscMenu = true;
minBaseCurrency = 0;
return "";
}
else {
// Pull basic info on the account first
var info = "";
try {
info = api.getAccountInfo(address);
}
catch (err) {
console.log("Error getAccountInfo: "+err);
}
return info;
}
}, function(err) { console.log("Error getAccountInfo: "+err); return ""; }).then(function(info) {
if(info) {
// Save minXRP and current XRP balance
var minReserve = baseReserve + baseIncrement*info.ownerCount;
if(minReserve!=minBaseCurrency) {
minBaseCurrency = minReserve;
changeMiscMenu = true;
}
baseCurrencyCount = parseFloat(info.xrpBalance);
//console.log(info);
// Download current fee
return api.getFee();
} else return null;
}, function(err) {
console.log("Error loading minBaseCurrency: "+err);
if(err=="[RippledError(actNotFound)]") {
if(minBaseCurrency!=baseReserve) changeMiscMenu = true;
minBaseCurrency = baseReserve;
baseCurrencyCount = 0;
}
}).then(function(currentFee) {
if(currentFee!=null) {
try { // Update the fee
var newFee = parseFloat(currentFee);
if(newFee!=fee) {
changeMiscMenu = true;
fee = newFee;
$("#feeAnnouncement").html((fee+0.000001).toFixed(6));
$("#feeDollar").html(((fee+0.000001)*baseToDollar).toFixed(6));
}
}
catch(ex) { console.log("Error parsing fee: "+err); }
}
}, function(err) {
console.log("Error loading fee: "+err);
}).then(function() {
if(address=="" || !api.isConnected()) return "";
else {
// Pull current balances. Use getBalanceSheet instead of getBalances because it's faster and aggregates duplicates together
var sheet = "";
try {
//console.log("Fetching balances...");
sheet = api.getBalanceSheet(address);
}
catch (err) {
console.log("Error getBalanceSheet: "+err);
}
return sheet;
}
}, function(err) { console.log("Error getBalances: "+err); return ""; }).then(function(sheet) {
var balanceOutput = "";
//console.log("Finished getting balances:");
//console.log(sheet);
// Parse balanceSheet object to extract holdings as positive and obligations (issuances) as negatives
if(address!="" && sheet!=null && sheet!="" && ((sheet.assets!=null && sheet.assets.length>0) || (sheet.obligations!=null && sheet.obligations.length>0))) {
//console.log("Building holdings from getBalanceSheet...");
// Reset holdings to empty and rebuild
holdings = {};
holdings[baseCurrency]=baseCurrencyCount;
var updateIssuers = false;
// Holdings as positive
if(sheet.assets) {
var balances = sheet.assets;
for(var i=0; i<balances.length; i++) {
if(balances[i].value==0) continue;
if(balanceOutput!="") balanceOutput+=", ";
var counterparty = ""+balances[i].counterparty;
if(balances[i].value<0) counterparty = address;
var s = balances[i].currency + (counterparty!="undefined" && (!(balances[i].currency in issuers) || (issuers[balances[i].currency].length>0))? "."+counterparty:"");
if(!(s in holdings)) holdings[s] = 0;
holdings[s] += parseFloat(balances[i].value);
}
}
// Obligations (issuances) as negatives
if(sheet.obligations) {
var balances = sheet.obligations;
for(var i=0; i<balances.length; i++) {
if(balances[i].value==0) continue;
if(balanceOutput!="") balanceOutput+=", ";
var counterparty = address;
var s = balances[i].currency + "."+counterparty;
if(!(s in holdings)) holdings[s] = 0;
holdings[s] -= parseFloat(balances[i].value);
}
}
}
else {
// Otherwise just update the XRP pulled from accountInfo
// We don't want to reset holdings to empty because sometimes getBalances just temporarily times out
//console.log("Only have XRP. Updating holdings = "+baseCurrencyCount);
holdings[baseCurrency]=baseCurrencyCount;
}
// Create display of balances
var sortedHoldings = Object.keys(holdings).sort(function(a,b){return holdings[a]-holdings[b]});
for(var i = 0; i<sortedHoldings.length; i++) {
var s = sortedHoldings[i];
if(holdings[s] == 0) continue;
var act = holdings[s]>0? "sell":"buy";
var qty = Math.abs(holdings[s]);
var ss = s.split('.');
var currency = ss[0];
var counterparty = (ss.length>1? ss[1]:"");
balanceOutput+="<a target='_blank' href='?qty1="+qty+"&symbol1="+s+"' onclick='loadURLSymbol(\"\", "+qty+", \""+s+"\"); return false;'>"+parseFloat(holdings[s].toFixed(holdings[s]>1? 2:4)).toString()+" "+currency+"</a> "; // Make sure to include space at the end to avoid page overflow
// Check if issuer exists in autocomplete and add if it doesn't
if(!(currency in issuers)) {
issuers[currency] = [];
updateIssuers = true;
}
if(counterparty!="" && counterparty!="undefined" && issuers[currency].indexOf(counterparty)<0) {
issuers[currency].push(counterparty);
updateIssuers = true;
}
}
// Update autocomplete of issuers if needed
if(updateIssuers) {
var symbolsList = symbolLister();
$("#symbol1").autocomplete({ source:symbolsList});
$("#symbol2").autocomplete({ source:symbolsList});
}
// Most likely new accounts not funded; should do nothing and let the fund your account message show (later below)
if(address!="" && (Object.keys(holdings).length<1 || holdings[baseCurrency]<minBaseCurrency)) {
//console.log("No results from getBalances.");
//console.log(balances);
}
// Normal display of balances
else if(balanceOutput!="") {
$("#balanceLabel").css("visibility", "visible");
$("#balanceLabel").css("display", "block");
$("#balance").css("display", "block");
$("#balance").html(""+balanceOutput);
}
// Hide balances box if nothing to show and no account
else {
$("#balanceLabel").css("visibility", "hidden");
$("#balanceLabel").css("display", "none");
$("#balance").css("display", "none");
$("#balance").html("");
}
}, function(err) {
console.log("Error building balances: "+err);
}).then(function() {
if(address=="" || !api.isConnected() || holdings[baseCurrency]==0) return "";
else {
// Look up outstanding trade orders but only if account is activated
var orders = "";
try {
orders = api.getOrders(address);
}
catch(err) {
console.log("Error api.getOrders: "+err);
}
return orders;
}
}, function(err) {console.log("Error getOrders: "+err); return ""; }).then(function(orders) {
// Display orders to page
var ordersOutput = "";
if(address!="" && orders!="") {
var updateIssuers = false;
for(var i=0; i<orders.length; i++) {
if(ordersOutput!="") ordersOutput+="<br /> ";
var direction = orders[i].specification.direction;
var counterparty1 = ""+orders[i].specification.quantity.counterparty;
if(counterparty1==address) direction = "issue";
var counterparty2 = ""+orders[i].specification.totalPrice.counterparty;
var qty = parseFloat(orders[i].specification.quantity.value);
var symbol1 = ""+orders[i].specification.quantity.currency;
var symbol2 = ""+orders[i].specification.totalPrice.currency;
var price = parseFloat(orders[i].specification.totalPrice.value)/parseFloat(orders[i].specification.quantity.value);
var s1 = symbol1 + (counterparty1!="" && counterparty1!="undefined" && (!(symbol1 in issuers) || (issuers[symbol1].length>0))? "."+counterparty1:"");
var s2 = symbol2 + (counterparty2!="" && counterparty2!="undefined" && (!(symbol2 in issuers) || (issuers[symbol2].length>0))? "."+counterparty2:"");
var orderSeq = orders[i].properties.sequence;
ordersOutput+="<span style='white-space:nowrap;'><a href='#' onclick='cancelOrder("+orderSeq+"); this.style.display = \"none\"'>[X]</a> <a target='_blank' href='?action="+direction+"&qty1="+qty+"&symbol1="+s1+"&price="+price+"&symbol2="+s2+"' onclick='loadURLSymbols(\""+direction+"\", "+qty+", \""+s1+"\", "+price+", \""+s2+"\"); return false;'>"+direction+" "+parseFloat(qty.toFixed(qty>1? 2:4)).toString()+" "+symbol1+" @ "+parseFloat(price.toFixed(price>1? 2:4)).toString()+" "+symbol2+"</a></span> "; // Make sure to include space at the end to avoid page overflow
// Check if issuer exists in autocomplete and add if it doesn't
if(!(symbol1 in issuers)) {
issuers[symbol1] = [];
updateIssuers = true;
}
if(counterparty1!="" && counterparty1!="undefined" && issuers[symbol1].indexOf(counterparty1)<0) {
issuers[symbol1].push(counterparty1);
updateIssuers = true;
}
if(!(symbol2 in issuers)) {
issuers[symbol2] = [];
updateIssuers = true;
}
if(counterparty2!="" && counterparty2!="undefined" && issuers[symbol2].indexOf(counterparty2)<0) {
issuers[symbol2].push(counterparty2);
updateIssuers = true;
}
}
// Update autocomplete for issuers if needed
if(updateIssuers) {
var symbolsList = symbolLister();
$("#symbol1").autocomplete({ source:symbolsList});
$("#symbol2").autocomplete({ source:symbolsList});
}
}
// Display orders if they exist, otherwise hide the box
if(ordersOutput!="") {
$("#ordersLabel").css("visibility", "visible");
$("#ordersLabel").css("display", "block");
$("#orders").css("display", "block");
$("#orders").css("visibility", "visible");
$("#orders").html(""+ordersOutput);
}
else {
$("#ordersLabel").css("visibility", "hidden");
$("#ordersLabel").css("display", "none");
$("#orders").css("display", "none");
$("#orders").css("visibility", "hidden");
$("#orders").html("");
}
}, function(er) { console.log("Error building orders: "+er); }).then(function() {
// Show account information only if logged in
var tag = "div";
if(address=="") tag="span";
var commonMenu = "<"+tag+" id='tutorialsHeader'><a href='https://www.youtube.com/playlist?list=PLHAK7FXoElZOyM6MaQ_O_i6ATap2k9r-o' target='_blank'>Video Tutorials</a></div>"+(address==""? " ":"")+"<"+tag+" id='chatHide' "+(showChat? "":"style='display:none;'")+"><a href='#' onclick='hideChatbox(); "+(isMobile()? "hideMiscMenu();":"")+"'>Hide Chat</a></"+tag+"><"+tag+" id='chatShow' "+(!showChat? "":"style='display:none;'")+"><a href='#' onclick='showChatbox(); "+(isMobile()? "hideMiscMenu();":"")+"'>Show Chat</a></"+tag+">";
if($.trim($("#miscMenu").html())=="") {
changeMiscMenu = true;
}
if(address!="") {
if(changeMiscMenu) {
$("#miscMenu").html("<div><a href='#started' onclick='$(\"#about\").css(\"display\", \"block\"); jQuery(\"html,body\").animate({scrollTop: jQuery(\"#started\").offset().top}, 1000); setURL(\"#started\"); "+(isMobile()? "hideMiscMenu();":"")+" return false;'>Min "+baseCurrency+": "+nFormatter(minBaseCurrency, accuracy)+"</a> | <a href='#started' onclick='$(\"#about\").css(\"display\", \"block\"); jQuery(\"html,body\").animate({scrollTop: jQuery(\"#started\").offset().top}, 1000); setURL(\"#started\"); "+(isMobile()? "hideMiscMenu();":"")+" return false;'>Current Fee: "+fee.toFixed(6)+"</a><br /><a href='"+accountHistoryURL+""+address+"' onclick='"+(isMobile()? "hideMiscMenu();":"")+"' target='_blank'>View Account History</a></div><div><a href='#' onclick='showTrustlines(); "+(isMobile()? "hideMiscMenu();":"")+"'>Set "+(settings["requireAuthorization"]? "Authorized Token Holders":"Receivable Tokens")+"</a></div><!--<div><a href='#started' onclick='$(\"#about\").css(\"display\", \"block\"); jQuery(\"html,body\").animate({scrollTop: jQuery(\"#started\").offset().top}, 1000); setURL(\"#started\"); "+(isMobile()? "hideMiscMenu();":"")+" return false;'>How to Fund / Deposit</a></div>--><div><a href='#' onclick='showSettings();"+(isMobile()? "hideMiscMenu();":"")+"'>Advanced Settings</a></div>"+commonMenu);
if($("#showMiscMenu").css("display") == 'none' && $("#hideMiscMenu").css("display") == 'none') {
$("#showMiscMenu").css("display", "block");
$("#hideMiscMenu").css("display", "none");
}
checkMinBaseCurrency(); // Update balance info to message to fund account
refreshLayout();
}
}
else {
if(changeMiscMenu) {
$("#miscMenu").html(commonMenu);
$("#showMiscMenu").css("display", "none");
$("#hideMiscMenu").css("display", "none");
refreshLayout();
}
}
}, function(er) { console.log("Error printing orders: "+er); }).then(function() {
// Periodic disconnect to refresh the connection and avoid stale no-response state
if(api.isConnected() && loadOrderbookNext && !noDisconnecting && !reconnecting) {
if(numIntervals>=reconnectInterval) {
numIntervals = 0;
return api.disconnect();
}
else numIntervals++;
}
}, function(er) { console.log("Error disconnecting after loadAccount: "+er); }).then(function() {
// Create back-and-forth loop with loadOrderbook function for constant refresh
if(loadOrderbookNext) {
interruptableTimer(loadOrderbook);
}
}, function(err) {
// Restart back-and-forth loop with loadOrderbook function if errored out
console.log("Error completing account load: "+err);
if(loadOrderbookNext) {
interruptableTimer(loadOrderbook);
}
});
}
// Custom setTimer function to allow wait-time to change while it's waiting
function interruptableTimer(functionToCall, waitedSoFar) {
if(waitedSoFar===undefined || waitedSoFar=='undefined') waitedSoFar = 0;
var waitThresh = getInterval();
if(waitedSoFar<waitThresh) {
//console.log("Waiting "+waitedSoFar+" / "+waitThresh);
setTimeout(function() {interruptableTimer(functionToCall, waitedSoFar+100); }, 100);
}
else {
//console.log("Calling function...");
functionToCall();
}
}
// Dynamic wait time of the interruptableTimer
// Set refreshImmediately to true anywhere in the code to end timer immediately
function getInterval() {
if(refreshImmediately) {
refreshImmediately = false;
//console.log("Forcing refresh immediately...");
return 1;
}
else return updateInterval*1000;
}
// Show/hide misc menu for mobile
function showMiscMenu() {
if(address=="") return;
document.getElementById("miscMenu").style.display="block";
document.getElementById("showMiscMenu").style.display="none";
document.getElementById("hideMiscMenu").style.display="block";
refreshImmediately = true;
rescaleWindow();
}
function hideMiscMenu() {
if(address=="") return;
document.getElementById("miscMenu").style.display="none";
document.getElementById("showMiscMenu").style.display="block";
document.getElementById("hideMiscMenu").style.display="none";
refreshImmediately = true;
rescaleWindow();
}
// Close/open chat box
function showChatbox(updateMenu) {
if(updateMenu===undefined || updateMenu=='undefined') updateMenu = true;
showChat = true;
currentChatUpdateInterval = 0;
document.getElementById("chatbox").style.display="initial";
if(isMobile()) $("#about").css("display", "none");
if(document.getElementById("chatShow")!=null && updateMenu) { // not built until end of doc load
document.getElementById("chatShow").style.display="none";
document.getElementById("chatHide").style.display="initial";
rescaleChat();
}
}
function hideChatbox(updateMenu) {
if(updateMenu===undefined || updateMenu=='undefined') updateMenu = true;
showChat = false;
document.getElementById("chatbox").style.display="none";
if(isMobile()) $("#about").css("display", "block");
if(document.getElementById("chatShow")!=null && updateMenu) {//not built until end of doc load
document.getElementById("chatShow").style.display="initial";
document.getElementById("chatHide").style.display="none";
}
}
// Check and display minXRP needed
function checkMinBaseCurrency() {
//console.log("Checking min balance: "+holdings[baseCurrency]+" vs "+minBaseCurrency);
if(holdings[baseCurrency]<minBaseCurrency) {
$("#balanceLabel").css("display", "hidden");
$("#balanceLabel").css("display", "block");
$("#balance").css("display", "block");
$("#balance").html("Your account needs <a href='#started' onclick='$(\"#about\").css(\"display\", \"block\"); jQuery(\"html,body\").animate({scrollTop: jQuery(\"#started\").offset().top}, 1000); setURL(\"#started\"); return false;'>>= "+minBaseCurrency+" "+baseCurrency+"</a>."+(isMobile()? " (Currently: "+(holdings[baseCurrency])+")":"<br />You currently have: "+(holdings[baseCurrency])+".<br />See: <a href='#started' onclick='$(\"#about\").css(\"display\", \"block\"); jQuery(\"html,body\").animate({scrollTop: jQuery(\"#started\").offset().top}, 1000); setURL(\"#started\"); return false;'>How to Get Started</a>"));
}
}
// Download account transaction history as a CSV
function accountHistoryCSVOld() {
if(address=="") return;
var csv = ['Date,Type,From,To,Amount,Currency,Issuer'];
var url = dataAPI+"/v2/accounts/"+address+"/transactions?result=tesSUCCESS&limit=2";
$.get( url, function( data ) {
try {
console.log(data);
if(data!=null && data.transactions!=null) {
for(var i=0; i<data.transactions.length; i++) {
var amt = "";
var symbol = "XRP";
var issuer = "";
if(typeof data.transactions[i].tx.Amount === 'object') {
amt = data.transactions[i].tx.Amount.value;
symbol = data.transactions[i].tx.Amount.currency;
issuer = data.transactions[i].tx.Amount.issuer;
}
else amt = data.transactions[i].tx.Amount;
csv.push([
data.transactions[i].date.replace("T", " ").replace(".000Z", ""),
data.transactions[i].tx.TransactionType,
data.transactions[i].tx.Account,
data.transactions[i].tx.Destination,
amt,
symbol,
issuer
].join(","));
}
downloadCSV("Ripple-Transaction-History_"+address+".csv", csv.join("\r\n"));
}
}
catch (err) {
errored = true;
$("#errors").html("Error retrieving history: "+err);
}
}, "json" );
}
function accountHistoryCSV() {
if(address=="") return;
var csv = ['Date,Type,From-Address,From-Amount,From-Symbol,To-Address,To-Amount,To-Currency'];
var transactionHistoryAPI = new ripple.RippleAPI({server:transactionServer});
transactionHistoryAPI.connect().then(function() {
var options = {earliestFirst:true, excludeFailures:true};
return transactionHistoryAPI.getTransactions(address, options );
}, function(err) { errored=true;$("#errors").html("Failed to connect for transaction history: "+err); return null;})
.then(function (transactions) {
if(transactions!=null) {
for(var i = 0; i<transactions.length; i++) {
try {
csv.push([
transactions[i].outcome.timestamp.replace("T", " ").replace(".000Z", ""),
transactions[i].type,
transactions[i].specification.source.address,
transactions[i].specification.source.maxAmount.value,
transactions[i].specification.source.maxAmount.currency,
transactions[i].specification.destination.address,
transactions[i].specification.destination.amount.value,
transactions[i].specification.destination.amount.currency
].join(","));
}
catch(ex) {
console.log("Transaction parsing error: "+ex);
}
}
}
else {
errored=true;
$("#errors").html("No transaction history. Try again a bit later.");
}
}, function(err) {
if(err=="[MissingLedgerHistoryError(Server is missing ledger history in the specified range)]") {
errored=true;
$("#errors").html("No transaction history retrieved. Try again a bit later.");
}
else {
errored=true;
$("#errors").html("Transaction retrieval error: "+err);
}
}).then(function() {
return transactionHistoryAPI.disconnect();
}).then(function() {
downloadCSV("Ripple-Transaction-History_"+address+".csv", csv.join("\r\n"));
});
}
// Generic CSV download
function downloadCSV(filename, content) {
var a = document.createElement('a');
var mimeType = 'application/csv';
var charset='utf-8';
if (navigator.msSaveBlob)
{
return navigator.msSaveBlob(new Blob([content], { type: mimeType }), filename);
}
else if ('download' in a)
{
a.href = 'data:' + mimeType+';charset='+charset + ',' + encodeURIComponent(content);
a.setAttribute('download', filename);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
return true;
}
else
{
var f = document.createElement('iframe');
document.body.appendChild(f);
f.src = 'data:' + mimeType+';charset='+charset + ',' + encodeURIComponent(content);
document.body.removeChild(f);
return true;
}
}
// Create list of symbols for autocomplete
function symbolLister() {
var result = [];
for(var symbol in issuers)
if($.inArray(symbol, result) === -1) result.push(symbol);
result.sort();
return result;
}
// Build pair for orderbook lookup
function getPair(s1, i1, s2, i2) {
var pair = {};
pair.base = {};
pair.counter = {};
pair.base.currency = s1;
pair.counter.currency = s2;
if(i1!="" && s1!=baseCurrency && (!(s1 in issuers) || issuers[s1].length>0)) pair.base.counterparty=i1;
if(i2!="" && s2!=baseCurrency && (!(s2 in issuers) || issuers[s2].length>0)) pair.counter.counterparty=i2;
//console.log(pair.base.currency+"."+pair.base.counterparty+" vs "+pair.counter.currency+"."+pair.counter.counterparty);
return pair;
}
// Get current selected text on page
function getSelectedText() {
var text = "";
if (typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
// Load and refresh orderbook; back-and-forth loop with loadAccount
// updateMessageOnly used by updateAction to only update page description quickly and skip orderbook lookup
// set repeat option to false to avoid multiple orderbook refresh loops
function loadOrderbook(updateMessageOnly, repeat) {
if(updateMessageOnly===undefined || updateMessageOnly=='undefined') updateMessageOnly = false;
if(repeat===undefined || repeat=='undefined') repeat = true;
if(action=='send') updateMessageOnly = true;
try {
//console.log("orderbook-entry: "+showOrderbook+", symbol1="+symbol1+", symbol2="+symbol2);
var currentOrderbook = null;
var bridgedBook1 = null;
var bridgedBook2 = null;
var orderbookExists = true;
new Promise(function(resolve, reject) {
// Check if disconnected first and reconnect if so
if(!updateMessageOnly) {
if(!reconnecting) { // Make sure we're not already reconnecting asynchronously
reconnecting = true;
try {
if(api.isConnected()) {
reconnecting = false;
resolve();
}
else {
console.log('Disconnected in loadOrderbook.');
try {
selectServer();
api.connect().then(function() {
console.log("Reconnected in loadOrderbook.");
reconnecting = false;
resolve();
}, function (err) {
console.log("Failed to reconnect in loadOrderbook: "+err);
reconnecting = false;
resolve();
});
}
catch (er) {
console.log("Failed to reconnect in loadOrderbook: "+er);
reconnecting = false;
resolve();
}
}
}
catch (erx) {
console.log("Error in loadOrderbook API: "+erx);
reconnecting = false;
resolve();
}
}
else setTimeout(resolve, 5000); // Wait a bit if asynchronously reconnecting already
}
else {
resolve();
}
}, function (err) {
// Restart orderbook refresh loop if errored out
console.log("Error in loadOrderbook: "+err);
console.log("Restarting refresh cycle...");
if(repeat && !updateMessageOnly)
interruptableTimer(loadOrderbook);
}).then(function() {
// Make sure symbols and marketcaps are accurate before doing expensive orderbook lookup
if(!updateMessageOnly && showOrderbook && getSelectedText()=="") {
updateSymbols();
updateMarketCaps();
}
}, function(err) { console.log("Error updating tokens before orderbook: "+err); }).then(function() {
// Only do orderbook lookup if function is not called to only update the page description
// Don't update while we're typing (getSelectedText=="")
if(!updateMessageOnly && api.isConnected() && showOrderbook && getSelectedText()=="") {
try {
refreshLayout();
// Limit request to how many we can display on the page
bookdepth = Math.max(1, Math.round((($('#container').outerHeight()- $("#orderbook").offset().top - $("footer").outerHeight())-100)/($('#footer').outerHeight()/1.5)));
// Older bug (and still exists in ripplelib!) where any modern Apple device froze because of Javascript outdated libraries in ripplelib
// Ripple still hasn't fixed this but we're using a modified version of it that has libraries updated
//if( /iPhone/i.test(navigator.userAgent) ) return null; // broken on iphone, freezes
//console.log("Requesting orderbook: "+symbol1+"."+issuer1+" x "+symbol2+"."+issuer2);
return api.getOrderbook(address=="" || address.length<=10? Object.keys(issuerNames)[0]:address, getPair(symbol1, issuer1, symbol2, issuer2), {limit:bookdepth+5});
}
catch (ex) {
console.log("Error requesting orderbook: "+ex);
return null;
//refreshLayout();
}
}
else return null;
}, function (err) {
console.log("Error in api.loadOrderbook: "+err);
return null;
})
.then(function(orderbook) {
currentOrderbook = orderbook;
if(!updateMessageOnly) {
//console.log("Main orderbook: ");
//console.log(orderbook);
}
// Check for autobridge-able orderbooks by 1 degree (through XRP pairs with each the left and right side)
// Don't bother for XRP, assuming only non-XRP tickers are autobridged
// work in progress, disabled until next vers
// First bridged orderbook
if(!updateMessageOnly
&& symbol1!=baseCurrency && symbol2 != baseCurrency) {
//console.log("Requesting orderbook for bridging left: "+symbol1+"."+issuer1+" x "+baseCurrency);
return api.getOrderbook(address=="" || address.length<=10? Object.keys(issuerNames)[0]:address, getPair(symbol1, issuer1, baseCurrency, ""), {limit:bookdepth+5});
}
else return null;
}, function (err) {
console.log("Error in api.loadOrderbook for bridged quote 1: "+err);
return null;
}).then(function(orderbook1) {
// Work in progress for autobridged orderbooks
bridgedBook1 = orderbook1;
//console.log("Left side of bridged book:");
//console.log(orderbook1);
// Second bridged orderbook
if(bridgedBook1!=null) {
//console.log("Requesting orderbook for bridging right: "+symbol2+"."+issuer2+" x "+baseCurrency);
return api.getOrderbook(address=="" || address.length<=10? Object.keys(issuerNames)[0]:address, getPair(symbol2, issuer2, baseCurrency, ""), {limit:bookdepth+5});
}
else {
//console.log("No left side to bridge orderbooks.");
return null;
}
}, function (err) {
console.log("Error in api.loadOrderbook for bridged quote 2: "+err);
return null;
}).then(function(orderbook2) {
bridgedBook2 = orderbook2;
if(!updateMessageOnly) {
//console.log("Right side of bridged book:");
//console.log(orderbook2);
}
// Combine the books
try {
if(!updateMessageOnly && showOrderbook && bridgedBook1!=null && bridgedBook2!=null) {
showOrderbook = true; // in case the main book has no orders and shut this off
if(currentOrderbook==null) currentOrderbook = {bids:[], asks:[]};