natspec_js.go 157 KB

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