-
Notifications
You must be signed in to change notification settings - Fork 4
/
bundle.js
13494 lines (11526 loc) · 391 KB
/
bundle.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
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
console.time('[start]')
const bel = require('bel')
const sca = require('smartcontract-app')
const solcjs = require('./')
const selectVersion = solcjs.version2url // require('./src/node_modules/version2url')
/* @TODO:
var { all } = await solcjs.versions()
var compiler = await solcjs(all[0])
var output = compiler`...code...`
*/
selectVersion((error, select) => {
if (error) return console.error(error)
const useVersion = (error, url) => {
if (error) return console.error(error)
console.log('url:', url)
solcjs(url, start)
}
const { releases, nightly, all} = select
const version = releases[0] // @NOTE: hard code to use latest version
select(version, useVersion)
document.body.appendChild(selector(releases, v => select(v, useVersion)))
})
function selector (list, action) {
const onchange = event => action(event.target.value)
return bel`
<select onchange=${onchange}>
${list.map(x => bel`<option value="${x}">${x}</option>`)}
</select>`
}
async function start (error, solc) {
if (error) return console.error(error)
console.time('[compile stuff]')
try {
// pragma solidity ^0.4.25;
var output = await /* solc(input) // OR */ solc`
contract Mortal {
address public owner;
constructor() public { owner = msg.sender; }
function kill() { if (msg.sender == owner) selfdestruct(owner); }
}
contract Greeter is Mortal {
string public greeting;
constructor(string memory _greeting) public {
greeting = _greeting;
}
}`
console.log('*** success ***')
document.body.appendChild(bel`<h1>success</h1>`)
console.log('[output]', output)
var opts = {
metadata: {
compiler: { version: output[0].compiler.version },
language: output[0].compiler.language,
output: {
abi: JSON.parse(output[0].abi),
devdoc: output[0].metadata.devdoc,
userdoc: output[0].metadata.userdoc
},
settings: {
compilationTarget: { '': output[0].sources.compilationTarget },
evmVersion: output[0].compiler.evmVersion,
libraries: output[0].sources.libraries,
optimizer: { enabled: output[0].compiler.optimizer, runs: output[0].compiler.runs },
remapings: output[0].sources.remappings
},
sources: { '': output[0].sources.sourcecode }
}
}
var el = sca(opts)
document.body.appendChild(el)
// @TODO: do in-website-only most minimal test library + iframe compatible dom reporter
// testCompiler(solc)
} catch (error) {
console.log('*** fail ***')
document.body.appendChild(bel`<h1>fail</h1>`)
console.error('[error]', error)
} finally {
console.timeEnd('[compile stuff]')
console.timeEnd('[start]')
}
}
function testCompiler (solc) {
var input1 = 'contract x { function g() {} }'
var input2 = 'contract y { function f() {} }'
// Setting 1 as second paramateractivates the optimiser
async function compile (input) {
console.time('[compile]')
// var output = await solc(input)
var output = solc.compile(input, 1)
console.timeEnd('[compile]')
console.log('output', output)
}
var id = setInterval(() => compile(input1), 500)
setTimeout(() => {
console.log('====================')
clearInterval(id)
id = setInterval(() => compile(input2), 500)
setTimeout(() => clearInterval(id), 5000)
}, 5000)
}
},{"./":73,"bel":3,"smartcontract-app":48}],2:[function(require,module,exports){
var trailingNewlineRegex = /\n[\s]+$/
var leadingNewlineRegex = /^\n[\s]+/
var trailingSpaceRegex = /[\s]+$/
var leadingSpaceRegex = /^[\s]+/
var multiSpaceRegex = /[\n\s]+/g
var TEXT_TAGS = [
'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite', 'data', 'dfn', 'em', 'i',
'kbd', 'mark', 'q', 'rp', 'rt', 'rtc', 'ruby', 's', 'amp', 'small', 'span',
'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr'
]
var VERBATIM_TAGS = [
'code', 'pre', 'textarea'
]
module.exports = function appendChild (el, childs) {
if (!Array.isArray(childs)) return
var nodeName = el.nodeName.toLowerCase()
var hadText = false
var value, leader
for (var i = 0, len = childs.length; i < len; i++) {
var node = childs[i]
if (Array.isArray(node)) {
appendChild(el, node)
continue
}
if (typeof node === 'number' ||
typeof node === 'boolean' ||
typeof node === 'function' ||
node instanceof Date ||
node instanceof RegExp) {
node = node.toString()
}
var lastChild = el.childNodes[el.childNodes.length - 1]
// Iterate over text nodes
if (typeof node === 'string') {
hadText = true
// If we already had text, append to the existing text
if (lastChild && lastChild.nodeName === '#text') {
lastChild.nodeValue += node
// We didn't have a text node yet, create one
} else {
node = document.createTextNode(node)
el.appendChild(node)
lastChild = node
}
// If this is the last of the child nodes, make sure we close it out
// right
if (i === len - 1) {
hadText = false
// Trim the child text nodes if the current node isn't a
// node where whitespace matters.
if (TEXT_TAGS.indexOf(nodeName) === -1 &&
VERBATIM_TAGS.indexOf(nodeName) === -1) {
value = lastChild.nodeValue
.replace(leadingNewlineRegex, '')
.replace(trailingSpaceRegex, '')
.replace(trailingNewlineRegex, '')
.replace(multiSpaceRegex, ' ')
if (value === '') {
el.removeChild(lastChild)
} else {
lastChild.nodeValue = value
}
} else if (VERBATIM_TAGS.indexOf(nodeName) === -1) {
// The very first node in the list should not have leading
// whitespace. Sibling text nodes should have whitespace if there
// was any.
leader = i === 0 ? '' : ' '
value = lastChild.nodeValue
.replace(leadingNewlineRegex, leader)
.replace(leadingSpaceRegex, ' ')
.replace(trailingSpaceRegex, '')
.replace(trailingNewlineRegex, '')
.replace(multiSpaceRegex, ' ')
lastChild.nodeValue = value
}
}
// Iterate over DOM nodes
} else if (node && node.nodeType) {
// If the last node was a text node, make sure it is properly closed out
if (hadText) {
hadText = false
// Trim the child text nodes if the current node isn't a
// text node or a code node
if (TEXT_TAGS.indexOf(nodeName) === -1 &&
VERBATIM_TAGS.indexOf(nodeName) === -1) {
value = lastChild.nodeValue
.replace(leadingNewlineRegex, '')
.replace(trailingNewlineRegex, '')
.replace(multiSpaceRegex, ' ')
// Remove empty text nodes, append otherwise
if (value === '') {
el.removeChild(lastChild)
} else {
lastChild.nodeValue = value
}
// Trim the child nodes if the current node is not a node
// where all whitespace must be preserved
} else if (VERBATIM_TAGS.indexOf(nodeName) === -1) {
value = lastChild.nodeValue
.replace(leadingSpaceRegex, ' ')
.replace(leadingNewlineRegex, '')
.replace(trailingNewlineRegex, '')
.replace(multiSpaceRegex, ' ')
lastChild.nodeValue = value
}
}
// Store the last nodename
var _nodeName = node.nodeName
if (_nodeName) nodeName = _nodeName.toLowerCase()
// Append the node to the DOM
el.appendChild(node)
}
}
}
},{}],3:[function(require,module,exports){
var hyperx = require('hyperx')
var appendChild = require('./appendChild')
var SVGNS = 'http://www.w3.org/2000/svg'
var XLINKNS = 'http://www.w3.org/1999/xlink'
var BOOL_PROPS = [
'autofocus', 'checked', 'defaultchecked', 'disabled', 'formnovalidate',
'indeterminate', 'readonly', 'required', 'selected', 'willvalidate'
]
var COMMENT_TAG = '!--'
var SVG_TAGS = [
'svg', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateColor',
'animateMotion', 'animateTransform', 'circle', 'clipPath', 'color-profile',
'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColorMatrix',
'feComponentTransfer', 'feComposite', 'feConvolveMatrix',
'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood',
'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage',
'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight',
'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'filter',
'font', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src',
'font-face-uri', 'foreignObject', 'g', 'glyph', 'glyphRef', 'hkern', 'image',
'line', 'linearGradient', 'marker', 'mask', 'metadata', 'missing-glyph',
'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect',
'set', 'stop', 'switch', 'symbol', 'text', 'textPath', 'title', 'tref',
'tspan', 'use', 'view', 'vkern'
]
function belCreateElement (tag, props, children) {
var el
// If an svg tag, it needs a namespace
if (SVG_TAGS.indexOf(tag) !== -1) {
props.namespace = SVGNS
}
// If we are using a namespace
var ns = false
if (props.namespace) {
ns = props.namespace
delete props.namespace
}
// Create the element
if (ns) {
el = document.createElementNS(ns, tag)
} else if (tag === COMMENT_TAG) {
return document.createComment(props.comment)
} else {
el = document.createElement(tag)
}
// Create the properties
for (var p in props) {
if (props.hasOwnProperty(p)) {
var key = p.toLowerCase()
var val = props[p]
// Normalize className
if (key === 'classname') {
key = 'class'
p = 'class'
}
// The for attribute gets transformed to htmlFor, but we just set as for
if (p === 'htmlFor') {
p = 'for'
}
// If a property is boolean, set itself to the key
if (BOOL_PROPS.indexOf(key) !== -1) {
if (val === 'true') val = key
else if (val === 'false') continue
}
// If a property prefers being set directly vs setAttribute
if (key.slice(0, 2) === 'on') {
el[p] = val
} else {
if (ns) {
if (p === 'xlink:href') {
el.setAttributeNS(XLINKNS, p, val)
} else if (/^xmlns($|:)/i.test(p)) {
// skip xmlns definitions
} else {
el.setAttributeNS(null, p, val)
}
} else {
el.setAttribute(p, val)
}
}
}
}
appendChild(el, children)
return el
}
module.exports = hyperx(belCreateElement, {comments: true})
module.exports.default = module.exports
module.exports.createElement = belCreateElement
},{"./appendChild":2,"hyperx":28}],4:[function(require,module,exports){
;(function (globalObject) {
'use strict';
/*
* bignumber.js v8.0.1
* A JavaScript library for arbitrary-precision arithmetic.
* https://github.com/MikeMcl/bignumber.js
* Copyright (c) 2018 Michael Mclaughlin <[email protected]>
* MIT Licensed.
*
* BigNumber.prototype methods | BigNumber methods
* |
* absoluteValue abs | clone
* comparedTo | config set
* decimalPlaces dp | DECIMAL_PLACES
* dividedBy div | ROUNDING_MODE
* dividedToIntegerBy idiv | EXPONENTIAL_AT
* exponentiatedBy pow | RANGE
* integerValue | CRYPTO
* isEqualTo eq | MODULO_MODE
* isFinite | POW_PRECISION
* isGreaterThan gt | FORMAT
* isGreaterThanOrEqualTo gte | ALPHABET
* isInteger | isBigNumber
* isLessThan lt | maximum max
* isLessThanOrEqualTo lte | minimum min
* isNaN | random
* isNegative | sum
* isPositive |
* isZero |
* minus |
* modulo mod |
* multipliedBy times |
* negated |
* plus |
* precision sd |
* shiftedBy |
* squareRoot sqrt |
* toExponential |
* toFixed |
* toFormat |
* toFraction |
* toJSON |
* toNumber |
* toPrecision |
* toString |
* valueOf |
*
*/
var BigNumber,
isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,
mathceil = Math.ceil,
mathfloor = Math.floor,
bignumberError = '[BigNumber Error] ',
tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',
BASE = 1e14,
LOG_BASE = 14,
MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
// MAX_INT32 = 0x7fffffff, // 2^31 - 1
POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
SQRT_BASE = 1e7,
// EDITABLE
// The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
// the arguments to toExponential, toFixed, toFormat, and toPrecision.
MAX = 1E9; // 0 to MAX_INT32
/*
* Create and return a BigNumber constructor.
*/
function clone(configObject) {
var div, convertBase, parseNumeric,
P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },
ONE = new BigNumber(1),
//----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------
// The default values below must be integers within the inclusive ranges stated.
// The values can also be changed at run-time using BigNumber.set.
// The maximum number of decimal places for operations involving division.
DECIMAL_PLACES = 20, // 0 to MAX
// The rounding mode used when rounding to the above decimal places, and when using
// toExponential, toFixed, toFormat and toPrecision, and round (default value).
// UP 0 Away from zero.
// DOWN 1 Towards zero.
// CEIL 2 Towards +Infinity.
// FLOOR 3 Towards -Infinity.
// HALF_UP 4 Towards nearest neighbour. If equidistant, up.
// HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
// HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
// HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
// HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
ROUNDING_MODE = 4, // 0 to 8
// EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
// The exponent value at and beneath which toString returns exponential notation.
// Number type: -7
TO_EXP_NEG = -7, // 0 to -MAX
// The exponent value at and above which toString returns exponential notation.
// Number type: 21
TO_EXP_POS = 21, // 0 to MAX
// RANGE : [MIN_EXP, MAX_EXP]
// The minimum exponent value, beneath which underflow to zero occurs.
// Number type: -324 (5e-324)
MIN_EXP = -1e7, // -1 to -MAX
// The maximum exponent value, above which overflow to Infinity occurs.
// Number type: 308 (1.7976931348623157e+308)
// For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
MAX_EXP = 1e7, // 1 to MAX
// Whether to use cryptographically-secure random number generation, if available.
CRYPTO = false, // true or false
// The modulo mode used when calculating the modulus: a mod n.
// The quotient (q = a / n) is calculated according to the corresponding rounding mode.
// The remainder (r) is calculated as: r = a - n * q.
//
// UP 0 The remainder is positive if the dividend is negative, else is negative.
// DOWN 1 The remainder has the same sign as the dividend.
// This modulo mode is commonly known as 'truncated division' and is
// equivalent to (a % n) in JavaScript.
// FLOOR 3 The remainder has the same sign as the divisor (Python %).
// HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
// EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
// The remainder is always positive.
//
// The truncated division, floored division, Euclidian division and IEEE 754 remainder
// modes are commonly used for the modulus operation.
// Although the other rounding modes can also be used, they may not give useful results.
MODULO_MODE = 1, // 0 to 9
// The maximum number of significant digits of the result of the exponentiatedBy operation.
// If POW_PRECISION is 0, there will be unlimited significant digits.
POW_PRECISION = 0, // 0 to MAX
// The format specification used by the BigNumber.prototype.toFormat method.
FORMAT = {
prefix: '',
groupSize: 3,
secondaryGroupSize: 0,
groupSeparator: ',',
decimalSeparator: '.',
fractionGroupSize: 0,
fractionGroupSeparator: '\xA0', // non-breaking space
suffix: ''
},
// The alphabet used for base conversion. It must be at least 2 characters long, with no '+',
// '-', '.', whitespace, or repeated character.
// '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
//------------------------------------------------------------------------------------------
// CONSTRUCTOR
/*
* The BigNumber constructor and exported function.
* Create and return a new instance of a BigNumber object.
*
* n {number|string|BigNumber} A numeric value.
* [b] {number} The base of n. Integer, 2 to ALPHABET.length inclusive.
*/
function BigNumber(n, b) {
var alphabet, c, caseChanged, e, i, isNum, len, str,
x = this;
// Enable constructor usage without new.
if (!(x instanceof BigNumber)) {
// Don't throw on constructor call without new (#81).
// '[BigNumber Error] Constructor call without new: {n}'
//throw Error(bignumberError + ' Constructor call without new: ' + n);
return new BigNumber(n, b);
}
if (b == null) {
// Duplicate.
if (n instanceof BigNumber) {
x.s = n.s;
x.e = n.e;
x.c = (n = n.c) ? n.slice() : n;
return;
}
isNum = typeof n == 'number';
if (isNum && n * 0 == 0) {
// Use `1 / n` to handle minus zero also.
x.s = 1 / n < 0 ? (n = -n, -1) : 1;
// Faster path for integers.
if (n === ~~n) {
for (e = 0, i = n; i >= 10; i /= 10, e++);
x.e = e;
x.c = [n];
return;
}
str = String(n);
} else {
str = String(n);
if (!isNumeric.test(str)) return parseNumeric(x, str, isNum);
x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;
}
// Decimal point?
if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
// Exponential form?
if ((i = str.search(/e/i)) > 0) {
// Determine exponent.
if (e < 0) e = i;
e += +str.slice(i + 1);
str = str.substring(0, i);
} else if (e < 0) {
// Integer.
e = str.length;
}
} else {
// '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'
intCheck(b, 2, ALPHABET.length, 'Base');
str = String(n);
// Allow exponential notation to be used with base 10 argument, while
// also rounding to DECIMAL_PLACES as with other bases.
if (b == 10) {
x = new BigNumber(n instanceof BigNumber ? n : str);
return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);
}
isNum = typeof n == 'number';
if (isNum) {
// Avoid potential interpretation of Infinity and NaN as base 44+ values.
if (n * 0 != 0) return parseNumeric(x, str, isNum, b);
x.s = 1 / n < 0 ? (str = str.slice(1), -1) : 1;
// '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) {
throw Error
(tooManyDigits + n);
}
// Prevent later check for length on converted number.
isNum = false;
} else {
x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;
}
alphabet = ALPHABET.slice(0, b);
e = i = 0;
// Check that str is a valid base b number.
// Don't use RegExp so alphabet can contain special characters.
for (len = str.length; i < len; i++) {
if (alphabet.indexOf(c = str.charAt(i)) < 0) {
if (c == '.') {
// If '.' is not the first character and it has not be found before.
if (i > e) {
e = len;
continue;
}
} else if (!caseChanged) {
// Allow e.g. hexadecimal 'FF' as well as 'ff'.
if (str == str.toUpperCase() && (str = str.toLowerCase()) ||
str == str.toLowerCase() && (str = str.toUpperCase())) {
caseChanged = true;
i = -1;
e = 0;
continue;
}
}
return parseNumeric(x, String(n), isNum, b);
}
}
str = convertBase(str, b, 10, x.s);
// Decimal point?
if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
else e = str.length;
}
// Determine leading zeros.
for (i = 0; str.charCodeAt(i) === 48; i++);
// Determine trailing zeros.
for (len = str.length; str.charCodeAt(--len) === 48;);
str = str.slice(i, ++len);
if (str) {
len -= i;
// '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
if (isNum && BigNumber.DEBUG &&
len > 15 && (n > MAX_SAFE_INTEGER || n !== mathfloor(n))) {
throw Error
(tooManyDigits + (x.s * n));
}
e = e - i - 1;
// Overflow?
if (e > MAX_EXP) {
// Infinity.
x.c = x.e = null;
// Underflow?
} else if (e < MIN_EXP) {
// Zero.
x.c = [x.e = 0];
} else {
x.e = e;
x.c = [];
// Transform base
// e is the base 10 exponent.
// i is where to slice str to get the first element of the coefficient array.
i = (e + 1) % LOG_BASE;
if (e < 0) i += LOG_BASE;
if (i < len) {
if (i) x.c.push(+str.slice(0, i));
for (len -= LOG_BASE; i < len;) {
x.c.push(+str.slice(i, i += LOG_BASE));
}
str = str.slice(i);
i = LOG_BASE - str.length;
} else {
i -= len;
}
for (; i--; str += '0');
x.c.push(+str);
}
} else {
// Zero.
x.c = [x.e = 0];
}
}
// CONSTRUCTOR PROPERTIES
BigNumber.clone = clone;
BigNumber.ROUND_UP = 0;
BigNumber.ROUND_DOWN = 1;
BigNumber.ROUND_CEIL = 2;
BigNumber.ROUND_FLOOR = 3;
BigNumber.ROUND_HALF_UP = 4;
BigNumber.ROUND_HALF_DOWN = 5;
BigNumber.ROUND_HALF_EVEN = 6;
BigNumber.ROUND_HALF_CEIL = 7;
BigNumber.ROUND_HALF_FLOOR = 8;
BigNumber.EUCLID = 9;
/*
* Configure infrequently-changing library-wide settings.
*
* Accept an object with the following optional properties (if the value of a property is
* a number, it must be an integer within the inclusive range stated):
*
* DECIMAL_PLACES {number} 0 to MAX
* ROUNDING_MODE {number} 0 to 8
* EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]
* RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]
* CRYPTO {boolean} true or false
* MODULO_MODE {number} 0 to 9
* POW_PRECISION {number} 0 to MAX
* ALPHABET {string} A string of two or more unique characters which does
* not contain '.'.
* FORMAT {object} An object with some of the following properties:
* prefix {string}
* groupSize {number}
* secondaryGroupSize {number}
* groupSeparator {string}
* decimalSeparator {string}
* fractionGroupSize {number}
* fractionGroupSeparator {string}
* suffix {string}
*
* (The values assigned to the above FORMAT object properties are not checked for validity.)
*
* E.g.
* BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
*
* Ignore properties/parameters set to null or undefined, except for ALPHABET.
*
* Return an object with the properties current values.
*/
BigNumber.config = BigNumber.set = function (obj) {
var p, v;
if (obj != null) {
if (typeof obj == 'object') {
// DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
// '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'
if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {
v = obj[p];
intCheck(v, 0, MAX, p);
DECIMAL_PLACES = v;
}
// ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
// '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'
if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {
v = obj[p];
intCheck(v, 0, 8, p);
ROUNDING_MODE = v;
}
// EXPONENTIAL_AT {number|number[]}
// Integer, -MAX to MAX inclusive or
// [integer -MAX to 0 inclusive, 0 to MAX inclusive].
// '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'
if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {
v = obj[p];
if (v && v.pop) {
intCheck(v[0], -MAX, 0, p);
intCheck(v[1], 0, MAX, p);
TO_EXP_NEG = v[0];
TO_EXP_POS = v[1];
} else {
intCheck(v, -MAX, MAX, p);
TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);
}
}
// RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
// [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
// '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'
if (obj.hasOwnProperty(p = 'RANGE')) {
v = obj[p];
if (v && v.pop) {
intCheck(v[0], -MAX, -1, p);
intCheck(v[1], 1, MAX, p);
MIN_EXP = v[0];
MAX_EXP = v[1];
} else {
intCheck(v, -MAX, MAX, p);
if (v) {
MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);
} else {
throw Error
(bignumberError + p + ' cannot be zero: ' + v);
}
}
}
// CRYPTO {boolean} true or false.
// '[BigNumber Error] CRYPTO not true or false: {v}'
// '[BigNumber Error] crypto unavailable'
if (obj.hasOwnProperty(p = 'CRYPTO')) {
v = obj[p];
if (v === !!v) {
if (v) {
if (typeof crypto != 'undefined' && crypto &&
(crypto.getRandomValues || crypto.randomBytes)) {
CRYPTO = v;
} else {
CRYPTO = !v;
throw Error
(bignumberError + 'crypto unavailable');
}
} else {
CRYPTO = v;
}
} else {
throw Error
(bignumberError + p + ' not true or false: ' + v);
}
}
// MODULO_MODE {number} Integer, 0 to 9 inclusive.
// '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'
if (obj.hasOwnProperty(p = 'MODULO_MODE')) {
v = obj[p];
intCheck(v, 0, 9, p);
MODULO_MODE = v;
}
// POW_PRECISION {number} Integer, 0 to MAX inclusive.
// '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'
if (obj.hasOwnProperty(p = 'POW_PRECISION')) {
v = obj[p];
intCheck(v, 0, MAX, p);
POW_PRECISION = v;
}
// FORMAT {object}
// '[BigNumber Error] FORMAT not an object: {v}'
if (obj.hasOwnProperty(p = 'FORMAT')) {
v = obj[p];
if (typeof v == 'object') FORMAT = v;
else throw Error
(bignumberError + p + ' not an object: ' + v);
}
// ALPHABET {string}
// '[BigNumber Error] ALPHABET invalid: {v}'
if (obj.hasOwnProperty(p = 'ALPHABET')) {
v = obj[p];
// Disallow if only one character,
// or if it contains '+', '-', '.', whitespace, or a repeated character.
if (typeof v == 'string' && !/^.$|[+-.\s]|(.).*\1/.test(v)) {
ALPHABET = v;
} else {
throw Error
(bignumberError + p + ' invalid: ' + v);
}
}
} else {
// '[BigNumber Error] Object expected: {v}'
throw Error
(bignumberError + 'Object expected: ' + obj);
}
}
return {
DECIMAL_PLACES: DECIMAL_PLACES,
ROUNDING_MODE: ROUNDING_MODE,
EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],
RANGE: [MIN_EXP, MAX_EXP],
CRYPTO: CRYPTO,
MODULO_MODE: MODULO_MODE,
POW_PRECISION: POW_PRECISION,
FORMAT: FORMAT,
ALPHABET: ALPHABET
};
};
/*
* Return true if v is a BigNumber instance, otherwise return false.
*
* v {any}
*/
BigNumber.isBigNumber = function (v) {
return v instanceof BigNumber || v && v._isBigNumber === true || false;
};
/*
* Return a new BigNumber whose value is the maximum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.maximum = BigNumber.max = function () {
return maxOrMin(arguments, P.lt);
};
/*
* Return a new BigNumber whose value is the minimum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.minimum = BigNumber.min = function () {
return maxOrMin(arguments, P.gt);
};
/*
* Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
* and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
* zeros are produced).
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'
* '[BigNumber Error] crypto unavailable'
*/
BigNumber.random = (function () {
var pow2_53 = 0x20000000000000;
// Return a 53 bit integer n, where 0 <= n < 9007199254740992.
// Check if Math.random() produces more than 32 bits of randomness.
// If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
// 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
? function () { return mathfloor(Math.random() * pow2_53); }
: function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
(Math.random() * 0x800000 | 0); };
return function (dp) {
var a, b, e, k, v,
i = 0,
c = [],
rand = new BigNumber(ONE);
if (dp == null) dp = DECIMAL_PLACES;
else intCheck(dp, 0, MAX);
k = mathceil(dp / LOG_BASE);
if (CRYPTO) {
// Browsers supporting crypto.getRandomValues.
if (crypto.getRandomValues) {
a = crypto.getRandomValues(new Uint32Array(k *= 2));
for (; i < k;) {
// 53 bits:
// ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)