natspec.js 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517
  1. require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. },{}],2:[function(require,module,exports){
  3. // shim for using process in browser
  4. var process = module.exports = {};
  5. var queue = [];
  6. var draining = false;
  7. function drainQueue() {
  8. if (draining) {
  9. return;
  10. }
  11. draining = true;
  12. var currentQueue;
  13. var len = queue.length;
  14. while(len) {
  15. currentQueue = queue;
  16. queue = [];
  17. var i = -1;
  18. while (++i < len) {
  19. currentQueue[i]();
  20. }
  21. len = queue.length;
  22. }
  23. draining = false;
  24. }
  25. process.nextTick = function (fun) {
  26. queue.push(fun);
  27. if (!draining) {
  28. setTimeout(drainQueue, 0);
  29. }
  30. };
  31. process.title = 'browser';
  32. process.browser = true;
  33. process.env = {};
  34. process.argv = [];
  35. process.version = ''; // empty string to avoid regexp issues
  36. function noop() {}
  37. process.on = noop;
  38. process.addListener = noop;
  39. process.once = noop;
  40. process.off = noop;
  41. process.removeListener = noop;
  42. process.removeAllListeners = noop;
  43. process.emit = noop;
  44. process.binding = function (name) {
  45. throw new Error('process.binding is not supported');
  46. };
  47. // TODO(shtylman)
  48. process.cwd = function () { return '/' };
  49. process.chdir = function (dir) {
  50. throw new Error('process.chdir is not supported');
  51. };
  52. process.umask = function() { return 0; };
  53. },{}],3:[function(require,module,exports){
  54. /*
  55. This file is part of ethereum.js.
  56. ethereum.js is free software: you can redistribute it and/or modify
  57. it under the terms of the GNU Lesser General Public License as published by
  58. the Free Software Foundation, either version 3 of the License, or
  59. (at your option) any later version.
  60. ethereum.js is distributed in the hope that it will be useful,
  61. but WITHOUT ANY WARRANTY; without even the implied warranty of
  62. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  63. GNU Lesser General Public License for more details.
  64. You should have received a copy of the GNU Lesser General Public License
  65. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  66. */
  67. /** @file abi.js
  68. * @authors:
  69. * Marek Kotewicz <marek@ethdev.com>
  70. * Gav Wood <g@ethdev.com>
  71. * @date 2014
  72. */
  73. var utils = require('./utils');
  74. var types = require('./types');
  75. var c = require('./const');
  76. var f = require('./formatters');
  77. var displayTypeError = function (type) {
  78. console.error('parser does not support type: ' + type);
  79. };
  80. /// This method should be called if we want to check if givent type is an array type
  81. /// @returns true if it is, otherwise false
  82. var arrayType = function (type) {
  83. return type.slice(-2) === '[]';
  84. };
  85. var dynamicTypeBytes = function (type, value) {
  86. // TODO: decide what to do with array of strings
  87. if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.
  88. return f.formatInputInt(value.length);
  89. return "";
  90. };
  91. var inputTypes = types.inputTypes();
  92. /// Formats input params to bytes
  93. /// @param abi contract method inputs
  94. /// @param array of params that will be formatted to bytes
  95. /// @returns bytes representation of input params
  96. var formatInput = function (inputs, params) {
  97. var bytes = "";
  98. var toAppendConstant = "";
  99. var toAppendArrayContent = "";
  100. /// first we iterate in search for dynamic
  101. inputs.forEach(function (input, index) {
  102. bytes += dynamicTypeBytes(input.type, params[index]);
  103. });
  104. inputs.forEach(function (input, i) {
  105. /*jshint maxcomplexity:5 */
  106. var typeMatch = false;
  107. for (var j = 0; j < inputTypes.length && !typeMatch; j++) {
  108. typeMatch = inputTypes[j].type(inputs[i].type, params[i]);
  109. }
  110. if (!typeMatch) {
  111. displayTypeError(inputs[i].type);
  112. }
  113. var formatter = inputTypes[j - 1].format;
  114. if (arrayType(inputs[i].type))
  115. toAppendArrayContent += params[i].reduce(function (acc, curr) {
  116. return acc + formatter(curr);
  117. }, "");
  118. else if (inputs[i].type === 'string')
  119. toAppendArrayContent += formatter(params[i]);
  120. else
  121. toAppendConstant += formatter(params[i]);
  122. });
  123. bytes += toAppendConstant + toAppendArrayContent;
  124. return bytes;
  125. };
  126. var dynamicBytesLength = function (type) {
  127. if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.
  128. return c.ETH_PADDING * 2;
  129. return 0;
  130. };
  131. var outputTypes = types.outputTypes();
  132. /// Formats output bytes back to param list
  133. /// @param contract abi method outputs
  134. /// @param bytes representtion of output
  135. /// @returns array of output params
  136. var formatOutput = function (outs, output) {
  137. output = output.slice(2);
  138. var result = [];
  139. var padding = c.ETH_PADDING * 2;
  140. var dynamicPartLength = outs.reduce(function (acc, curr) {
  141. return acc + dynamicBytesLength(curr.type);
  142. }, 0);
  143. var dynamicPart = output.slice(0, dynamicPartLength);
  144. output = output.slice(dynamicPartLength);
  145. outs.forEach(function (out, i) {
  146. /*jshint maxcomplexity:6 */
  147. var typeMatch = false;
  148. for (var j = 0; j < outputTypes.length && !typeMatch; j++) {
  149. typeMatch = outputTypes[j].type(outs[i].type);
  150. }
  151. if (!typeMatch) {
  152. displayTypeError(outs[i].type);
  153. }
  154. var formatter = outputTypes[j - 1].format;
  155. if (arrayType(outs[i].type)) {
  156. var size = f.formatOutputUInt(dynamicPart.slice(0, padding));
  157. dynamicPart = dynamicPart.slice(padding);
  158. var array = [];
  159. for (var k = 0; k < size; k++) {
  160. array.push(formatter(output.slice(0, padding)));
  161. output = output.slice(padding);
  162. }
  163. result.push(array);
  164. }
  165. else if (types.prefixedType('string')(outs[i].type)) {
  166. dynamicPart = dynamicPart.slice(padding);
  167. result.push(formatter(output.slice(0, padding)));
  168. output = output.slice(padding);
  169. } else {
  170. result.push(formatter(output.slice(0, padding)));
  171. output = output.slice(padding);
  172. }
  173. });
  174. return result;
  175. };
  176. /// @param json abi for contract
  177. /// @returns input parser object for given json abi
  178. /// TODO: refactor creating the parser, do not double logic from contract
  179. var inputParser = function (json) {
  180. var parser = {};
  181. json.forEach(function (method) {
  182. var displayName = utils.extractDisplayName(method.name);
  183. var typeName = utils.extractTypeName(method.name);
  184. var impl = function () {
  185. var params = Array.prototype.slice.call(arguments);
  186. return formatInput(method.inputs, params);
  187. };
  188. if (parser[displayName] === undefined) {
  189. parser[displayName] = impl;
  190. }
  191. parser[displayName][typeName] = impl;
  192. });
  193. return parser;
  194. };
  195. /// @param json abi for contract
  196. /// @returns output parser for given json abi
  197. var outputParser = function (json) {
  198. var parser = {};
  199. json.forEach(function (method) {
  200. var displayName = utils.extractDisplayName(method.name);
  201. var typeName = utils.extractTypeName(method.name);
  202. var impl = function (output) {
  203. return formatOutput(method.outputs, output);
  204. };
  205. if (parser[displayName] === undefined) {
  206. parser[displayName] = impl;
  207. }
  208. parser[displayName][typeName] = impl;
  209. });
  210. return parser;
  211. };
  212. module.exports = {
  213. inputParser: inputParser,
  214. outputParser: outputParser,
  215. formatInput: formatInput,
  216. formatOutput: formatOutput
  217. };
  218. },{"./const":4,"./formatters":5,"./types":6,"./utils":7}],4:[function(require,module,exports){
  219. (function (process){
  220. /*
  221. This file is part of ethereum.js.
  222. ethereum.js is free software: you can redistribute it and/or modify
  223. it under the terms of the GNU Lesser General Public License as published by
  224. the Free Software Foundation, either version 3 of the License, or
  225. (at your option) any later version.
  226. ethereum.js is distributed in the hope that it will be useful,
  227. but WITHOUT ANY WARRANTY; without even the implied warranty of
  228. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  229. GNU Lesser General Public License for more details.
  230. You should have received a copy of the GNU Lesser General Public License
  231. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  232. */
  233. /** @file const.js
  234. * @authors:
  235. * Marek Kotewicz <marek@ethdev.com>
  236. * @date 2015
  237. */
  238. /// required to define ETH_BIGNUMBER_ROUNDING_MODE
  239. if (process.env.NODE_ENV !== 'build') {
  240. var BigNumber = require('bignumber.js'); // jshint ignore:line
  241. }
  242. var ETH_UNITS = [
  243. 'wei',
  244. 'Kwei',
  245. 'Mwei',
  246. 'Gwei',
  247. 'szabo',
  248. 'finney',
  249. 'ether',
  250. 'grand',
  251. 'Mether',
  252. 'Gether',
  253. 'Tether',
  254. 'Pether',
  255. 'Eether',
  256. 'Zether',
  257. 'Yether',
  258. 'Nether',
  259. 'Dether',
  260. 'Vether',
  261. 'Uether'
  262. ];
  263. module.exports = {
  264. ETH_PADDING: 32,
  265. ETH_SIGNATURE_LENGTH: 4,
  266. ETH_UNITS: ETH_UNITS,
  267. ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN },
  268. ETH_POLLING_TIMEOUT: 1000
  269. };
  270. }).call(this,require('_process'))
  271. },{"_process":2,"bignumber.js":8}],5:[function(require,module,exports){
  272. (function (process){
  273. /*
  274. This file is part of ethereum.js.
  275. ethereum.js is free software: you can redistribute it and/or modify
  276. it under the terms of the GNU Lesser General Public License as published by
  277. the Free Software Foundation, either version 3 of the License, or
  278. (at your option) any later version.
  279. ethereum.js is distributed in the hope that it will be useful,
  280. but WITHOUT ANY WARRANTY; without even the implied warranty of
  281. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  282. GNU Lesser General Public License for more details.
  283. You should have received a copy of the GNU Lesser General Public License
  284. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  285. */
  286. /** @file formatters.js
  287. * @authors:
  288. * Marek Kotewicz <marek@ethdev.com>
  289. * @date 2015
  290. */
  291. if (process.env.NODE_ENV !== 'build') {
  292. var BigNumber = require('bignumber.js'); // jshint ignore:line
  293. }
  294. var utils = require('./utils');
  295. var c = require('./const');
  296. /// @param string string to be padded
  297. /// @param number of characters that result string should have
  298. /// @param sign, by default 0
  299. /// @returns right aligned string
  300. var padLeft = function (string, chars, sign) {
  301. return new Array(chars - string.length + 1).join(sign ? sign : "0") + string;
  302. };
  303. /// Formats input value to byte representation of int
  304. /// If value is negative, return it's two's complement
  305. /// If the value is floating point, round it down
  306. /// @returns right-aligned byte representation of int
  307. var formatInputInt = function (value) {
  308. /*jshint maxcomplexity:7 */
  309. var padding = c.ETH_PADDING * 2;
  310. if (value instanceof BigNumber || typeof value === 'number') {
  311. if (typeof value === 'number')
  312. value = new BigNumber(value);
  313. BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
  314. value = value.round();
  315. if (value.lessThan(0))
  316. value = new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(value).plus(1);
  317. value = value.toString(16);
  318. }
  319. else if (value.indexOf('0x') === 0)
  320. value = value.substr(2);
  321. else if (typeof value === 'string')
  322. value = formatInputInt(new BigNumber(value));
  323. else
  324. value = (+value).toString(16);
  325. return padLeft(value, padding);
  326. };
  327. /// Formats input value to byte representation of string
  328. /// @returns left-algined byte representation of string
  329. var formatInputString = function (value) {
  330. return utils.fromAscii(value, c.ETH_PADDING).substr(2);
  331. };
  332. /// Formats input value to byte representation of bool
  333. /// @returns right-aligned byte representation bool
  334. var formatInputBool = function (value) {
  335. return '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');
  336. };
  337. /// Formats input value to byte representation of real
  338. /// Values are multiplied by 2^m and encoded as integers
  339. /// @returns byte representation of real
  340. var formatInputReal = function (value) {
  341. return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
  342. };
  343. /// Check if input value is negative
  344. /// @param value is hex format
  345. /// @returns true if it is negative, otherwise false
  346. var signedIsNegative = function (value) {
  347. return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1';
  348. };
  349. /// Formats input right-aligned input bytes to int
  350. /// @returns right-aligned input bytes formatted to int
  351. var formatOutputInt = function (value) {
  352. value = value || "0";
  353. // check if it's negative number
  354. // it it is, return two's complement
  355. if (signedIsNegative(value)) {
  356. return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1);
  357. }
  358. return new BigNumber(value, 16);
  359. };
  360. /// Formats big right-aligned input bytes to uint
  361. /// @returns right-aligned input bytes formatted to uint
  362. var formatOutputUInt = function (value) {
  363. value = value || "0";
  364. return new BigNumber(value, 16);
  365. };
  366. /// @returns input bytes formatted to real
  367. var formatOutputReal = function (value) {
  368. return formatOutputInt(value).dividedBy(new BigNumber(2).pow(128));
  369. };
  370. /// @returns input bytes formatted to ureal
  371. var formatOutputUReal = function (value) {
  372. return formatOutputUInt(value).dividedBy(new BigNumber(2).pow(128));
  373. };
  374. /// @returns right-aligned input bytes formatted to hex
  375. var formatOutputHash = function (value) {
  376. return "0x" + value;
  377. };
  378. /// @returns right-aligned input bytes formatted to bool
  379. var formatOutputBool = function (value) {
  380. return value === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;
  381. };
  382. /// @returns left-aligned input bytes formatted to ascii string
  383. var formatOutputString = function (value) {
  384. return utils.toAscii(value);
  385. };
  386. /// @returns right-aligned input bytes formatted to address
  387. var formatOutputAddress = function (value) {
  388. return "0x" + value.slice(value.length - 40, value.length);
  389. };
  390. module.exports = {
  391. formatInputInt: formatInputInt,
  392. formatInputString: formatInputString,
  393. formatInputBool: formatInputBool,
  394. formatInputReal: formatInputReal,
  395. formatOutputInt: formatOutputInt,
  396. formatOutputUInt: formatOutputUInt,
  397. formatOutputReal: formatOutputReal,
  398. formatOutputUReal: formatOutputUReal,
  399. formatOutputHash: formatOutputHash,
  400. formatOutputBool: formatOutputBool,
  401. formatOutputString: formatOutputString,
  402. formatOutputAddress: formatOutputAddress
  403. };
  404. }).call(this,require('_process'))
  405. },{"./const":4,"./utils":7,"_process":2,"bignumber.js":8}],6:[function(require,module,exports){
  406. /*
  407. This file is part of ethereum.js.
  408. ethereum.js is free software: you can redistribute it and/or modify
  409. it under the terms of the GNU Lesser General Public License as published by
  410. the Free Software Foundation, either version 3 of the License, or
  411. (at your option) any later version.
  412. ethereum.js is distributed in the hope that it will be useful,
  413. but WITHOUT ANY WARRANTY; without even the implied warranty of
  414. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  415. GNU Lesser General Public License for more details.
  416. You should have received a copy of the GNU Lesser General Public License
  417. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  418. */
  419. /** @file types.js
  420. * @authors:
  421. * Marek Kotewicz <marek@ethdev.com>
  422. * @date 2015
  423. */
  424. var f = require('./formatters');
  425. /// @param expected type prefix (string)
  426. /// @returns function which checks if type has matching prefix. if yes, returns true, otherwise false
  427. var prefixedType = function (prefix) {
  428. return function (type) {
  429. return type.indexOf(prefix) === 0;
  430. };
  431. };
  432. /// @param expected type name (string)
  433. /// @returns function which checks if type is matching expected one. if yes, returns true, otherwise false
  434. var namedType = function (name) {
  435. return function (type) {
  436. return name === type;
  437. };
  438. };
  439. /// Setups input formatters for solidity types
  440. /// @returns an array of input formatters
  441. var inputTypes = function () {
  442. return [
  443. { type: prefixedType('uint'), format: f.formatInputInt },
  444. { type: prefixedType('int'), format: f.formatInputInt },
  445. { type: prefixedType('hash'), format: f.formatInputInt },
  446. { type: prefixedType('string'), format: f.formatInputString },
  447. { type: prefixedType('real'), format: f.formatInputReal },
  448. { type: prefixedType('ureal'), format: f.formatInputReal },
  449. { type: namedType('address'), format: f.formatInputInt },
  450. { type: namedType('bool'), format: f.formatInputBool }
  451. ];
  452. };
  453. /// Setups output formaters for solidity types
  454. /// @returns an array of output formatters
  455. var outputTypes = function () {
  456. return [
  457. { type: prefixedType('uint'), format: f.formatOutputUInt },
  458. { type: prefixedType('int'), format: f.formatOutputInt },
  459. { type: prefixedType('hash'), format: f.formatOutputHash },
  460. { type: prefixedType('string'), format: f.formatOutputString },
  461. { type: prefixedType('real'), format: f.formatOutputReal },
  462. { type: prefixedType('ureal'), format: f.formatOutputUReal },
  463. { type: namedType('address'), format: f.formatOutputAddress },
  464. { type: namedType('bool'), format: f.formatOutputBool }
  465. ];
  466. };
  467. module.exports = {
  468. prefixedType: prefixedType,
  469. namedType: namedType,
  470. inputTypes: inputTypes,
  471. outputTypes: outputTypes
  472. };
  473. },{"./formatters":5}],7:[function(require,module,exports){
  474. /*
  475. This file is part of ethereum.js.
  476. ethereum.js is free software: you can redistribute it and/or modify
  477. it under the terms of the GNU Lesser General Public License as published by
  478. the Free Software Foundation, either version 3 of the License, or
  479. (at your option) any later version.
  480. ethereum.js is distributed in the hope that it will be useful,
  481. but WITHOUT ANY WARRANTY; without even the implied warranty of
  482. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  483. GNU Lesser General Public License for more details.
  484. You should have received a copy of the GNU Lesser General Public License
  485. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  486. */
  487. /** @file utils.js
  488. * @authors:
  489. * Marek Kotewicz <marek@ethdev.com>
  490. * @date 2015
  491. */
  492. var c = require('./const');
  493. /// Finds first index of array element matching pattern
  494. /// @param array
  495. /// @param callback pattern
  496. /// @returns index of element
  497. var findIndex = function (array, callback) {
  498. var end = false;
  499. var i = 0;
  500. for (; i < array.length && !end; i++) {
  501. end = callback(array[i]);
  502. }
  503. return end ? i - 1 : -1;
  504. };
  505. /// @returns ascii string representation of hex value prefixed with 0x
  506. var toAscii = function(hex) {
  507. // Find termination
  508. var str = "";
  509. var i = 0, l = hex.length;
  510. if (hex.substring(0, 2) === '0x') {
  511. i = 2;
  512. }
  513. for (; i < l; i+=2) {
  514. var code = parseInt(hex.substr(i, 2), 16);
  515. if (code === 0) {
  516. break;
  517. }
  518. str += String.fromCharCode(code);
  519. }
  520. return str;
  521. };
  522. var toHex = function(str) {
  523. var hex = "";
  524. for(var i = 0; i < str.length; i++) {
  525. var n = str.charCodeAt(i).toString(16);
  526. hex += n.length < 2 ? '0' + n : n;
  527. }
  528. return hex;
  529. };
  530. /// @returns hex representation (prefixed by 0x) of ascii string
  531. var fromAscii = function(str, pad) {
  532. pad = pad === undefined ? 0 : pad;
  533. var hex = toHex(str);
  534. while (hex.length < pad*2)
  535. hex += "00";
  536. return "0x" + hex;
  537. };
  538. /// @returns display name for function/event eg. multiply(uint256) -> multiply
  539. var extractDisplayName = function (name) {
  540. var length = name.indexOf('(');
  541. return length !== -1 ? name.substr(0, length) : name;
  542. };
  543. /// @returns overloaded part of function/event name
  544. var extractTypeName = function (name) {
  545. /// TODO: make it invulnerable
  546. var length = name.indexOf('(');
  547. return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : "";
  548. };
  549. /// Filters all function from input abi
  550. /// @returns abi array with filtered objects of type 'function'
  551. var filterFunctions = function (json) {
  552. return json.filter(function (current) {
  553. return current.type === 'function';
  554. });
  555. };
  556. /// Filters all events form input abi
  557. /// @returns abi array with filtered objects of type 'event'
  558. var filterEvents = function (json) {
  559. return json.filter(function (current) {
  560. return current.type === 'event';
  561. });
  562. };
  563. /// used to transform value/string to eth string
  564. /// TODO: use BigNumber.js to parse int
  565. /// TODO: add tests for it!
  566. var toEth = function (str) {
  567. /*jshint maxcomplexity:7 */
  568. var val = typeof str === "string" ? str.indexOf('0x') === 0 ? parseInt(str.substr(2), 16) : parseInt(str) : str;
  569. var unit = 0;
  570. var units = c.ETH_UNITS;
  571. while (val > 3000 && unit < units.length - 1)
  572. {
  573. val /= 1000;
  574. unit++;
  575. }
  576. var s = val.toString().length < val.toFixed(2).length ? val.toString() : val.toFixed(2);
  577. var replaceFunction = function($0, $1, $2) {
  578. return $1 + ',' + $2;
  579. };
  580. while (true) {
  581. var o = s;
  582. s = s.replace(/(\d)(\d\d\d[\.\,])/, replaceFunction);
  583. if (o === s)
  584. break;
  585. }
  586. return s + ' ' + units[unit];
  587. };
  588. module.exports = {
  589. findIndex: findIndex,
  590. toAscii: toAscii,
  591. fromAscii: fromAscii,
  592. extractDisplayName: extractDisplayName,
  593. extractTypeName: extractTypeName,
  594. filterFunctions: filterFunctions,
  595. filterEvents: filterEvents,
  596. toEth: toEth
  597. };
  598. },{"./const":4}],8:[function(require,module,exports){
  599. /*! bignumber.js v2.0.3 https://github.com/MikeMcl/bignumber.js/LICENCE */
  600. ;(function (global) {
  601. 'use strict';
  602. /*
  603. bignumber.js v2.0.3
  604. A JavaScript library for arbitrary-precision arithmetic.
  605. https://github.com/MikeMcl/bignumber.js
  606. Copyright (c) 2015 Michael Mclaughlin <M8ch88l@gmail.com>
  607. MIT Expat Licence
  608. */
  609. var BigNumber, crypto, parseNumeric,
  610. isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
  611. mathceil = Math.ceil,
  612. mathfloor = Math.floor,
  613. notBool = ' not a boolean or binary digit',
  614. roundingMode = 'rounding mode',
  615. tooManyDigits = 'number type has more than 15 significant digits',
  616. ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
  617. BASE = 1e14,
  618. LOG_BASE = 14,
  619. MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
  620. // MAX_INT32 = 0x7fffffff, // 2^31 - 1
  621. POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
  622. SQRT_BASE = 1e7,
  623. /*
  624. * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
  625. * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
  626. * exception is thrown (if ERRORS is true).
  627. */
  628. MAX = 1E9; // 0 to MAX_INT32
  629. /*
  630. * Create and return a BigNumber constructor.
  631. */
  632. function another(configObj) {
  633. var div,
  634. // id tracks the caller function, so its name can be included in error messages.
  635. id = 0,
  636. P = BigNumber.prototype,
  637. ONE = new BigNumber(1),
  638. /********************************* EDITABLE DEFAULTS **********************************/
  639. /*
  640. * The default values below must be integers within the inclusive ranges stated.
  641. * The values can also be changed at run-time using BigNumber.config.
  642. */
  643. // The maximum number of decimal places for operations involving division.
  644. DECIMAL_PLACES = 20, // 0 to MAX
  645. /*
  646. * The rounding mode used when rounding to the above decimal places, and when using
  647. * toExponential, toFixed, toFormat and toPrecision, and round (default value).
  648. * UP 0 Away from zero.
  649. * DOWN 1 Towards zero.
  650. * CEIL 2 Towards +Infinity.
  651. * FLOOR 3 Towards -Infinity.
  652. * HALF_UP 4 Towards nearest neighbour. If equidistant, up.
  653. * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
  654. * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
  655. * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
  656. * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
  657. */
  658. ROUNDING_MODE = 4, // 0 to 8
  659. // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
  660. // The exponent value at and beneath which toString returns exponential notation.
  661. // Number type: -7
  662. TO_EXP_NEG = -7, // 0 to -MAX
  663. // The exponent value at and above which toString returns exponential notation.
  664. // Number type: 21
  665. TO_EXP_POS = 21, // 0 to MAX
  666. // RANGE : [MIN_EXP, MAX_EXP]
  667. // The minimum exponent value, beneath which underflow to zero occurs.
  668. // Number type: -324 (5e-324)
  669. MIN_EXP = -1e7, // -1 to -MAX
  670. // The maximum exponent value, above which overflow to Infinity occurs.
  671. // Number type: 308 (1.7976931348623157e+308)
  672. // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
  673. MAX_EXP = 1e7, // 1 to MAX
  674. // Whether BigNumber Errors are ever thrown.
  675. ERRORS = true, // true or false
  676. // Change to intValidatorNoErrors if ERRORS is false.
  677. isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
  678. // Whether to use cryptographically-secure random number generation, if available.
  679. CRYPTO = false, // true or false
  680. /*
  681. * The modulo mode used when calculating the modulus: a mod n.
  682. * The quotient (q = a / n) is calculated according to the corresponding rounding mode.
  683. * The remainder (r) is calculated as: r = a - n * q.
  684. *
  685. * UP 0 The remainder is positive if the dividend is negative, else is negative.
  686. * DOWN 1 The remainder has the same sign as the dividend.
  687. * This modulo mode is commonly known as 'truncated division' and is
  688. * equivalent to (a % n) in JavaScript.
  689. * FLOOR 3 The remainder has the same sign as the divisor (Python %).
  690. * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
  691. * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
  692. * The remainder is always positive.
  693. *
  694. * The truncated division, floored division, Euclidian division and IEEE 754 remainder
  695. * modes are commonly used for the modulus operation.
  696. * Although the other rounding modes can also be used, they may not give useful results.
  697. */
  698. MODULO_MODE = 1, // 0 to 9
  699. // The maximum number of significant digits of the result of the toPower operation.
  700. // If POW_PRECISION is 0, there will be unlimited significant digits.
  701. POW_PRECISION = 100, // 0 to MAX
  702. // The format specification used by the BigNumber.prototype.toFormat method.
  703. FORMAT = {
  704. decimalSeparator: '.',
  705. groupSeparator: ',',
  706. groupSize: 3,
  707. secondaryGroupSize: 0,
  708. fractionGroupSeparator: '\xA0', // non-breaking space
  709. fractionGroupSize: 0
  710. };
  711. /******************************************************************************************/
  712. // CONSTRUCTOR
  713. /*
  714. * The BigNumber constructor and exported function.
  715. * Create and return a new instance of a BigNumber object.
  716. *
  717. * n {number|string|BigNumber} A numeric value.
  718. * [b] {number} The base of n. Integer, 2 to 64 inclusive.
  719. */
  720. function BigNumber( n, b ) {
  721. var c, e, i, num, len, str,
  722. x = this;
  723. // Enable constructor usage without new.
  724. if ( !( x instanceof BigNumber ) ) {
  725. // 'BigNumber() constructor call without new: {n}'
  726. if (ERRORS) raise( 26, 'constructor call without new', n );
  727. return new BigNumber( n, b );
  728. }
  729. // 'new BigNumber() base not an integer: {b}'
  730. // 'new BigNumber() base out of range: {b}'
  731. if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
  732. // Duplicate.
  733. if ( n instanceof BigNumber ) {
  734. x.s = n.s;
  735. x.e = n.e;
  736. x.c = ( n = n.c ) ? n.slice() : n;
  737. id = 0;
  738. return;
  739. }
  740. if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
  741. x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
  742. // Fast path for integers.
  743. if ( n === ~~n ) {
  744. for ( e = 0, i = n; i >= 10; i /= 10, e++ );
  745. x.e = e;
  746. x.c = [n];
  747. id = 0;
  748. return;
  749. }
  750. str = n + '';
  751. } else {
  752. if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
  753. x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
  754. }
  755. } else {
  756. b = b | 0;
  757. str = n + '';
  758. // Ensure return value is rounded to DECIMAL_PLACES as with other bases.
  759. // Allow exponential notation to be used with base 10 argument.
  760. if ( b == 10 ) {
  761. x = new BigNumber( n instanceof BigNumber ? n : str );
  762. return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
  763. }
  764. // Avoid potential interpretation of Infinity and NaN as base 44+ values.
  765. // Any number in exponential form will fail due to the [Ee][+-].
  766. if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
  767. !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
  768. '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
  769. return parseNumeric( x, str, num, b );
  770. }
  771. if (num) {
  772. x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
  773. if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
  774. // 'new BigNumber() number type has more than 15 significant digits: {n}'
  775. raise( id, tooManyDigits, n );
  776. }
  777. // Prevent later check for length on converted number.
  778. num = false;
  779. } else {
  780. x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
  781. }
  782. str = convertBase( str, 10, b, x.s );
  783. }
  784. // Decimal point?
  785. if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
  786. // Exponential form?
  787. if ( ( i = str.search( /e/i ) ) > 0 ) {
  788. // Determine exponent.
  789. if ( e < 0 ) e = i;
  790. e += +str.slice( i + 1 );
  791. str = str.substring( 0, i );
  792. } else if ( e < 0 ) {
  793. // Integer.
  794. e = str.length;
  795. }
  796. // Determine leading zeros.
  797. for ( i = 0; str.charCodeAt(i) === 48; i++ );
  798. // Determine trailing zeros.
  799. for ( len = str.length; str.charCodeAt(--len) === 48; );
  800. str = str.slice( i, len + 1 );
  801. if (str) {
  802. len = str.length;
  803. // Disallow numbers with over 15 significant digits if number type.
  804. // 'new BigNumber() number type has more than 15 significant digits: {n}'
  805. if ( num && ERRORS && len > 15 ) raise( id, tooManyDigits, x.s * n );
  806. e = e - i - 1;
  807. // Overflow?
  808. if ( e > MAX_EXP ) {
  809. // Infinity.
  810. x.c = x.e = null;
  811. // Underflow?
  812. } else if ( e < MIN_EXP ) {
  813. // Zero.
  814. x.c = [ x.e = 0 ];
  815. } else {
  816. x.e = e;
  817. x.c = [];
  818. // Transform base
  819. // e is the base 10 exponent.
  820. // i is where to slice str to get the first element of the coefficient array.
  821. i = ( e + 1 ) % LOG_BASE;
  822. if ( e < 0 ) i += LOG_BASE;
  823. if ( i < len ) {
  824. if (i) x.c.push( +str.slice( 0, i ) );
  825. for ( len -= LOG_BASE; i < len; ) {
  826. x.c.push( +str.slice( i, i += LOG_BASE ) );
  827. }
  828. str = str.slice(i);
  829. i = LOG_BASE - str.length;
  830. } else {
  831. i -= len;
  832. }
  833. for ( ; i--; str += '0' );
  834. x.c.push( +str );
  835. }
  836. } else {
  837. // Zero.
  838. x.c = [ x.e = 0 ];
  839. }
  840. id = 0;
  841. }
  842. // CONSTRUCTOR PROPERTIES
  843. BigNumber.another = another;
  844. BigNumber.ROUND_UP = 0;
  845. BigNumber.ROUND_DOWN = 1;
  846. BigNumber.ROUND_CEIL = 2;
  847. BigNumber.ROUND_FLOOR = 3;
  848. BigNumber.ROUND_HALF_UP = 4;
  849. BigNumber.ROUND_HALF_DOWN = 5;
  850. BigNumber.ROUND_HALF_EVEN = 6;
  851. BigNumber.ROUND_HALF_CEIL = 7;
  852. BigNumber.ROUND_HALF_FLOOR = 8;
  853. BigNumber.EUCLID = 9;
  854. /*
  855. * Configure infrequently-changing library-wide settings.
  856. *
  857. * Accept an object or an argument list, with one or many of the following properties or
  858. * parameters respectively:
  859. *
  860. * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
  861. * ROUNDING_MODE {number} Integer, 0 to 8 inclusive
  862. * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
  863. * [integer -MAX to 0 incl., 0 to MAX incl.]
  864. * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
  865. * [integer -MAX to -1 incl., integer 1 to MAX incl.]
  866. * ERRORS {boolean|number} true, false, 1 or 0
  867. * CRYPTO {boolean|number} true, false, 1 or 0
  868. * MODULO_MODE {number} 0 to 9 inclusive
  869. * POW_PRECISION {number} 0 to MAX inclusive
  870. * FORMAT {object} See BigNumber.prototype.toFormat
  871. * decimalSeparator {string}
  872. * groupSeparator {string}
  873. * groupSize {number}
  874. * secondaryGroupSize {number}
  875. * fractionGroupSeparator {string}
  876. * fractionGroupSize {number}
  877. *
  878. * (The values assigned to the above FORMAT object properties are not checked for validity.)
  879. *
  880. * E.g.
  881. * BigNumber.config(20, 4) is equivalent to
  882. * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
  883. *
  884. * Ignore properties/parameters set to null or undefined.
  885. * Return an object with the properties current values.
  886. */
  887. BigNumber.config = function () {
  888. var v, p,
  889. i = 0,
  890. r = {},
  891. a = arguments,
  892. o = a[0],
  893. has = o && typeof o == 'object'
  894. ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
  895. : function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
  896. // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
  897. // 'config() DECIMAL_PLACES not an integer: {v}'
  898. // 'config() DECIMAL_PLACES out of range: {v}'
  899. if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
  900. DECIMAL_PLACES = v | 0;
  901. }
  902. r[p] = DECIMAL_PLACES;
  903. // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
  904. // 'config() ROUNDING_MODE not an integer: {v}'
  905. // 'config() ROUNDING_MODE out of range: {v}'
  906. if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
  907. ROUNDING_MODE = v | 0;
  908. }
  909. r[p] = ROUNDING_MODE;
  910. // EXPONENTIAL_AT {number|number[]}
  911. // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
  912. // 'config() EXPONENTIAL_AT not an integer: {v}'
  913. // 'config() EXPONENTIAL_AT out of range: {v}'
  914. if ( has( p = 'EXPONENTIAL_AT' ) ) {
  915. if ( isArray(v) ) {
  916. if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
  917. TO_EXP_NEG = v[0] | 0;
  918. TO_EXP_POS = v[1] | 0;
  919. }
  920. } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
  921. TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
  922. }
  923. }
  924. r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
  925. // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
  926. // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
  927. // 'config() RANGE not an integer: {v}'
  928. // 'config() RANGE cannot be zero: {v}'
  929. // 'config() RANGE out of range: {v}'
  930. if ( has( p = 'RANGE' ) ) {
  931. if ( isArray(v) ) {
  932. if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
  933. MIN_EXP = v[0] | 0;
  934. MAX_EXP = v[1] | 0;
  935. }
  936. } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
  937. if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
  938. else if (ERRORS) raise( 2, p + ' cannot be zero', v );
  939. }
  940. }
  941. r[p] = [ MIN_EXP, MAX_EXP ];
  942. // ERRORS {boolean|number} true, false, 1 or 0.
  943. // 'config() ERRORS not a boolean or binary digit: {v}'
  944. if ( has( p = 'ERRORS' ) ) {
  945. if ( v === !!v || v === 1 || v === 0 ) {
  946. id = 0;
  947. isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
  948. } else if (ERRORS) {
  949. raise( 2, p + notBool, v );
  950. }
  951. }
  952. r[p] = ERRORS;
  953. // CRYPTO {boolean|number} true, false, 1 or 0.
  954. // 'config() CRYPTO not a boolean or binary digit: {v}'
  955. // 'config() crypto unavailable: {crypto}'
  956. if ( has( p = 'CRYPTO' ) ) {
  957. if ( v === !!v || v === 1 || v === 0 ) {
  958. CRYPTO = !!( v && crypto && typeof crypto == 'object' );
  959. if ( v && !CRYPTO && ERRORS ) raise( 2, 'crypto unavailable', crypto );
  960. } else if (ERRORS) {
  961. raise( 2, p + notBool, v );
  962. }
  963. }
  964. r[p] = CRYPTO;
  965. // MODULO_MODE {number} Integer, 0 to 9 inclusive.
  966. // 'config() MODULO_MODE not an integer: {v}'
  967. // 'config() MODULO_MODE out of range: {v}'
  968. if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
  969. MODULO_MODE = v | 0;
  970. }
  971. r[p] = MODULO_MODE;
  972. // POW_PRECISION {number} Integer, 0 to MAX inclusive.
  973. // 'config() POW_PRECISION not an integer: {v}'
  974. // 'config() POW_PRECISION out of range: {v}'
  975. if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
  976. POW_PRECISION = v | 0;
  977. }
  978. r[p] = POW_PRECISION;
  979. // FORMAT {object}
  980. // 'config() FORMAT not an object: {v}'
  981. if ( has( p = 'FORMAT' ) ) {
  982. if ( typeof v == 'object' ) {
  983. FORMAT = v;
  984. } else if (ERRORS) {
  985. raise( 2, p + ' not an object', v );
  986. }
  987. }
  988. r[p] = FORMAT;
  989. return r;
  990. };
  991. /*
  992. * Return a new BigNumber whose value is the maximum of the arguments.
  993. *
  994. * arguments {number|string|BigNumber}
  995. */
  996. BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
  997. /*
  998. * Return a new BigNumber whose value is the minimum of the arguments.
  999. *
  1000. * arguments {number|string|BigNumber}
  1001. */
  1002. BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
  1003. /*
  1004. * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
  1005. * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
  1006. * zeros are produced).
  1007. *
  1008. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  1009. *
  1010. * 'random() decimal places not an integer: {dp}'
  1011. * 'random() decimal places out of range: {dp}'
  1012. * 'random() crypto unavailable: {crypto}'
  1013. */
  1014. BigNumber.random = (function () {
  1015. var pow2_53 = 0x20000000000000;
  1016. // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
  1017. // Check if Math.random() produces more than 32 bits of randomness.
  1018. // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
  1019. // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
  1020. var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
  1021. ? function () { return mathfloor( Math.random() * pow2_53 ); }
  1022. : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
  1023. (Math.random() * 0x800000 | 0); };
  1024. return function (dp) {
  1025. var a, b, e, k, v,
  1026. i = 0,
  1027. c = [],
  1028. rand = new BigNumber(ONE);
  1029. dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
  1030. k = mathceil( dp / LOG_BASE );
  1031. if (CRYPTO) {
  1032. // Browsers supporting crypto.getRandomValues.
  1033. if ( crypto && crypto.getRandomValues ) {
  1034. a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
  1035. for ( ; i < k; ) {
  1036. // 53 bits:
  1037. // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
  1038. // 11111 11111111 11111111 11111111 11100000 00000000 00000000
  1039. // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
  1040. // 11111 11111111 11111111
  1041. // 0x20000 is 2^21.
  1042. v = a[i] * 0x20000 + (a[i + 1] >>> 11);
  1043. // Rejection sampling:
  1044. // 0 <= v < 9007199254740992
  1045. // Probability that v >= 9e15, is
  1046. // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
  1047. if ( v >= 9e15 ) {
  1048. b = crypto.getRandomValues( new Uint32Array(2) );
  1049. a[i] = b[0];
  1050. a[i + 1] = b[1];
  1051. } else {
  1052. // 0 <= v <= 8999999999999999
  1053. // 0 <= (v % 1e14) <= 99999999999999
  1054. c.push( v % 1e14 );
  1055. i += 2;
  1056. }
  1057. }
  1058. i = k / 2;
  1059. // Node.js supporting crypto.randomBytes.
  1060. } else if ( crypto && crypto.randomBytes ) {
  1061. // buffer
  1062. a = crypto.randomBytes( k *= 7 );
  1063. for ( ; i < k; ) {
  1064. // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
  1065. // 0x100000000 is 2^32, 0x1000000 is 2^24
  1066. // 11111 11111111 11111111 11111111 11111111 11111111 11111111
  1067. // 0 <= v < 9007199254740992
  1068. v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
  1069. ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
  1070. ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
  1071. if ( v >= 9e15 ) {
  1072. crypto.randomBytes(7).copy( a, i );
  1073. } else {
  1074. // 0 <= (v % 1e14) <= 99999999999999
  1075. c.push( v % 1e14 );
  1076. i += 7;
  1077. }
  1078. }
  1079. i = k / 7;
  1080. } else if (ERRORS) {
  1081. raise( 14, 'crypto unavailable', crypto );
  1082. }
  1083. }
  1084. // Use Math.random: CRYPTO is false or crypto is unavailable and ERRORS is false.
  1085. if (!i) {
  1086. for ( ; i < k; ) {
  1087. v = random53bitInt();
  1088. if ( v < 9e15 ) c[i++] = v % 1e14;
  1089. }
  1090. }
  1091. k = c[--i];
  1092. dp %= LOG_BASE;
  1093. // Convert trailing digits to zeros according to dp.
  1094. if ( k && dp ) {
  1095. v = POWS_TEN[LOG_BASE - dp];
  1096. c[i] = mathfloor( k / v ) * v;
  1097. }
  1098. // Remove trailing elements which are zero.
  1099. for ( ; c[i] === 0; c.pop(), i-- );
  1100. // Zero?
  1101. if ( i < 0 ) {
  1102. c = [ e = 0 ];
  1103. } else {
  1104. // Remove leading elements which are zero and adjust exponent accordingly.
  1105. for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE);
  1106. // Count the digits of the first element of c to determine leading zeros, and...
  1107. for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
  1108. // adjust the exponent accordingly.
  1109. if ( i < LOG_BASE ) e -= LOG_BASE - i;
  1110. }
  1111. rand.e = e;
  1112. rand.c = c;
  1113. return rand;
  1114. };
  1115. })();
  1116. // PRIVATE FUNCTIONS
  1117. // Convert a numeric string of baseIn to a numeric string of baseOut.
  1118. function convertBase( str, baseOut, baseIn, sign ) {
  1119. var d, e, k, r, x, xc, y,
  1120. i = str.indexOf( '.' ),
  1121. dp = DECIMAL_PLACES,
  1122. rm = ROUNDING_MODE;
  1123. if ( baseIn < 37 ) str = str.toLowerCase();
  1124. // Non-integer.
  1125. if ( i >= 0 ) {
  1126. k = POW_PRECISION;
  1127. // Unlimited precision.
  1128. POW_PRECISION = 0;
  1129. str = str.replace( '.', '' );
  1130. y = new BigNumber(baseIn);
  1131. x = y.pow( str.length - i );
  1132. POW_PRECISION = k;
  1133. // Convert str as if an integer, then restore the fraction part by dividing the
  1134. // result by its base raised to a power.
  1135. y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
  1136. y.e = y.c.length;
  1137. }
  1138. // Convert the number as integer.
  1139. xc = toBaseOut( str, baseIn, baseOut );
  1140. e = k = xc.length;
  1141. // Remove trailing zeros.
  1142. for ( ; xc[--k] == 0; xc.pop() );
  1143. if ( !xc[0] ) return '0';
  1144. if ( i < 0 ) {
  1145. --e;
  1146. } else {
  1147. x.c = xc;
  1148. x.e = e;
  1149. // sign is needed for correct rounding.
  1150. x.s = sign;
  1151. x = div( x, y, dp, rm, baseOut );
  1152. xc = x.c;
  1153. r = x.r;
  1154. e = x.e;
  1155. }
  1156. d = e + dp + 1;
  1157. // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
  1158. i = xc[d];
  1159. k = baseOut / 2;
  1160. r = r || d < 0 || xc[d + 1] != null;
  1161. r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
  1162. : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
  1163. rm == ( x.s < 0 ? 8 : 7 ) );
  1164. if ( d < 1 || !xc[0] ) {
  1165. // 1^-dp or 0.
  1166. str = r ? toFixedPoint( '1', -dp ) : '0';
  1167. } else {
  1168. xc.length = d;
  1169. if (r) {
  1170. // Rounding up may mean the previous digit has to be rounded up and so on.
  1171. for ( --baseOut; ++xc[--d] > baseOut; ) {
  1172. xc[d] = 0;
  1173. if ( !d ) {
  1174. ++e;
  1175. xc.unshift(1);
  1176. }
  1177. }
  1178. }
  1179. // Determine trailing zeros.
  1180. for ( k = xc.length; !xc[--k]; );
  1181. // E.g. [4, 11, 15] becomes 4bf.
  1182. for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
  1183. str = toFixedPoint( str, e );
  1184. }
  1185. // The caller will add the sign.
  1186. return str;
  1187. }
  1188. // Perform division in the specified base. Called by div and convertBase.
  1189. div = (function () {
  1190. // Assume non-zero x and k.
  1191. function multiply( x, k, base ) {
  1192. var m, temp, xlo, xhi,
  1193. carry = 0,
  1194. i = x.length,
  1195. klo = k % SQRT_BASE,
  1196. khi = k / SQRT_BASE | 0;
  1197. for ( x = x.slice(); i--; ) {
  1198. xlo = x[i] % SQRT_BASE;
  1199. xhi = x[i] / SQRT_BASE | 0;
  1200. m = khi * xlo + xhi * klo;
  1201. temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
  1202. carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
  1203. x[i] = temp % base;
  1204. }
  1205. if (carry) x.unshift(carry);
  1206. return x;
  1207. }
  1208. function compare( a, b, aL, bL ) {
  1209. var i, cmp;
  1210. if ( aL != bL ) {
  1211. cmp = aL > bL ? 1 : -1;
  1212. } else {
  1213. for ( i = cmp = 0; i < aL; i++ ) {
  1214. if ( a[i] != b[i] ) {
  1215. cmp = a[i] > b[i] ? 1 : -1;
  1216. break;
  1217. }
  1218. }
  1219. }
  1220. return cmp;
  1221. }
  1222. function subtract( a, b, aL, base ) {
  1223. var i = 0;
  1224. // Subtract b from a.
  1225. for ( ; aL--; ) {
  1226. a[aL] -= i;
  1227. i = a[aL] < b[aL] ? 1 : 0;
  1228. a[aL] = i * base + a[aL] - b[aL];
  1229. }
  1230. // Remove leading zeros.
  1231. for ( ; !a[0] && a.length > 1; a.shift() );
  1232. }
  1233. // x: dividend, y: divisor.
  1234. return function ( x, y, dp, rm, base ) {
  1235. var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
  1236. yL, yz,
  1237. s = x.s == y.s ? 1 : -1,
  1238. xc = x.c,
  1239. yc = y.c;
  1240. // Either NaN, Infinity or 0?
  1241. if ( !xc || !xc[0] || !yc || !yc[0] ) {
  1242. return new BigNumber(
  1243. // Return NaN if either NaN, or both Infinity or 0.
  1244. !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
  1245. // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
  1246. xc && xc[0] == 0 || !yc ? s * 0 : s / 0
  1247. );
  1248. }
  1249. q = new BigNumber(s);
  1250. qc = q.c = [];
  1251. e = x.e - y.e;
  1252. s = dp + e + 1;
  1253. if ( !base ) {
  1254. base = BASE;
  1255. e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
  1256. s = s / LOG_BASE | 0;
  1257. }
  1258. // Result exponent may be one less then the current value of e.
  1259. // The coefficients of the BigNumbers from convertBase may have trailing zeros.
  1260. for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
  1261. if ( yc[i] > ( xc[i] || 0 ) ) e--;
  1262. if ( s < 0 ) {
  1263. qc.push(1);
  1264. more = true;
  1265. } else {
  1266. xL = xc.length;
  1267. yL = yc.length;
  1268. i = 0;
  1269. s += 2;
  1270. // Normalise xc and yc so highest order digit of yc is >= base/2
  1271. n = mathfloor( base / ( yc[0] + 1 ) );
  1272. if ( n > 1 ) {
  1273. yc = multiply( yc, n, base );
  1274. xc = multiply( xc, n, base );
  1275. yL = yc.length;
  1276. xL = xc.length;
  1277. }
  1278. xi = yL;
  1279. rem = xc.slice( 0, yL );
  1280. remL = rem.length;
  1281. // Add zeros to make remainder as long as divisor.
  1282. for ( ; remL < yL; rem[remL++] = 0 );
  1283. yz = yc.slice();
  1284. yz.unshift(0);
  1285. yc0 = yc[0];
  1286. if ( yc[1] >= base / 2 ) yc0++;
  1287. do {
  1288. n = 0;
  1289. // Compare divisor and remainder.
  1290. cmp = compare( yc, rem, yL, remL );
  1291. // If divisor < remainder.
  1292. if ( cmp < 0 ) {
  1293. // Calculate trial digit, n.
  1294. rem0 = rem[0];
  1295. if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
  1296. // n is how many times the divisor goes into the current remainder.
  1297. n = mathfloor( rem0 / yc0 );
  1298. // Algorithm:
  1299. // 1. product = divisor * trial digit (n)
  1300. // 2. if product > remainder: product -= divisor, n--
  1301. // 3. remainder -= product
  1302. // 4. if product was < remainder at 2:
  1303. // 5. compare new remainder and divisor
  1304. // 6. If remainder > divisor: remainder -= divisor, n++
  1305. if ( n > 1 ) {
  1306. if ( n >= base ) n = base - 1;
  1307. // product = divisor * trial digit.
  1308. prod = multiply( yc, n, base );
  1309. prodL = prod.length;
  1310. remL = rem.length;
  1311. // Compare product and remainder.
  1312. cmp = compare( prod, rem, prodL, remL );
  1313. // product > remainder.
  1314. if ( cmp == 1 ) {
  1315. n--;
  1316. // Subtract divisor from product.
  1317. subtract( prod, yL < prodL ? yz : yc, prodL, base );
  1318. }
  1319. } else {
  1320. // cmp is -1.
  1321. // If n is 0, there is no need to compare yc and rem again
  1322. // below, so change cmp to 1 to avoid it.
  1323. // If n is 1, compare yc and rem again below.
  1324. if ( n == 0 ) cmp = n = 1;
  1325. prod = yc.slice();
  1326. }
  1327. prodL = prod.length;
  1328. if ( prodL < remL ) prod.unshift(0);
  1329. // Subtract product from remainder.
  1330. subtract( rem, prod, remL, base );
  1331. // If product was < previous remainder.
  1332. if ( cmp == -1 ) {
  1333. remL = rem.length;
  1334. // Compare divisor and new remainder.
  1335. cmp = compare( yc, rem, yL, remL );
  1336. // If divisor < new remainder, subtract divisor from remainder.
  1337. if ( cmp < 1 ) {
  1338. n++;
  1339. // Subtract divisor from remainder.
  1340. subtract( rem, yL < remL ? yz : yc, remL, base );
  1341. }
  1342. }
  1343. remL = rem.length;
  1344. } else if ( cmp === 0 ) {
  1345. n++;
  1346. rem = [0];
  1347. }
  1348. // if cmp === 1, n will be 0
  1349. // Add the next digit, n, to the result array.
  1350. qc[i++] = n;
  1351. // Update the remainder.
  1352. if ( cmp && rem[0] ) {
  1353. rem[remL++] = xc[xi] || 0;
  1354. } else {
  1355. rem = [ xc[xi] ];
  1356. remL = 1;
  1357. }
  1358. } while ( ( xi++ < xL || rem[0] != null ) && s-- );
  1359. more = rem[0] != null;
  1360. // Leading zero?
  1361. if ( !qc[0] ) qc.shift();
  1362. }
  1363. if ( base == BASE ) {
  1364. // To calculate q.e, first get the number of digits of qc[0].
  1365. for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
  1366. round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
  1367. // Caller is convertBase.
  1368. } else {
  1369. q.e = e;
  1370. q.r = +more;
  1371. }
  1372. return q;
  1373. };
  1374. })();
  1375. /*
  1376. * Return a string representing the value of BigNumber n in fixed-point or exponential
  1377. * notation rounded to the specified decimal places or significant digits.
  1378. *
  1379. * n is a BigNumber.
  1380. * i is the index of the last digit required (i.e. the digit that may be rounded up).
  1381. * rm is the rounding mode.
  1382. * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
  1383. */
  1384. function format( n, i, rm, caller ) {
  1385. var c0, e, ne, len, str;
  1386. rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
  1387. ? rm | 0 : ROUNDING_MODE;
  1388. if ( !n.c ) return n.toString();
  1389. c0 = n.c[0];
  1390. ne = n.e;
  1391. if ( i == null ) {
  1392. str = coeffToString( n.c );
  1393. str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
  1394. ? toExponential( str, ne )
  1395. : toFixedPoint( str, ne );
  1396. } else {
  1397. n = round( new BigNumber(n), i, rm );
  1398. // n.e may have changed if the value was rounded up.
  1399. e = n.e;
  1400. str = coeffToString( n.c );
  1401. len = str.length;
  1402. // toPrecision returns exponential notation if the number of significant digits
  1403. // specified is less than the number of digits necessary to represent the integer
  1404. // part of the value in fixed-point notation.
  1405. // Exponential notation.
  1406. if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
  1407. // Append zeros?
  1408. for ( ; len < i; str += '0', len++ );
  1409. str = toExponential( str, e );
  1410. // Fixed-point notation.
  1411. } else {
  1412. i -= ne;
  1413. str = toFixedPoint( str, e );
  1414. // Append zeros?
  1415. if ( e + 1 > len ) {
  1416. if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
  1417. } else {
  1418. i += e - len;
  1419. if ( i > 0 ) {
  1420. if ( e + 1 == len ) str += '.';
  1421. for ( ; i--; str += '0' );
  1422. }
  1423. }
  1424. }
  1425. }
  1426. return n.s < 0 && c0 ? '-' + str : str;
  1427. }
  1428. // Handle BigNumber.max and BigNumber.min.
  1429. function maxOrMin( args, method ) {
  1430. var m, n,
  1431. i = 0;
  1432. if ( isArray( args[0] ) ) args = args[0];
  1433. m = new BigNumber( args[0] );
  1434. for ( ; ++i < args.length; ) {
  1435. n = new BigNumber( args[i] );
  1436. // If any number is NaN, return NaN.
  1437. if ( !n.s ) {
  1438. m = n;
  1439. break;
  1440. } else if ( method.call( m, n ) ) {
  1441. m = n;
  1442. }
  1443. }
  1444. return m;
  1445. }
  1446. /*
  1447. * Return true if n is an integer in range, otherwise throw.
  1448. * Use for argument validation when ERRORS is true.
  1449. */
  1450. function intValidatorWithErrors( n, min, max, caller, name ) {
  1451. if ( n < min || n > max || n != truncate(n) ) {
  1452. raise( caller, ( name || 'decimal places' ) +
  1453. ( n < min || n > max ? ' out of range' : ' not an integer' ), n );
  1454. }
  1455. return true;
  1456. }
  1457. /*
  1458. * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
  1459. * Called by minus, plus and times.
  1460. */
  1461. function normalise( n, c, e ) {
  1462. var i = 1,
  1463. j = c.length;
  1464. // Remove trailing zeros.
  1465. for ( ; !c[--j]; c.pop() );
  1466. // Calculate the base 10 exponent. First get the number of digits of c[0].
  1467. for ( j = c[0]; j >= 10; j /= 10, i++ );
  1468. // Overflow?
  1469. if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
  1470. // Infinity.
  1471. n.c = n.e = null;
  1472. // Underflow?
  1473. } else if ( e < MIN_EXP ) {
  1474. // Zero.
  1475. n.c = [ n.e = 0 ];
  1476. } else {
  1477. n.e = e;
  1478. n.c = c;
  1479. }
  1480. return n;
  1481. }
  1482. // Handle values that fail the validity test in BigNumber.
  1483. parseNumeric = (function () {
  1484. // var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
  1485. var basePrefix = /^(-?)0([xbo])/i,
  1486. dotAfter = /^([^.]+)\.$/,
  1487. dotBefore = /^\.([^.]+)$/,
  1488. isInfinityOrNaN = /^-?(Infinity|NaN)$/,
  1489. // whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
  1490. whitespaceOrPlus = /^\s*\+[\w.]|^\s+|\s+$/g;
  1491. return function ( x, str, num, b ) {
  1492. var base,
  1493. s = num ? str : str.replace( whitespaceOrPlus, '' );
  1494. // No exception on ±Infinity or NaN.
  1495. if ( isInfinityOrNaN.test(s) ) {
  1496. x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
  1497. } else {
  1498. if ( !num ) {
  1499. // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
  1500. s = s.replace( basePrefix, function ( m, p1, p2 ) {
  1501. base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
  1502. return !b || b == base ? p1 : m;
  1503. });
  1504. if (b) {
  1505. base = b;
  1506. // E.g. '1.' to '1', '.1' to '0.1'
  1507. s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
  1508. }
  1509. if ( str != s ) return new BigNumber( s, base );
  1510. }
  1511. // 'new BigNumber() not a number: {n}'
  1512. // 'new BigNumber() not a base {b} number: {n}'
  1513. if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
  1514. x.s = null;
  1515. }
  1516. x.c = x.e = null;
  1517. id = 0;
  1518. }
  1519. })();
  1520. // Throw a BigNumber Error.
  1521. function raise( caller, msg, val ) {
  1522. var error = new Error( [
  1523. 'new BigNumber', // 0
  1524. 'cmp', // 1
  1525. 'config', // 2
  1526. 'div', // 3
  1527. 'divToInt', // 4
  1528. 'eq', // 5
  1529. 'gt', // 6
  1530. 'gte', // 7
  1531. 'lt', // 8
  1532. 'lte', // 9
  1533. 'minus', // 10
  1534. 'mod', // 11
  1535. 'plus', // 12
  1536. 'precision', // 13
  1537. 'random', // 14
  1538. 'round', // 15
  1539. 'shift', // 16
  1540. 'times', // 17
  1541. 'toDigits', // 18
  1542. 'toExponential', // 19
  1543. 'toFixed', // 20
  1544. 'toFormat', // 21
  1545. 'toFraction', // 22
  1546. 'pow', // 23
  1547. 'toPrecision', // 24
  1548. 'toString', // 25
  1549. 'BigNumber' // 26
  1550. ][caller] + '() ' + msg + ': ' + val );
  1551. error.name = 'BigNumber Error';
  1552. id = 0;
  1553. throw error;
  1554. }
  1555. /*
  1556. * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
  1557. * If r is truthy, it is known that there are more digits after the rounding digit.
  1558. */
  1559. function round( x, sd, rm, r ) {
  1560. var d, i, j, k, n, ni, rd,
  1561. xc = x.c,
  1562. pows10 = POWS_TEN;
  1563. // if x is not Infinity or NaN...
  1564. if (xc) {
  1565. // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
  1566. // n is a base 1e14 number, the value of the element of array x.c containing rd.
  1567. // ni is the index of n within x.c.
  1568. // d is the number of digits of n.
  1569. // i is the index of rd within n including leading zeros.
  1570. // j is the actual index of rd within n (if < 0, rd is a leading zero).
  1571. out: {
  1572. // Get the number of digits of the first element of xc.
  1573. for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
  1574. i = sd - d;
  1575. // If the rounding digit is in the first element of xc...
  1576. if ( i < 0 ) {
  1577. i += LOG_BASE;
  1578. j = sd;
  1579. n = xc[ ni = 0 ];
  1580. // Get the rounding digit at index j of n.
  1581. rd = n / pows10[ d - j - 1 ] % 10 | 0;
  1582. } else {
  1583. ni = mathceil( ( i + 1 ) / LOG_BASE );
  1584. if ( ni >= xc.length ) {
  1585. if (r) {
  1586. // Needed by sqrt.
  1587. for ( ; xc.length <= ni; xc.push(0) );
  1588. n = rd = 0;
  1589. d = 1;
  1590. i %= LOG_BASE;
  1591. j = i - LOG_BASE + 1;
  1592. } else {
  1593. break out;
  1594. }
  1595. } else {
  1596. n = k = xc[ni];
  1597. // Get the number of digits of n.
  1598. for ( d = 1; k >= 10; k /= 10, d++ );
  1599. // Get the index of rd within n.
  1600. i %= LOG_BASE;
  1601. // Get the index of rd within n, adjusted for leading zeros.
  1602. // The number of leading zeros of n is given by LOG_BASE - d.
  1603. j = i - LOG_BASE + d;
  1604. // Get the rounding digit at index j of n.
  1605. rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
  1606. }
  1607. }
  1608. r = r || sd < 0 ||
  1609. // Are there any non-zero digits after the rounding digit?
  1610. // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
  1611. // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
  1612. xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
  1613. r = rm < 4
  1614. ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
  1615. : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
  1616. // Check whether the digit to the left of the rounding digit is odd.
  1617. ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
  1618. rm == ( x.s < 0 ? 8 : 7 ) );
  1619. if ( sd < 1 || !xc[0] ) {
  1620. xc.length = 0;
  1621. if (r) {
  1622. // Convert sd to decimal places.
  1623. sd -= x.e + 1;
  1624. // 1, 0.1, 0.01, 0.001, 0.0001 etc.
  1625. xc[0] = pows10[ sd % LOG_BASE ];
  1626. x.e = -sd || 0;
  1627. } else {
  1628. // Zero.
  1629. xc[0] = x.e = 0;
  1630. }
  1631. return x;
  1632. }
  1633. // Remove excess digits.
  1634. if ( i == 0 ) {
  1635. xc.length = ni;
  1636. k = 1;
  1637. ni--;
  1638. } else {
  1639. xc.length = ni + 1;
  1640. k = pows10[ LOG_BASE - i ];
  1641. // E.g. 56700 becomes 56000 if 7 is the rounding digit.
  1642. // j > 0 means i > number of leading zeros of n.
  1643. xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
  1644. }
  1645. // Round up?
  1646. if (r) {
  1647. for ( ; ; ) {
  1648. // If the digit to be rounded up is in the first element of xc...
  1649. if ( ni == 0 ) {
  1650. // i will be the length of xc[0] before k is added.
  1651. for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
  1652. j = xc[0] += k;
  1653. for ( k = 1; j >= 10; j /= 10, k++ );
  1654. // if i != k the length has increased.
  1655. if ( i != k ) {
  1656. x.e++;
  1657. if ( xc[0] == BASE ) xc[0] = 1;
  1658. }
  1659. break;
  1660. } else {
  1661. xc[ni] += k;
  1662. if ( xc[ni] != BASE ) break;
  1663. xc[ni--] = 0;
  1664. k = 1;
  1665. }
  1666. }
  1667. }
  1668. // Remove trailing zeros.
  1669. for ( i = xc.length; xc[--i] === 0; xc.pop() );
  1670. }
  1671. // Overflow? Infinity.
  1672. if ( x.e > MAX_EXP ) {
  1673. x.c = x.e = null;
  1674. // Underflow? Zero.
  1675. } else if ( x.e < MIN_EXP ) {
  1676. x.c = [ x.e = 0 ];
  1677. }
  1678. }
  1679. return x;
  1680. }
  1681. // PROTOTYPE/INSTANCE METHODS
  1682. /*
  1683. * Return a new BigNumber whose value is the absolute value of this BigNumber.
  1684. */
  1685. P.absoluteValue = P.abs = function () {
  1686. var x = new BigNumber(this);
  1687. if ( x.s < 0 ) x.s = 1;
  1688. return x;
  1689. };
  1690. /*
  1691. * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
  1692. * number in the direction of Infinity.
  1693. */
  1694. P.ceil = function () {
  1695. return round( new BigNumber(this), this.e + 1, 2 );
  1696. };
  1697. /*
  1698. * Return
  1699. * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
  1700. * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
  1701. * 0 if they have the same value,
  1702. * or null if the value of either is NaN.
  1703. */
  1704. P.comparedTo = P.cmp = function ( y, b ) {
  1705. id = 1;
  1706. return compare( this, new BigNumber( y, b ) );
  1707. };
  1708. /*
  1709. * Return the number of decimal places of the value of this BigNumber, or null if the value
  1710. * of this BigNumber is ±Infinity or NaN.
  1711. */
  1712. P.decimalPlaces = P.dp = function () {
  1713. var n, v,
  1714. c = this.c;
  1715. if ( !c ) return null;
  1716. n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
  1717. // Subtract the number of trailing zeros of the last number.
  1718. if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
  1719. if ( n < 0 ) n = 0;
  1720. return n;
  1721. };
  1722. /*
  1723. * n / 0 = I
  1724. * n / N = N
  1725. * n / I = 0
  1726. * 0 / n = 0
  1727. * 0 / 0 = N
  1728. * 0 / N = N
  1729. * 0 / I = 0
  1730. * N / n = N
  1731. * N / 0 = N
  1732. * N / N = N
  1733. * N / I = N
  1734. * I / n = I
  1735. * I / 0 = I
  1736. * I / N = N
  1737. * I / I = N
  1738. *
  1739. * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
  1740. * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
  1741. */
  1742. P.dividedBy = P.div = function ( y, b ) {
  1743. id = 3;
  1744. return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
  1745. };
  1746. /*
  1747. * Return a new BigNumber whose value is the integer part of dividing the value of this
  1748. * BigNumber by the value of BigNumber(y, b).
  1749. */
  1750. P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
  1751. id = 4;
  1752. return div( this, new BigNumber( y, b ), 0, 1 );
  1753. };
  1754. /*
  1755. * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
  1756. * otherwise returns false.
  1757. */
  1758. P.equals = P.eq = function ( y, b ) {
  1759. id = 5;
  1760. return compare( this, new BigNumber( y, b ) ) === 0;
  1761. };
  1762. /*
  1763. * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
  1764. * number in the direction of -Infinity.
  1765. */
  1766. P.floor = function () {
  1767. return round( new BigNumber(this), this.e + 1, 3 );
  1768. };
  1769. /*
  1770. * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
  1771. * otherwise returns false.
  1772. */
  1773. P.greaterThan = P.gt = function ( y, b ) {
  1774. id = 6;
  1775. return compare( this, new BigNumber( y, b ) ) > 0;
  1776. };
  1777. /*
  1778. * Return true if the value of this BigNumber is greater than or equal to the value of
  1779. * BigNumber(y, b), otherwise returns false.
  1780. */
  1781. P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
  1782. id = 7;
  1783. return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
  1784. };
  1785. /*
  1786. * Return true if the value of this BigNumber is a finite number, otherwise returns false.
  1787. */
  1788. P.isFinite = function () {
  1789. return !!this.c;
  1790. };
  1791. /*
  1792. * Return true if the value of this BigNumber is an integer, otherwise return false.
  1793. */
  1794. P.isInteger = P.isInt = function () {
  1795. return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
  1796. };
  1797. /*
  1798. * Return true if the value of this BigNumber is NaN, otherwise returns false.
  1799. */
  1800. P.isNaN = function () {
  1801. return !this.s;
  1802. };
  1803. /*
  1804. * Return true if the value of this BigNumber is negative, otherwise returns false.
  1805. */
  1806. P.isNegative = P.isNeg = function () {
  1807. return this.s < 0;
  1808. };
  1809. /*
  1810. * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
  1811. */
  1812. P.isZero = function () {
  1813. return !!this.c && this.c[0] == 0;
  1814. };
  1815. /*
  1816. * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
  1817. * otherwise returns false.
  1818. */
  1819. P.lessThan = P.lt = function ( y, b ) {
  1820. id = 8;
  1821. return compare( this, new BigNumber( y, b ) ) < 0;
  1822. };
  1823. /*
  1824. * Return true if the value of this BigNumber is less than or equal to the value of
  1825. * BigNumber(y, b), otherwise returns false.
  1826. */
  1827. P.lessThanOrEqualTo = P.lte = function ( y, b ) {
  1828. id = 9;
  1829. return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
  1830. };
  1831. /*
  1832. * n - 0 = n
  1833. * n - N = N
  1834. * n - I = -I
  1835. * 0 - n = -n
  1836. * 0 - 0 = 0
  1837. * 0 - N = N
  1838. * 0 - I = -I
  1839. * N - n = N
  1840. * N - 0 = N
  1841. * N - N = N
  1842. * N - I = N
  1843. * I - n = I
  1844. * I - 0 = I
  1845. * I - N = N
  1846. * I - I = N
  1847. *
  1848. * Return a new BigNumber whose value is the value of this BigNumber minus the value of
  1849. * BigNumber(y, b).
  1850. */
  1851. P.minus = P.sub = function ( y, b ) {
  1852. var i, j, t, xLTy,
  1853. x = this,
  1854. a = x.s;
  1855. id = 10;
  1856. y = new BigNumber( y, b );
  1857. b = y.s;
  1858. // Either NaN?
  1859. if ( !a || !b ) return new BigNumber(NaN);
  1860. // Signs differ?
  1861. if ( a != b ) {
  1862. y.s = -b;
  1863. return x.plus(y);
  1864. }
  1865. var xe = x.e / LOG_BASE,
  1866. ye = y.e / LOG_BASE,
  1867. xc = x.c,
  1868. yc = y.c;
  1869. if ( !xe || !ye ) {
  1870. // Either Infinity?
  1871. if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
  1872. // Either zero?
  1873. if ( !xc[0] || !yc[0] ) {
  1874. // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
  1875. return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
  1876. // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
  1877. ROUNDING_MODE == 3 ? -0 : 0 );
  1878. }
  1879. }
  1880. xe = bitFloor(xe);
  1881. ye = bitFloor(ye);
  1882. xc = xc.slice();
  1883. // Determine which is the bigger number.
  1884. if ( a = xe - ye ) {
  1885. if ( xLTy = a < 0 ) {
  1886. a = -a;
  1887. t = xc;
  1888. } else {
  1889. ye = xe;
  1890. t = yc;
  1891. }
  1892. t.reverse();
  1893. // Prepend zeros to equalise exponents.
  1894. for ( b = a; b--; t.push(0) );
  1895. t.reverse();
  1896. } else {
  1897. // Exponents equal. Check digit by digit.
  1898. j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
  1899. for ( a = b = 0; b < j; b++ ) {
  1900. if ( xc[b] != yc[b] ) {
  1901. xLTy = xc[b] < yc[b];
  1902. break;
  1903. }
  1904. }
  1905. }
  1906. // x < y? Point xc to the array of the bigger number.
  1907. if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
  1908. b = ( j = yc.length ) - ( i = xc.length );
  1909. // Append zeros to xc if shorter.
  1910. // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
  1911. if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
  1912. b = BASE - 1;
  1913. // Subtract yc from xc.
  1914. for ( ; j > a; ) {
  1915. if ( xc[--j] < yc[j] ) {
  1916. for ( i = j; i && !xc[--i]; xc[i] = b );
  1917. --xc[i];
  1918. xc[j] += BASE;
  1919. }
  1920. xc[j] -= yc[j];
  1921. }
  1922. // Remove leading zeros and adjust exponent accordingly.
  1923. for ( ; xc[0] == 0; xc.shift(), --ye );
  1924. // Zero?
  1925. if ( !xc[0] ) {
  1926. // Following IEEE 754 (2008) 6.3,
  1927. // n - n = +0 but n - n = -0 when rounding towards -Infinity.
  1928. y.s = ROUNDING_MODE == 3 ? -1 : 1;
  1929. y.c = [ y.e = 0 ];
  1930. return y;
  1931. }
  1932. // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
  1933. // for finite x and y.
  1934. return normalise( y, xc, ye );
  1935. };
  1936. /*
  1937. * n % 0 = N
  1938. * n % N = N
  1939. * n % I = n
  1940. * 0 % n = 0
  1941. * -0 % n = -0
  1942. * 0 % 0 = N
  1943. * 0 % N = N
  1944. * 0 % I = 0
  1945. * N % n = N
  1946. * N % 0 = N
  1947. * N % N = N
  1948. * N % I = N
  1949. * I % n = N
  1950. * I % 0 = N
  1951. * I % N = N
  1952. * I % I = N
  1953. *
  1954. * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
  1955. * BigNumber(y, b). The result depends on the value of MODULO_MODE.
  1956. */
  1957. P.modulo = P.mod = function ( y, b ) {
  1958. var q, s,
  1959. x = this;
  1960. id = 11;
  1961. y = new BigNumber( y, b );
  1962. // Return NaN if x is Infinity or NaN, or y is NaN or zero.
  1963. if ( !x.c || !y.s || y.c && !y.c[0] ) {
  1964. return new BigNumber(NaN);
  1965. // Return x if y is Infinity or x is zero.
  1966. } else if ( !y.c || x.c && !x.c[0] ) {
  1967. return new BigNumber(x);
  1968. }
  1969. if ( MODULO_MODE == 9 ) {
  1970. // Euclidian division: q = sign(y) * floor(x / abs(y))
  1971. // r = x - qy where 0 <= r < abs(y)
  1972. s = y.s;
  1973. y.s = 1;
  1974. q = div( x, y, 0, 3 );
  1975. y.s = s;
  1976. q.s *= s;
  1977. } else {
  1978. q = div( x, y, 0, MODULO_MODE );
  1979. }
  1980. return x.minus( q.times(y) );
  1981. };
  1982. /*
  1983. * Return a new BigNumber whose value is the value of this BigNumber negated,
  1984. * i.e. multiplied by -1.
  1985. */
  1986. P.negated = P.neg = function () {
  1987. var x = new BigNumber(this);
  1988. x.s = -x.s || null;
  1989. return x;
  1990. };
  1991. /*
  1992. * n + 0 = n
  1993. * n + N = N
  1994. * n + I = I
  1995. * 0 + n = n
  1996. * 0 + 0 = 0
  1997. * 0 + N = N
  1998. * 0 + I = I
  1999. * N + n = N
  2000. * N + 0 = N
  2001. * N + N = N
  2002. * N + I = N
  2003. * I + n = I
  2004. * I + 0 = I
  2005. * I + N = N
  2006. * I + I = I
  2007. *
  2008. * Return a new BigNumber whose value is the value of this BigNumber plus the value of
  2009. * BigNumber(y, b).
  2010. */
  2011. P.plus = P.add = function ( y, b ) {
  2012. var t,
  2013. x = this,
  2014. a = x.s;
  2015. id = 12;
  2016. y = new BigNumber( y, b );
  2017. b = y.s;
  2018. // Either NaN?
  2019. if ( !a || !b ) return new BigNumber(NaN);
  2020. // Signs differ?
  2021. if ( a != b ) {
  2022. y.s = -b;
  2023. return x.minus(y);
  2024. }
  2025. var xe = x.e / LOG_BASE,
  2026. ye = y.e / LOG_BASE,
  2027. xc = x.c,
  2028. yc = y.c;
  2029. if ( !xe || !ye ) {
  2030. // Return ±Infinity if either ±Infinity.
  2031. if ( !xc || !yc ) return new BigNumber( a / 0 );
  2032. // Either zero?
  2033. // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
  2034. if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
  2035. }
  2036. xe = bitFloor(xe);
  2037. ye = bitFloor(ye);
  2038. xc = xc.slice();
  2039. // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
  2040. if ( a = xe - ye ) {
  2041. if ( a > 0 ) {
  2042. ye = xe;
  2043. t = yc;
  2044. } else {
  2045. a = -a;
  2046. t = xc;
  2047. }
  2048. t.reverse();
  2049. for ( ; a--; t.push(0) );
  2050. t.reverse();
  2051. }
  2052. a = xc.length;
  2053. b = yc.length;
  2054. // Point xc to the longer array, and b to the shorter length.
  2055. if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
  2056. // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
  2057. for ( a = 0; b; ) {
  2058. a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
  2059. xc[b] %= BASE;
  2060. }
  2061. if (a) {
  2062. xc.unshift(a);
  2063. ++ye;
  2064. }
  2065. // No need to check for zero, as +x + +y != 0 && -x + -y != 0
  2066. // ye = MAX_EXP + 1 possible
  2067. return normalise( y, xc, ye );
  2068. };
  2069. /*
  2070. * Return the number of significant digits of the value of this BigNumber.
  2071. *
  2072. * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
  2073. */
  2074. P.precision = P.sd = function (z) {
  2075. var n, v,
  2076. x = this,
  2077. c = x.c;
  2078. // 'precision() argument not a boolean or binary digit: {z}'
  2079. if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
  2080. if (ERRORS) raise( 13, 'argument' + notBool, z );
  2081. if ( z != !!z ) z = null;
  2082. }
  2083. if ( !c ) return null;
  2084. v = c.length - 1;
  2085. n = v * LOG_BASE + 1;
  2086. if ( v = c[v] ) {
  2087. // Subtract the number of trailing zeros of the last element.
  2088. for ( ; v % 10 == 0; v /= 10, n-- );
  2089. // Add the number of digits of the first element.
  2090. for ( v = c[0]; v >= 10; v /= 10, n++ );
  2091. }
  2092. if ( z && x.e + 1 > n ) n = x.e + 1;
  2093. return n;
  2094. };
  2095. /*
  2096. * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
  2097. * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
  2098. * omitted.
  2099. *
  2100. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  2101. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2102. *
  2103. * 'round() decimal places out of range: {dp}'
  2104. * 'round() decimal places not an integer: {dp}'
  2105. * 'round() rounding mode not an integer: {rm}'
  2106. * 'round() rounding mode out of range: {rm}'
  2107. */
  2108. P.round = function ( dp, rm ) {
  2109. var n = new BigNumber(this);
  2110. if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
  2111. round( n, ~~dp + this.e + 1, rm == null ||
  2112. !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
  2113. }
  2114. return n;
  2115. };
  2116. /*
  2117. * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
  2118. * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
  2119. *
  2120. * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
  2121. *
  2122. * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
  2123. * otherwise.
  2124. *
  2125. * 'shift() argument not an integer: {k}'
  2126. * 'shift() argument out of range: {k}'
  2127. */
  2128. P.shift = function (k) {
  2129. var n = this;
  2130. return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
  2131. // k < 1e+21, or truncate(k) will produce exponential notation.
  2132. ? n.times( '1e' + truncate(k) )
  2133. : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
  2134. ? n.s * ( k < 0 ? 0 : 1 / 0 )
  2135. : n );
  2136. };
  2137. /*
  2138. * sqrt(-n) = N
  2139. * sqrt( N) = N
  2140. * sqrt(-I) = N
  2141. * sqrt( I) = I
  2142. * sqrt( 0) = 0
  2143. * sqrt(-0) = -0
  2144. *
  2145. * Return a new BigNumber whose value is the square root of the value of this BigNumber,
  2146. * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
  2147. */
  2148. P.squareRoot = P.sqrt = function () {
  2149. var m, n, r, rep, t,
  2150. x = this,
  2151. c = x.c,
  2152. s = x.s,
  2153. e = x.e,
  2154. dp = DECIMAL_PLACES + 4,
  2155. half = new BigNumber('0.5');
  2156. // Negative/NaN/Infinity/zero?
  2157. if ( s !== 1 || !c || !c[0] ) {
  2158. return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
  2159. }
  2160. // Initial estimate.
  2161. s = Math.sqrt( +x );
  2162. // Math.sqrt underflow/overflow?
  2163. // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
  2164. if ( s == 0 || s == 1 / 0 ) {
  2165. n = coeffToString(c);
  2166. if ( ( n.length + e ) % 2 == 0 ) n += '0';
  2167. s = Math.sqrt(n);
  2168. e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
  2169. if ( s == 1 / 0 ) {
  2170. n = '1e' + e;
  2171. } else {
  2172. n = s.toExponential();
  2173. n = n.slice( 0, n.indexOf('e') + 1 ) + e;
  2174. }
  2175. r = new BigNumber(n);
  2176. } else {
  2177. r = new BigNumber( s + '' );
  2178. }
  2179. // Check for zero.
  2180. // r could be zero if MIN_EXP is changed after the this value was created.
  2181. // This would cause a division by zero (x/t) and hence Infinity below, which would cause
  2182. // coeffToString to throw.
  2183. if ( r.c[0] ) {
  2184. e = r.e;
  2185. s = e + dp;
  2186. if ( s < 3 ) s = 0;
  2187. // Newton-Raphson iteration.
  2188. for ( ; ; ) {
  2189. t = r;
  2190. r = half.times( t.plus( div( x, t, dp, 1 ) ) );
  2191. if ( coeffToString( t.c ).slice( 0, s ) === ( n =
  2192. coeffToString( r.c ) ).slice( 0, s ) ) {
  2193. // The exponent of r may here be one less than the final result exponent,
  2194. // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
  2195. // are indexed correctly.
  2196. if ( r.e < e ) --s;
  2197. n = n.slice( s - 3, s + 1 );
  2198. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
  2199. // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
  2200. // iteration.
  2201. if ( n == '9999' || !rep && n == '4999' ) {
  2202. // On the first iteration only, check to see if rounding up gives the
  2203. // exact result as the nines may infinitely repeat.
  2204. if ( !rep ) {
  2205. round( t, t.e + DECIMAL_PLACES + 2, 0 );
  2206. if ( t.times(t).eq(x) ) {
  2207. r = t;
  2208. break;
  2209. }
  2210. }
  2211. dp += 4;
  2212. s += 4;
  2213. rep = 1;
  2214. } else {
  2215. // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
  2216. // result. If not, then there are further digits and m will be truthy.
  2217. if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
  2218. // Truncate to the first rounding digit.
  2219. round( r, r.e + DECIMAL_PLACES + 2, 1 );
  2220. m = !r.times(r).eq(x);
  2221. }
  2222. break;
  2223. }
  2224. }
  2225. }
  2226. }
  2227. return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
  2228. };
  2229. /*
  2230. * n * 0 = 0
  2231. * n * N = N
  2232. * n * I = I
  2233. * 0 * n = 0
  2234. * 0 * 0 = 0
  2235. * 0 * N = N
  2236. * 0 * I = N
  2237. * N * n = N
  2238. * N * 0 = N
  2239. * N * N = N
  2240. * N * I = N
  2241. * I * n = I
  2242. * I * 0 = N
  2243. * I * N = N
  2244. * I * I = I
  2245. *
  2246. * Return a new BigNumber whose value is the value of this BigNumber times the value of
  2247. * BigNumber(y, b).
  2248. */
  2249. P.times = P.mul = function ( y, b ) {
  2250. var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
  2251. base, sqrtBase,
  2252. x = this,
  2253. xc = x.c,
  2254. yc = ( id = 17, y = new BigNumber( y, b ) ).c;
  2255. // Either NaN, ±Infinity or ±0?
  2256. if ( !xc || !yc || !xc[0] || !yc[0] ) {
  2257. // Return NaN if either is NaN, or one is 0 and the other is Infinity.
  2258. if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
  2259. y.c = y.e = y.s = null;
  2260. } else {
  2261. y.s *= x.s;
  2262. // Return ±Infinity if either is ±Infinity.
  2263. if ( !xc || !yc ) {
  2264. y.c = y.e = null;
  2265. // Return ±0 if either is ±0.
  2266. } else {
  2267. y.c = [0];
  2268. y.e = 0;
  2269. }
  2270. }
  2271. return y;
  2272. }
  2273. e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
  2274. y.s *= x.s;
  2275. xcL = xc.length;
  2276. ycL = yc.length;
  2277. // Ensure xc points to longer array and xcL to its length.
  2278. if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
  2279. // Initialise the result array with zeros.
  2280. for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
  2281. base = BASE;
  2282. sqrtBase = SQRT_BASE;
  2283. for ( i = ycL; --i >= 0; ) {
  2284. c = 0;
  2285. ylo = yc[i] % sqrtBase;
  2286. yhi = yc[i] / sqrtBase | 0;
  2287. for ( k = xcL, j = i + k; j > i; ) {
  2288. xlo = xc[--k] % sqrtBase;
  2289. xhi = xc[k] / sqrtBase | 0;
  2290. m = yhi * xlo + xhi * ylo;
  2291. xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
  2292. c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
  2293. zc[j--] = xlo % base;
  2294. }
  2295. zc[j] = c;
  2296. }
  2297. if (c) {
  2298. ++e;
  2299. } else {
  2300. zc.shift();
  2301. }
  2302. return normalise( y, zc, e );
  2303. };
  2304. /*
  2305. * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
  2306. * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
  2307. *
  2308. * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
  2309. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2310. *
  2311. * 'toDigits() precision out of range: {sd}'
  2312. * 'toDigits() precision not an integer: {sd}'
  2313. * 'toDigits() rounding mode not an integer: {rm}'
  2314. * 'toDigits() rounding mode out of range: {rm}'
  2315. */
  2316. P.toDigits = function ( sd, rm ) {
  2317. var n = new BigNumber(this);
  2318. sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
  2319. rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
  2320. return sd ? round( n, sd, rm ) : n;
  2321. };
  2322. /*
  2323. * Return a string representing the value of this BigNumber in exponential notation and
  2324. * rounded using ROUNDING_MODE to dp fixed decimal places.
  2325. *
  2326. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  2327. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2328. *
  2329. * 'toExponential() decimal places not an integer: {dp}'
  2330. * 'toExponential() decimal places out of range: {dp}'
  2331. * 'toExponential() rounding mode not an integer: {rm}'
  2332. * 'toExponential() rounding mode out of range: {rm}'
  2333. */
  2334. P.toExponential = function ( dp, rm ) {
  2335. return format( this,
  2336. dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
  2337. };
  2338. /*
  2339. * Return a string representing the value of this BigNumber in fixed-point notation rounding
  2340. * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
  2341. *
  2342. * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
  2343. * but e.g. (-0.00001).toFixed(0) is '-0'.
  2344. *
  2345. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  2346. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2347. *
  2348. * 'toFixed() decimal places not an integer: {dp}'
  2349. * 'toFixed() decimal places out of range: {dp}'
  2350. * 'toFixed() rounding mode not an integer: {rm}'
  2351. * 'toFixed() rounding mode out of range: {rm}'
  2352. */
  2353. P.toFixed = function ( dp, rm ) {
  2354. return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
  2355. ? ~~dp + this.e + 1 : null, rm, 20 );
  2356. };
  2357. /*
  2358. * Return a string representing the value of this BigNumber in fixed-point notation rounded
  2359. * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
  2360. * of the FORMAT object (see BigNumber.config).
  2361. *
  2362. * FORMAT = {
  2363. * decimalSeparator : '.',
  2364. * groupSeparator : ',',
  2365. * groupSize : 3,
  2366. * secondaryGroupSize : 0,
  2367. * fractionGroupSeparator : '\xA0', // non-breaking space
  2368. * fractionGroupSize : 0
  2369. * };
  2370. *
  2371. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  2372. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2373. *
  2374. * 'toFormat() decimal places not an integer: {dp}'
  2375. * 'toFormat() decimal places out of range: {dp}'
  2376. * 'toFormat() rounding mode not an integer: {rm}'
  2377. * 'toFormat() rounding mode out of range: {rm}'
  2378. */
  2379. P.toFormat = function ( dp, rm ) {
  2380. var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
  2381. ? ~~dp + this.e + 1 : null, rm, 21 );
  2382. if ( this.c ) {
  2383. var i,
  2384. arr = str.split('.'),
  2385. g1 = +FORMAT.groupSize,
  2386. g2 = +FORMAT.secondaryGroupSize,
  2387. groupSeparator = FORMAT.groupSeparator,
  2388. intPart = arr[0],
  2389. fractionPart = arr[1],
  2390. isNeg = this.s < 0,
  2391. intDigits = isNeg ? intPart.slice(1) : intPart,
  2392. len = intDigits.length;
  2393. if (g2) i = g1, g1 = g2, g2 = i, len -= i;
  2394. if ( g1 > 0 && len > 0 ) {
  2395. i = len % g1 || g1;
  2396. intPart = intDigits.substr( 0, i );
  2397. for ( ; i < len; i += g1 ) {
  2398. intPart += groupSeparator + intDigits.substr( i, g1 );
  2399. }
  2400. if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
  2401. if (isNeg) intPart = '-' + intPart;
  2402. }
  2403. str = fractionPart
  2404. ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
  2405. ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
  2406. '$&' + FORMAT.fractionGroupSeparator )
  2407. : fractionPart )
  2408. : intPart;
  2409. }
  2410. return str;
  2411. };
  2412. /*
  2413. * Return a string array representing the value of this BigNumber as a simple fraction with
  2414. * an integer numerator and an integer denominator. The denominator will be a positive
  2415. * non-zero value less than or equal to the specified maximum denominator. If a maximum
  2416. * denominator is not specified, the denominator will be the lowest value necessary to
  2417. * represent the number exactly.
  2418. *
  2419. * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
  2420. *
  2421. * 'toFraction() max denominator not an integer: {md}'
  2422. * 'toFraction() max denominator out of range: {md}'
  2423. */
  2424. P.toFraction = function (md) {
  2425. var arr, d0, d2, e, exp, n, n0, q, s,
  2426. k = ERRORS,
  2427. x = this,
  2428. xc = x.c,
  2429. d = new BigNumber(ONE),
  2430. n1 = d0 = new BigNumber(ONE),
  2431. d1 = n0 = new BigNumber(ONE);
  2432. if ( md != null ) {
  2433. ERRORS = false;
  2434. n = new BigNumber(md);
  2435. ERRORS = k;
  2436. if ( !( k = n.isInt() ) || n.lt(ONE) ) {
  2437. if (ERRORS) {
  2438. raise( 22,
  2439. 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
  2440. }
  2441. // ERRORS is false:
  2442. // If md is a finite non-integer >= 1, round it to an integer and use it.
  2443. md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
  2444. }
  2445. }
  2446. if ( !xc ) return x.toString();
  2447. s = coeffToString(xc);
  2448. // Determine initial denominator.
  2449. // d is a power of 10 and the minimum max denominator that specifies the value exactly.
  2450. e = d.e = s.length - x.e - 1;
  2451. d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
  2452. md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
  2453. exp = MAX_EXP;
  2454. MAX_EXP = 1 / 0;
  2455. n = new BigNumber(s);
  2456. // n0 = d1 = 0
  2457. n0.c[0] = 0;
  2458. for ( ; ; ) {
  2459. q = div( n, d, 0, 1 );
  2460. d2 = d0.plus( q.times(d1) );
  2461. if ( d2.cmp(md) == 1 ) break;
  2462. d0 = d1;
  2463. d1 = d2;
  2464. n1 = n0.plus( q.times( d2 = n1 ) );
  2465. n0 = d2;
  2466. d = n.minus( q.times( d2 = d ) );
  2467. n = d2;
  2468. }
  2469. d2 = div( md.minus(d0), d1, 0, 1 );
  2470. n0 = n0.plus( d2.times(n1) );
  2471. d0 = d0.plus( d2.times(d1) );
  2472. n0.s = n1.s = x.s;
  2473. e *= 2;
  2474. // Determine which fraction is closer to x, n0/d0 or n1/d1
  2475. arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
  2476. div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
  2477. ? [ n1.toString(), d1.toString() ]
  2478. : [ n0.toString(), d0.toString() ];
  2479. MAX_EXP = exp;
  2480. return arr;
  2481. };
  2482. /*
  2483. * Return the value of this BigNumber converted to a number primitive.
  2484. */
  2485. P.toNumber = function () {
  2486. var x = this;
  2487. // Ensure zero has correct sign.
  2488. return +x || ( x.s ? x.s * 0 : NaN );
  2489. };
  2490. /*
  2491. * Return a BigNumber whose value is the value of this BigNumber raised to the power n.
  2492. * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
  2493. * If POW_PRECISION is not 0, round to POW_PRECISION using ROUNDING_MODE.
  2494. *
  2495. * n {number} Integer, -9007199254740992 to 9007199254740992 inclusive.
  2496. * (Performs 54 loop iterations for n of 9007199254740992.)
  2497. *
  2498. * 'pow() exponent not an integer: {n}'
  2499. * 'pow() exponent out of range: {n}'
  2500. */
  2501. P.toPower = P.pow = function (n) {
  2502. var k, y,
  2503. i = mathfloor( n < 0 ? -n : +n ),
  2504. x = this;
  2505. // Pass ±Infinity to Math.pow if exponent is out of range.
  2506. if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
  2507. ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
  2508. parseFloat(n) != n && !( n = NaN ) ) ) {
  2509. return new BigNumber( Math.pow( +x, n ) );
  2510. }
  2511. // Truncating each coefficient array to a length of k after each multiplication equates
  2512. // to truncating significant digits to POW_PRECISION + [28, 41], i.e. there will be a
  2513. // minimum of 28 guard digits retained. (Using + 1.5 would give [9, 21] guard digits.)
  2514. k = POW_PRECISION ? mathceil( POW_PRECISION / LOG_BASE + 2 ) : 0;
  2515. y = new BigNumber(ONE);
  2516. for ( ; ; ) {
  2517. if ( i % 2 ) {
  2518. y = y.times(x);
  2519. if ( !y.c ) break;
  2520. if ( k && y.c.length > k ) y.c.length = k;
  2521. }
  2522. i = mathfloor( i / 2 );
  2523. if ( !i ) break;
  2524. x = x.times(x);
  2525. if ( k && x.c && x.c.length > k ) x.c.length = k;
  2526. }
  2527. if ( n < 0 ) y = ONE.div(y);
  2528. return k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
  2529. };
  2530. /*
  2531. * Return a string representing the value of this BigNumber rounded to sd significant digits
  2532. * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
  2533. * necessary to represent the integer part of the value in fixed-point notation, then use
  2534. * exponential notation.
  2535. *
  2536. * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
  2537. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2538. *
  2539. * 'toPrecision() precision not an integer: {sd}'
  2540. * 'toPrecision() precision out of range: {sd}'
  2541. * 'toPrecision() rounding mode not an integer: {rm}'
  2542. * 'toPrecision() rounding mode out of range: {rm}'
  2543. */
  2544. P.toPrecision = function ( sd, rm ) {
  2545. return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
  2546. ? sd | 0 : null, rm, 24 );
  2547. };
  2548. /*
  2549. * Return a string representing the value of this BigNumber in base b, or base 10 if b is
  2550. * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
  2551. * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
  2552. * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
  2553. * TO_EXP_NEG, return exponential notation.
  2554. *
  2555. * [b] {number} Integer, 2 to 64 inclusive.
  2556. *
  2557. * 'toString() base not an integer: {b}'
  2558. * 'toString() base out of range: {b}'
  2559. */
  2560. P.toString = function (b) {
  2561. var str,
  2562. n = this,
  2563. s = n.s,
  2564. e = n.e;
  2565. // Infinity or NaN?
  2566. if ( e === null ) {
  2567. if (s) {
  2568. str = 'Infinity';
  2569. if ( s < 0 ) str = '-' + str;
  2570. } else {
  2571. str = 'NaN';
  2572. }
  2573. } else {
  2574. str = coeffToString( n.c );
  2575. if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
  2576. str = e <= TO_EXP_NEG || e >= TO_EXP_POS
  2577. ? toExponential( str, e )
  2578. : toFixedPoint( str, e );
  2579. } else {
  2580. str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
  2581. }
  2582. if ( s < 0 && n.c[0] ) str = '-' + str;
  2583. }
  2584. return str;
  2585. };
  2586. /*
  2587. * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
  2588. * number.
  2589. */
  2590. P.truncated = P.trunc = function () {
  2591. return round( new BigNumber(this), this.e + 1, 1 );
  2592. };
  2593. /*
  2594. * Return as toString, but do not accept a base argument.
  2595. */
  2596. P.valueOf = P.toJSON = function () {
  2597. return this.toString();
  2598. };
  2599. // Aliases for BigDecimal methods.
  2600. //P.add = P.plus; // P.add included above
  2601. //P.subtract = P.minus; // P.sub included above
  2602. //P.multiply = P.times; // P.mul included above
  2603. //P.divide = P.div;
  2604. //P.remainder = P.mod;
  2605. //P.compareTo = P.cmp;
  2606. //P.negate = P.neg;
  2607. if ( configObj != null ) BigNumber.config(configObj);
  2608. return BigNumber;
  2609. }
  2610. // PRIVATE HELPER FUNCTIONS
  2611. function bitFloor(n) {
  2612. var i = n | 0;
  2613. return n > 0 || n === i ? i : i - 1;
  2614. }
  2615. // Return a coefficient array as a string of base 10 digits.
  2616. function coeffToString(a) {
  2617. var s, z,
  2618. i = 1,
  2619. j = a.length,
  2620. r = a[0] + '';
  2621. for ( ; i < j; ) {
  2622. s = a[i++] + '';
  2623. z = LOG_BASE - s.length;
  2624. for ( ; z--; s = '0' + s );
  2625. r += s;
  2626. }
  2627. // Determine trailing zeros.
  2628. for ( j = r.length; r.charCodeAt(--j) === 48; );
  2629. return r.slice( 0, j + 1 || 1 );
  2630. }
  2631. // Compare the value of BigNumbers x and y.
  2632. function compare( x, y ) {
  2633. var a, b,
  2634. xc = x.c,
  2635. yc = y.c,
  2636. i = x.s,
  2637. j = y.s,
  2638. k = x.e,
  2639. l = y.e;
  2640. // Either NaN?
  2641. if ( !i || !j ) return null;
  2642. a = xc && !xc[0];
  2643. b = yc && !yc[0];
  2644. // Either zero?
  2645. if ( a || b ) return a ? b ? 0 : -j : i;
  2646. // Signs differ?
  2647. if ( i != j ) return i;
  2648. a = i < 0;
  2649. b = k == l;
  2650. // Either Infinity?
  2651. if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
  2652. // Compare exponents.
  2653. if ( !b ) return k > l ^ a ? 1 : -1;
  2654. j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
  2655. // Compare digit by digit.
  2656. for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
  2657. // Compare lengths.
  2658. return k == l ? 0 : k > l ^ a ? 1 : -1;
  2659. }
  2660. /*
  2661. * Return true if n is a valid number in range, otherwise false.
  2662. * Use for argument validation when ERRORS is false.
  2663. * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
  2664. */
  2665. function intValidatorNoErrors( n, min, max ) {
  2666. return ( n = truncate(n) ) >= min && n <= max;
  2667. }
  2668. function isArray(obj) {
  2669. return Object.prototype.toString.call(obj) == '[object Array]';
  2670. }
  2671. /*
  2672. * Convert string of baseIn to an array of numbers of baseOut.
  2673. * Eg. convertBase('255', 10, 16) returns [15, 15].
  2674. * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
  2675. */
  2676. function toBaseOut( str, baseIn, baseOut ) {
  2677. var j,
  2678. arr = [0],
  2679. arrL,
  2680. i = 0,
  2681. len = str.length;
  2682. for ( ; i < len; ) {
  2683. for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
  2684. arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
  2685. for ( ; j < arr.length; j++ ) {
  2686. if ( arr[j] > baseOut - 1 ) {
  2687. if ( arr[j + 1] == null ) arr[j + 1] = 0;
  2688. arr[j + 1] += arr[j] / baseOut | 0;
  2689. arr[j] %= baseOut;
  2690. }
  2691. }
  2692. }
  2693. return arr.reverse();
  2694. }
  2695. function toExponential( str, e ) {
  2696. return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
  2697. ( e < 0 ? 'e' : 'e+' ) + e;
  2698. }
  2699. function toFixedPoint( str, e ) {
  2700. var len, z;
  2701. // Negative exponent?
  2702. if ( e < 0 ) {
  2703. // Prepend zeros.
  2704. for ( z = '0.'; ++e; z += '0' );
  2705. str = z + str;
  2706. // Positive exponent
  2707. } else {
  2708. len = str.length;
  2709. // Append zeros.
  2710. if ( ++e > len ) {
  2711. for ( z = '0', e -= len; --e; z += '0' );
  2712. str += z;
  2713. } else if ( e < len ) {
  2714. str = str.slice( 0, e ) + '.' + str.slice(e);
  2715. }
  2716. }
  2717. return str;
  2718. }
  2719. function truncate(n) {
  2720. n = parseFloat(n);
  2721. return n < 0 ? mathceil(n) : mathfloor(n);
  2722. }
  2723. // EXPORT
  2724. BigNumber = another();
  2725. // AMD.
  2726. if ( typeof define == 'function' && define.amd ) {
  2727. define( function () { return BigNumber; } );
  2728. // Node and other environments that support module.exports.
  2729. } else if ( typeof module != 'undefined' && module.exports ) {
  2730. module.exports = BigNumber;
  2731. if ( !crypto ) try { crypto = require('crypto'); } catch (e) {}
  2732. // Browser.
  2733. } else {
  2734. global.BigNumber = BigNumber;
  2735. }
  2736. })(this);
  2737. },{"crypto":1}],"natspec":[function(require,module,exports){
  2738. /*
  2739. This file is part of natspec.js.
  2740. natspec.js is free software: you can redistribute it and/or modify
  2741. it under the terms of the GNU Lesser General Public License as published by
  2742. the Free Software Foundation, either version 3 of the License, or
  2743. (at your option) any later version.
  2744. natspec.js is distributed in the hope that it will be useful,
  2745. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2746. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2747. GNU Lesser General Public License for more details.
  2748. You should have received a copy of the GNU Lesser General Public License
  2749. along with natspec.js. If not, see <http://www.gnu.org/licenses/>.
  2750. */
  2751. /** @file natspec.js
  2752. * @authors:
  2753. * Marek Kotewicz <marek@ethdev.com>
  2754. * @date 2015
  2755. */
  2756. var abi = require('./node_modules/ethereum.js/lib/abi.js');
  2757. /**
  2758. * This object should be used to evaluate natspec expression
  2759. * It has one method evaluateExpression which shoul be used
  2760. */
  2761. var natspec = (function () {
  2762. /// Helper method
  2763. /// Should be called to copy values from object to global context
  2764. var copyToContext = function (obj, context) {
  2765. Object.keys(obj).forEach(function (key) {
  2766. context[key] = obj[key];
  2767. });
  2768. }
  2769. /// generate codes, which will be evaluated
  2770. var generateCode = function (obj) {
  2771. return Object.keys(obj).reduce(function (acc, key) {
  2772. return acc + "var " + key + " = context['" + key + "'];\n";
  2773. }, "");
  2774. };
  2775. /// Helper method
  2776. /// Should be called to get method with given name from the abi
  2777. /// @param contract's abi
  2778. /// @param name of the method that we are looking for
  2779. var getMethodWithName = function(abi, name) {
  2780. return abi.filter(function (method) {
  2781. return method.name === name;
  2782. })[0];
  2783. };
  2784. /// Function called to get all contract method input variables
  2785. /// @returns hashmap with all contract's method input variables
  2786. var getMethodInputParams = function (method, transaction) {
  2787. // do it with output formatter (cause we have to decode)
  2788. var params = abi.formatOutput(method.inputs, '0x' + transaction.params[0].data.slice(10));
  2789. return method.inputs.reduce(function (acc, current, index) {
  2790. acc[current.name] = params[index];
  2791. return acc;
  2792. }, {});
  2793. };
  2794. /// Should be called to evaluate expression
  2795. var mapExpressionsToEvaluate = function (expression, cb) {
  2796. var evaluatedExpression = "";
  2797. // match everything in `` quotes
  2798. var pattern = /\`(?:\\.|[^`\\])*\`/gim
  2799. var match;
  2800. var lastIndex = 0;
  2801. while ((match = pattern.exec(expression)) !== null) {
  2802. var startIndex = pattern.lastIndex - match[0].length;
  2803. var toEval = match[0].slice(1, match[0].length - 1);
  2804. evaluatedExpression += expression.slice(lastIndex, startIndex);
  2805. var evaluatedPart = cb(toEval);
  2806. evaluatedExpression += evaluatedPart;
  2807. lastIndex = pattern.lastIndex;
  2808. }
  2809. evaluatedExpression += expression.slice(lastIndex);
  2810. return evaluatedExpression;
  2811. };
  2812. /// Should be called to evaluate single expression
  2813. /// Is internally using javascript's 'eval' method
  2814. /// @param expression which should be evaluated
  2815. /// @param [call] object containing contract abi, transaction, called method
  2816. /// TODO: separate evaluation from getting input params, so as not to spoil 'evaluateExpression' function
  2817. var evaluateExpression = function (expression, call) {
  2818. //var self = this;
  2819. var context = {};
  2820. if (!!call) {
  2821. try {
  2822. var method = getMethodWithName(call.abi, call.method);
  2823. var params = getMethodInputParams(method, call.transaction);
  2824. copyToContext(params, context);
  2825. }
  2826. catch (err) {
  2827. return "Natspec evaluation failed, wrong input params";
  2828. }
  2829. }
  2830. var code = generateCode(context);
  2831. var evaluatedExpression = mapExpressionsToEvaluate(expression, function (toEval) {
  2832. try {
  2833. var fn = new Function("context", code + "return " + toEval + ";");
  2834. return fn(context).toString();
  2835. }
  2836. catch (err) {
  2837. return 'undefined';
  2838. }
  2839. });
  2840. return evaluatedExpression;
  2841. };
  2842. return {
  2843. evaluateExpression: evaluateExpression
  2844. };
  2845. })();
  2846. module.exports = natspec;
  2847. },{"./node_modules/ethereum.js/lib/abi.js":3}]},{},[]);