github.com/jeffallen/go-ethereum@v1.1.4-0.20150910155051-571d3236c49c/common/natspec/natspec_js.go (about)

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