This repository has been archived by the owner on Nov 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
amount.js
1191 lines (990 loc) · 34.7 KB
/
amount.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
// Represent Ripple amounts and currencies.
// - Numbers in hex are big-endian.
var utils = require('./utils');
var sjcl = utils.sjcl;
var bn = sjcl.bn;
var BigInteger = utils.jsbn.BigInteger;
var UInt160 = require('./uint160').UInt160;
var Seed = require('./seed').Seed;
var Currency = require('./currency').Currency;
var consts = exports.consts = {
currency_xns: 0,
currency_one: 1,
xns_precision: 6,
// BigInteger values prefixed with bi_.
bi_5: new BigInteger('5'),
bi_7: new BigInteger('7'),
bi_10: new BigInteger('10'),
bi_1e14: new BigInteger(String(1e14)),
bi_1e16: new BigInteger(String(1e16)),
bi_1e17: new BigInteger(String(1e17)),
bi_1e32: new BigInteger('100000000000000000000000000000000'),
bi_man_max_value: new BigInteger('9999999999999999'),
bi_man_min_value: new BigInteger('1000000000000000'),
bi_xns_max: new BigInteger('9000000000000000000'), // Json wire limit.
bi_xns_min: new BigInteger('-9000000000000000000'),// Json wire limit.
bi_xns_unit: new BigInteger('1000000'),
cMinOffset: -96,
cMaxOffset: 80,
};
//
// Amount class in the style of Java's BigInteger class
// http://docs.oracle.com/javase/1.3/docs/api/java/math/BigInteger.html
//
function Amount() {
// Json format:
// integer : XRP
// { 'value' : ..., 'currency' : ..., 'issuer' : ...}
this._value = new BigInteger(); // NaN for bad value. Always positive.
this._offset = 0; // Always 0 for XRP.
this._is_native = true; // Default to XRP. Only valid if value is not NaN.
this._is_negative = false;
this._currency = new Currency();
this._issuer = new UInt160();
};
// Given '100/USD/mtgox' return the a string with mtgox remapped.
Amount.text_full_rewrite = function (j) {
return Amount.from_json(j).to_text_full();
};
// Given '100/USD/mtgox' return the json.
Amount.json_rewrite = function (j) {
return Amount.from_json(j).to_json();
};
Amount.from_number = function (n) {
return (new Amount()).parse_number(n);
};
Amount.from_json = function (j) {
return (new Amount()).parse_json(j);
};
Amount.from_quality = function (quality, currency, issuer, opts) {
return (new Amount()).parse_quality(quality, currency, issuer, opts);
};
Amount.from_human = function (j, opts) {
return (new Amount()).parse_human(j, opts);
};
Amount.is_valid = function (j) {
return Amount.from_json(j).is_valid();
};
Amount.is_valid_full = function (j) {
return Amount.from_json(j).is_valid_full();
};
Amount.NaN = function () {
var result = new Amount();
result._value = NaN;
return result;
};
// Returns a new value which is the absolute value of this.
Amount.prototype.abs = function () {
return this.clone(this.is_negative());
};
// Result in terms of this' currency and issuer.
Amount.prototype.add = function (v) {
var result;
v = Amount.from_json(v);
if (!this.is_comparable(v)) {
result = Amount.NaN();
} else if (v.is_zero()) {
result = this;
} else if (this.is_zero()) {
result = v.clone();
result._is_native = this._is_native;
result._currency = this._currency;
result._issuer = this._issuer;
} else if (this._is_native) {
result = new Amount();
var v1 = this._is_negative ? this._value.negate() : this._value;
var v2 = v._is_negative ? v._value.negate() : v._value;
var s = v1.add(v2);
result._is_negative = s.compareTo(BigInteger.ZERO) < 0;
result._value = result._is_negative ? s.negate() : s;
result._currency = this._currency;
result._issuer = this._issuer;
} else {
var v1 = this._is_negative ? this._value.negate() : this._value;
var o1 = this._offset;
var v2 = v._is_negative ? v._value.negate() : v._value;
var o2 = v._offset;
while (o1 < o2) {
v1 = v1.divide(consts.bi_10);
o1 += 1;
}
while (o2 < o1) {
v2 = v2.divide(consts.bi_10);
o2 += 1;
}
result = new Amount();
result._is_native = false;
result._offset = o1;
result._value = v1.add(v2);
result._is_negative = result._value.compareTo(BigInteger.ZERO) < 0;
if (result._is_negative) {
result._value = result._value.negate();
}
result._currency = this._currency;
result._issuer = this._issuer;
result.canonicalize();
}
return result;
};
/**
* Turn this amount into its inverse.
*
* @private
*/
Amount.prototype._invert = function () {
this._value = consts.bi_1e32.divide(this._value);
this._offset = -32 - this._offset;
this.canonicalize();
return this;
};
/**
* Return the inverse of this amount.
*
* @return {Amount} New Amount object with same currency and issuer, but the
* inverse of the value.
*/
Amount.prototype.invert = function () {
return this.copy()._invert();
};
Amount.prototype.canonicalize = function () {
if (!(this._value instanceof BigInteger)) {
// NaN.
// nothing
} else if (this._is_native) {
// Native.
if (this._value.equals(BigInteger.ZERO)) {
this._offset = 0;
this._is_negative = false;
} else {
// Normalize _offset to 0.
while (this._offset < 0) {
this._value = this._value.divide(consts.bi_10);
this._offset += 1;
}
while (this._offset > 0) {
this._value = this._value.multiply(consts.bi_10);
this._offset -= 1;
}
}
// XXX Make sure not bigger than supported. Throw if so.
} else if (this.is_zero()) {
this._offset = -100;
this._is_negative = false;
} else {
// Normalize mantissa to valid range.
while (this._value.compareTo(consts.bi_man_min_value) < 0) {
this._value = this._value.multiply(consts.bi_10);
this._offset -= 1;
}
while (this._value.compareTo(consts.bi_man_max_value) > 0) {
this._value = this._value.divide(consts.bi_10);
this._offset += 1;
}
}
return this;
};
Amount.prototype.clone = function (negate) {
return this.copyTo(new Amount(), negate);
};
Amount.prototype.compareTo = function (v) {
var result;
if (!this.is_comparable(v)) {
result = Amount.NaN();
} else if (this._is_negative !== v._is_negative) {
// Different sign.
result = this._is_negative ? -1 : 1;
} else if (this._value.equals(BigInteger.ZERO)) {
// Same sign: positive.
result = v._value.equals(BigInteger.ZERO) ? 0 : -1;
} else if (v._value.equals(BigInteger.ZERO)) {
// Same sign: positive.
result = 1;
} else if (!this._is_native && this._offset > v._offset) {
result = this._is_negative ? -1 : 1;
} else if (!this._is_native && this._offset < v._offset) {
result = this._is_negative ? 1 : -1;
} else {
result = this._value.compareTo(v._value);
if (result > 0) {
result = this._is_negative ? -1 : 1;
} else if (result < 0) {
result = this._is_negative ? 1 : -1;
}
}
return result;
};
// Make d a copy of this. Returns d.
// Modification of objects internally refered to is not allowed.
Amount.prototype.copyTo = function (d, negate) {
if (typeof this._value === 'object') {
this._value.copyTo(d._value);
} else {
d._value = this._value;
}
d._offset = this._offset;
d._is_native = this._is_native;
d._is_negative = negate
? !this._is_negative // Negating.
: this._is_negative; // Just copying.
d._currency = this._currency;
d._issuer = this._issuer;
// Prevent negative zero
if (d.is_zero()) {
d._is_negative = false;
}
return d;
};
Amount.prototype.currency = function () {
return this._currency;
};
Amount.prototype.equals = function (d, ignore_issuer) {
if (typeof d === 'string') {
return this.equals(Amount.from_json(d));
}
var result = true;
result = !((!this.is_valid() || !d.is_valid())
|| (this._is_native !== d._is_native)
|| (!this._value.equals(d._value) || this._offset !== d._offset)
|| (this._is_negative !== d._is_negative)
|| (!this._is_native && (!this._currency.equals(d._currency) || !ignore_issuer && !this._issuer.equals(d._issuer))))
return result;
};
// Result in terms of this' currency and issuer.
Amount.prototype.divide = function (d) {
var result;
if (d.is_zero()) {
throw 'divide by zero';
}
if (this.is_zero()) {
result = this;
} else if (!this.is_valid()) {
throw new Error('Invalid dividend');
} else if (!d.is_valid()) {
throw new Error('Invalid divisor');
} else {
var _n = this;
if (_n.is_native()) {
_n = _n.clone();
while (_n._value.compareTo(consts.bi_man_min_value) < 0) {
_n._value = _n._value.multiply(consts.bi_10);
_n._offset -= 1;
}
}
var _d = d;
if (_d.is_native()) {
_d = _d.clone();
while (_d._value.compareTo(consts.bi_man_min_value) < 0) {
_d._value = _d._value.multiply(consts.bi_10);
_d._offset -= 1;
}
}
result = new Amount();
result._offset = _n._offset - _d._offset - 17;
result._value = _n._value.multiply(consts.bi_1e17).divide(_d._value).add(consts.bi_5);
result._is_native = _n._is_native;
result._is_negative = _n._is_negative !== _d._is_negative;
result._currency = _n._currency;
result._issuer = _n._issuer;
result.canonicalize();
}
return result;
};
/**
* Calculate a ratio between two amounts.
*
* This function calculates a ratio - such as a price - between two Amount
* objects.
*
* The return value will have the same type (currency) as the numerator. This is
* a simplification, which should be sane in most cases. For example, a USD/XRP
* price would be rendered as USD.
*
* @example
* var price = buy_amount.ratio_human(sell_amount);
*
* @this {Amount} The numerator (top half) of the fraction.
* @param {Amount} denominator The denominator (bottom half) of the fraction.
* @param opts Options for the calculation.
* @param opts.reference_date {Date|Number} Date based on which demurrage/interest
* should be applied. Can be given as JavaScript Date or int for Ripple epoch.
* @return {Amount} The resulting ratio. Unit will be the same as numerator.
*/
Amount.prototype.ratio_human = function (denominator, opts) {
opts = opts || {};
if (typeof denominator === 'number' && parseInt(denominator, 10) === denominator) {
// Special handling of integer arguments
denominator = Amount.from_json('' + denominator + '.0');
} else {
denominator = Amount.from_json(denominator);
}
var numerator = this;
denominator = Amount.from_json(denominator);
// If either operand is NaN, the result is NaN.
if (!numerator.is_valid() || !denominator.is_valid()) {
return Amount.NaN();
}
// Apply interest/demurrage
//
// We only need to apply it to the second factor, because the currency unit of
// the first factor will carry over into the result.
if (opts.reference_date) {
denominator = denominator.applyInterest(opts.reference_date);
}
// Special case: The denominator is a native (XRP) amount.
//
// In that case, it's going to be expressed as base units (1 XRP =
// 10^xns_precision base units).
//
// However, the unit of the denominator is lost, so when the resulting ratio
// is printed, the ratio is going to be too small by a factor of
// 10^xns_precision.
//
// To compensate, we multiply the numerator by 10^xns_precision.
if (denominator._is_native) {
numerator = numerator.clone();
numerator._value = numerator._value.multiply(consts.bi_xns_unit);
numerator.canonicalize();
}
return numerator.divide(denominator);
};
/**
* Calculate a product of two amounts.
*
* This function allows you to calculate a product between two amounts which
* retains XRPs human/external interpretation (i.e. 1 XRP = 1,000,000 base
* units).
*
* Intended use is to calculate something like: 10 USD * 10 XRP/USD = 100 XRP
*
* @example
* var sell_amount = buy_amount.product_human(price);
*
* @see Amount#ratio_human
*
* @this {Amount} The first factor of the product.
* @param {Amount} factor The second factor of the product.
* @param opts Options for the calculation.
* @param opts.reference_date {Date|Number} Date based on which demurrage/interest
* should be applied. Can be given as JavaScript Date or int for Ripple epoch.
* @return {Amount} The product. Unit will be the same as the first factor.
*/
Amount.prototype.product_human = function (factor, opts) {
opts = opts || {};
if (typeof factor === 'number' && parseInt(factor, 10) === factor) {
// Special handling of integer arguments
factor = Amount.from_json(String(factor) + '.0');
} else {
factor = Amount.from_json(factor);
}
// If either operand is NaN, the result is NaN.
if (!this.is_valid() || !factor.is_valid()) {
return Amount.NaN();
}
// Apply interest/demurrage
//
// We only need to apply it to the second factor, because the currency unit of
// the first factor will carry over into the result.
if (opts.reference_date) {
factor = factor.applyInterest(opts.reference_date);
}
var product = this.multiply(factor);
// Special case: The second factor is a native (XRP) amount expressed as base
// units (1 XRP = 10^xns_precision base units).
//
// See also Amount#ratio_human.
if (factor._is_native) {
product._value = product._value.divide(consts.bi_xns_unit);
product.canonicalize();
}
return product;
}
// True if Amounts are valid and both native or non-native.
Amount.prototype.is_comparable = function (v) {
return this._value instanceof BigInteger
&& v._value instanceof BigInteger
&& this._is_native === v._is_native;
};
Amount.prototype.is_native = function () {
return this._is_native;
};
Amount.prototype.is_negative = function () {
return this._value instanceof BigInteger
? this._is_negative
: false; // NaN is not negative
};
Amount.prototype.is_positive = function () {
return !this.is_zero() && !this.is_negative();
};
// Only checks the value. Not the currency and issuer.
Amount.prototype.is_valid = function () {
return this._value instanceof BigInteger;
};
Amount.prototype.is_valid_full = function () {
return this.is_valid() && this._currency.is_valid() && this._issuer.is_valid();
};
Amount.prototype.is_zero = function () {
return this._value instanceof BigInteger ? this._value.equals(BigInteger.ZERO) : false;
};
Amount.prototype.issuer = function () {
return this._issuer;
};
// Result in terms of this' currency and issuer.
// XXX Diverges from cpp.
Amount.prototype.multiply = function (v) {
var result;
if (this.is_zero()) {
result = this;
} else if (v.is_zero()) {
result = this.clone();
result._value = BigInteger.ZERO;
} else {
var v1 = this._value;
var o1 = this._offset;
var v2 = v._value;
var o2 = v._offset;
if (this.is_native()) {
while (v1.compareTo(consts.bi_man_min_value) < 0) {
v1 = v1.multiply(consts.bi_10);
o1 -= 1;
}
}
if (v.is_native()) {
while (v2.compareTo(consts.bi_man_min_value) < 0) {
v2 = v2.multiply(consts.bi_10);
o2 -= 1;
}
}
result = new Amount();
result._offset = o1 + o2 + 14;
result._value = v1.multiply(v2).divide(consts.bi_1e14).add(consts.bi_7);
result._is_native = this._is_native;
result._is_negative = this._is_negative !== v._is_negative;
result._currency = this._currency;
result._issuer = this._issuer;
result.canonicalize();
}
return result;
};
// Return a new value.
Amount.prototype.negate = function () {
return this.clone('NEGATE');
};
/**
* Invert this amount and return the new value.
*
* Creates a new Amount object as a copy of the current one (including the same
* unit (currency & issuer), inverts it (1/x) and returns the result.
*/
Amount.prototype.invert = function () {
var one = this.clone();
one._value = BigInteger.ONE;
one._offset = 0;
one._is_negative = false;
one.canonicalize();
return one.ratio_human(this);
};
/**
* Tries to correctly interpret an amount as entered by a user.
*
* Examples:
*
* XRP 250 => 250000000/XRP
* 25.2 XRP => 25200000/XRP
* USD 100.40 => 100.4/USD/?
* 100 => 100000000/XRP
*/
Amount.human_RE = /^\s*([a-z]{3})?\s*(-)?(\d+)(?:\.(\d*))?\s*([a-f0-9]{40}|[a-z0-9]{3})?\s*$/i;
Amount.prototype.parse_human = function (j, opts) {
opts = opts || {};
var m = String(j).match(Amount.human_RE);
if (m) {
var currency = m[1] || m[5] || 'XRP';
var integer = m[3] || '0';
var fraction = m[4] || '';
var precision = null;
currency = currency.toUpperCase();
this._value = new BigInteger(integer);
this.set_currency(currency);
// XRP have exactly six digits of precision
if (currency === 'XRP') {
fraction = fraction.slice(0, 6);
while (fraction.length < 6) {
fraction += '0';
}
this._is_native = true;
this._value = this._value.multiply(consts.bi_xns_unit).add(new BigInteger(fraction));
} else {
// Other currencies have arbitrary precision
fraction = fraction.replace(/0+$/, '');
precision = fraction.length;
this._is_native = false;
var multiplier = consts.bi_10.clone().pow(precision);
this._value = this._value.multiply(multiplier).add(new BigInteger(fraction));
this._offset = -precision;
this.canonicalize();
}
this._is_negative = !!m[2];
// Apply interest/demurrage
if (opts.reference_date && this._currency.has_interest()) {
var interest = this._currency.get_interest_at(opts.reference_date);
// XXX Because the Amount parsing routines don't support some of the things
// that JavaScript can output when casting a float to a string, the
// following call sometimes does not produce a valid Amount.
//
// The correct way to solve this is probably to switch to a proper
// BigDecimal for our internal representation and then use that across
// the board instead of instantiating these dummy Amount objects.
var interestTempAmount = Amount.from_json(""+interest+"/1/1");
if (interestTempAmount.is_valid()) {
var ref = this.divide(interestTempAmount);
this._value = ref._value;
this._offset = ref._offset;
}
}
} else {
this._value = NaN;
}
return this;
};
Amount.prototype.parse_issuer = function (issuer) {
this._issuer = UInt160.from_json(issuer);
return this;
};
/**
* Decode a price from a BookDirectory index.
*
* BookDirectory ledger entries each encode the offer price in their index. This
* method can decode that information and populate an Amount object with it.
*
* It is possible not to provide a currency or issuer, but be aware that Amount
* objects behave differently based on the currency, so you may get incorrect
* results.
*
* Prices involving demurraging currencies are tricky, since they depend on the
* base and counter currencies.
*
* @param quality {String} 8 hex bytes quality or 32 hex bytes BookDirectory
* index.
* @param counterCurrency {Currency|String} Currency of the resulting Amount
* object.
* @param counterIssuer {Issuer|String} Issuer of the resulting Amount object.
* @param opts Additional options
* @param opts.inverse {Boolean} If true, return the inverse of the price
* encoded in the quality.
* @param opts.base_currency {Currency|String} The other currency. This plays a
* role with interest-bearing or demurrage currencies. In that case the
* demurrage has to be applied when the quality is decoded, otherwise the
* price will be false.
* @param opts.reference_date {Date|Number} Date based on which demurrage/interest
* should be applied. Can be given as JavaScript Date or int for Ripple epoch.
* @param opts.xrp_as_drops {Boolean} Whether XRP amount should be treated as
* drops. When the base currency is XRP, the quality is calculated in drops.
* For human use however, we want to think of 1000000 drops as 1 XRP and
* prices as per-XRP instead of per-drop.
*/
Amount.prototype.parse_quality = function (quality, counterCurrency, counterIssuer, opts)
{
opts = opts || {};
var baseCurrency = Currency.from_json(opts.base_currency);
this._is_negative = false;
this._value = new BigInteger(quality.substring(quality.length-14), 16);
this._offset = parseInt(quality.substring(quality.length-16, quality.length-14), 16)-100;
this._currency = Currency.from_json(counterCurrency);
this._issuer = UInt160.from_json(counterIssuer);
this._is_native = this._currency.is_native();
// Correct offset if xrp_as_drops option is not set and base currency is XRP
if (!opts.xrp_as_drops &&
baseCurrency.is_valid() &&
baseCurrency.is_native()) {
if (opts.inverse) {
this._offset -= 6;
} else {
this._offset += 6;
}
}
if (opts.inverse) {
this._invert();
}
this.canonicalize();
if (opts.reference_date && baseCurrency.is_valid() && baseCurrency.has_interest()) {
var interest = baseCurrency.get_interest_at(opts.reference_date);
// XXX If we had better math utilities, we wouldn't need this hack.
var interestTempAmount = Amount.from_json(""+interest+"/1/1");
if (interestTempAmount.is_valid()) {
var v = this.divide(interestTempAmount);
this._value = v._value;
this._offset = v._offset;
}
}
return this;
}
Amount.prototype.parse_number = function (n) {
this._is_native = false;
this._currency = Currency.from_json(1);
this._issuer = UInt160.from_json(1);
this._is_negative = n < 0 ? 1 : 0;
this._value = new BigInteger(String(this._is_negative ? -n : n));
this._offset = 0;
this.canonicalize();
return this;
};
// <-> j
Amount.prototype.parse_json = function (j) {
switch (typeof j) {
case 'string':
// .../.../... notation is not a wire format. But allowed for easier testing.
var m = j.match(/^([^/]+)\/([^/]+)(?:\/(.+))?$/);
if (m) {
this._currency = Currency.from_json(m[2]);
if (m[3]) {
this._issuer = UInt160.from_json(m[3]);
} else {
this._issuer = UInt160.from_json('1');
}
this.parse_value(m[1]);
} else {
this.parse_native(j);
this._currency = Currency.from_json('0');
this._issuer = UInt160.from_json('0');
}
break;
case 'number':
this.parse_json(String(j));
break;
case 'object':
if (j === null) break;
if (j instanceof Amount) {
j.copyTo(this);
} else if (j.hasOwnProperty('value')) {
// Parse the passed value to sanitize and copy it.
this._currency.parse_json(j.currency, true); // Never XRP.
if (typeof j.issuer === 'string') {
this._issuer.parse_json(j.issuer);
}
this.parse_value(j.value);
}
break;
default:
this._value = NaN;
}
return this;
};
// Parse a XRP value from untrusted input.
// - integer = raw units
// - float = with precision 6
// XXX Improvements: disallow leading zeros.
Amount.prototype.parse_native = function (j) {
var m;
if (typeof j === 'string') {
m = j.match(/^(-?)(\d*)(\.\d{0,6})?$/);
}
if (m) {
if (m[3] === void(0)) {
// Integer notation
this._value = new BigInteger(m[2]);
} else {
// Float notation : values multiplied by 1,000,000.
var int_part = (new BigInteger(m[2])).multiply(consts.bi_xns_unit);
var fraction_part = (new BigInteger(m[3])).multiply(new BigInteger(String(Math.pow(10, 1+consts.xns_precision-m[3].length))));
this._value = int_part.add(fraction_part);
}
this._is_native = true;
this._offset = 0;
this._is_negative = !!m[1] && this._value.compareTo(BigInteger.ZERO) !== 0;
if (this._value.compareTo(consts.bi_xns_max) > 0) {
this._value = NaN;
}
} else {
this._value = NaN;
}
return this;
};
// Parse a non-native value for the json wire format.
// Requires _currency to be set!
Amount.prototype.parse_value = function (j) {
this._is_native = false;
switch (typeof j) {
case 'number':
this._is_negative = j < 0;
this._value = new BigInteger(Math.abs(j));
this._offset = 0;
this.canonicalize();
break;
case 'string':
var i = j.match(/^(-?)(\d+)$/);
var d = !i && j.match(/^(-?)(\d*)\.(\d*)$/);
var e = !e && j.match(/^(-?)(\d*)e(-?\d+)$/);
if (e) {
// e notation
this._value = new BigInteger(e[2]);
this._offset = parseInt(e[3]);
this._is_negative = !!e[1];
this.canonicalize();
} else if (d) {
// float notation
var integer = new BigInteger(d[2]);
var fraction = new BigInteger(d[3]);
var precision = d[3].length;
this._value = integer.multiply(consts.bi_10.clone().pow(precision)).add(fraction);
this._offset = -precision;
this._is_negative = !!d[1];
this.canonicalize();
} else if (i) {
// integer notation
this._value = new BigInteger(i[2]);
this._offset = 0;
this._is_negative = !!i[1];
this.canonicalize();
} else {
this._value = NaN;
}
break;
default:
this._value = j instanceof BigInteger ? j : NaN;
}
return this;
};
Amount.prototype.set_currency = function (c) {
this._currency = Currency.from_json(c);
this._is_native = this._currency.is_native();
return this;
};
Amount.prototype.set_issuer = function (issuer) {
if (issuer instanceof UInt160) {
this._issuer = issuer;
} else {
this._issuer = UInt160.from_json(issuer);
}
return this;
};
// Result in terms of this' currency and issuer.
Amount.prototype.subtract = function (v) {
// Correctness over speed, less code has less bugs, reuse add code.
return this.add(Amount.from_json(v).negate());
};
Amount.prototype.to_number = function (allow_nan) {
var s = this.to_text(allow_nan);
return typeof s === 'string' ? Number(s) : s;
};
// Convert only value to JSON wire format.
Amount.prototype.to_text = function (allow_nan) {
var result = NaN;
if (this._is_native) {
if (this.is_valid() && this._value.compareTo(consts.bi_xns_max) <= 0){
result = this._value.toString();
}
} else if (this.is_zero()) {
result = '0';
} else if (this._offset && (this._offset < -25 || this._offset > -4)) {
// Use e notation.
// XXX Clamp output.
result = this._value.toString() + 'e' + this._offset;
} else {
var val = '000000000000000000000000000' + this._value.toString() + '00000000000000000000000';
var pre = val.substring(0, this._offset + 43);
var post = val.substring(this._offset + 43);
var s_pre = pre.match(/[1-9].*$/); // Everything but leading zeros.
var s_post = post.match(/[1-9]0*$/); // Last non-zero plus trailing zeros.
result = ''
+ (s_pre ? s_pre[0] : '0')
+ (s_post ? '.' + post.substring(0, 1 + post.length - s_post[0].length) : '');
}
if (!allow_nan && typeof result === 'number' && isNaN(result)) {
result = '0';
} else if (this._is_negative) {
result = '-' + result;
}
return result;
};
/**
* Calculate present value based on currency and a reference date.
*
* This only affects demurraging and interest-bearing currencies.
*
* User should not store amount objects after the interest is applied. This is
* intended by display functions such as toHuman().
*
* @param referenceDate {Date|Number} Date based on which demurrage/interest
* should be applied. Can be given as JavaScript Date or int for Ripple epoch.
* @return {Amount} The amount with interest applied.
*/
Amount.prototype.applyInterest = function (referenceDate) {
if (this._currency.has_interest()) {
var interest = this._currency.get_interest_at(referenceDate);
// XXX Because the Amount parsing routines don't support some of the things
// that JavaScript can output when casting a float to a string, the
// following call sometimes does not produce a valid Amount.
//
// The correct way to solve this is probably to switch to a proper
// BigDecimal for our internal representation and then use that across
// the board instead of instantiating these dummy Amount objects.
var interestTempAmount = Amount.from_json(""+interest+"/1/1");
if (interestTempAmount.is_valid()) {
return this.multiply(interestTempAmount);
}
} else {
return this;
}
};
/**
* Format only value in a human-readable format.