diff --git a/CMakeLists.txt b/CMakeLists.txt index 778f7dafe..037728a9e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,6 +23,7 @@ function(createDefaultCacheConfig) set(JUSTTESTS OFF CACHE BOOL "Build only for tests.") set(SOLIDITY ON CACHE BOOL "Build the Solidity language components (requried unless HEADLESS)") set(USENPM OFF CACHE BOOL "Use npm to recompile ethereum.js if it was changed") + set(ETHASHCL OFF CACHE BOOL "Build in support for GPU mining via OpenCL") endfunction() @@ -44,6 +45,10 @@ function(configureProject) endif () endif () + if (ETHASHCL) + add_definitions(-DETH_ETHASHCL) + endif() + if (EVMJIT) add_definitions(-DETH_EVMJIT) endif() @@ -181,6 +186,10 @@ add_subdirectory(libdevcrypto) add_subdirectory(libwhisper) add_subdirectory(libethash) +if (ETHASHCL) + add_subdirectory(libethash-cl) +endif () + add_subdirectory(libethcore) add_subdirectory(libevm) add_subdirectory(libethereum) diff --git a/alethzero/MainWin.cpp b/alethzero/MainWin.cpp index 0fc4d34f6..a6ef485df 100644 --- a/alethzero/MainWin.cpp +++ b/alethzero/MainWin.cpp @@ -478,10 +478,83 @@ QString Main::pretty(dev::Address _a) const return fromRaw(n); } +template inline string toBase36(FixedHash const& _h) +{ + static char const* c_alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + typename FixedHash::Arith a = _h; + std::string ret; + for (; a > 0; a /= 36) + ret = c_alphabet[(unsigned)a % 36] + ret; + return ret; +} + +template inline FixedHash fromBase36(string const& _h) +{ + typename FixedHash::Arith ret = 0; + for (char c: _h) + ret = ret * 36 + (c < 'A' ? c - '0' : (c - 'A' + 10)); + return ret; +} + +static string iban(std::string _c, std::string _d) +{ + boost::to_upper(_c); + boost::to_upper(_d); + auto totStr = _d + _c + "00"; + bigint tot = 0; + for (char x: totStr) + if (x >= 'A') + tot = tot * 100 + x - 'A' + 10; + else + tot = tot * 10 + x - '0'; + unsigned check = (unsigned)(u256)(98 - tot % 97); + ostringstream out; + out << _c << setfill('0') << setw(2) << check << _d; + return out.str(); +} + +static std::pair fromIban(std::string _iban) +{ + if (_iban.size() < 4) + return std::make_pair(string(), string()); + boost::to_upper(_iban); + std::string c = _iban.substr(0, 2); + std::string d = _iban.substr(4); + if (iban(c, d) != _iban) + return std::make_pair(string(), string()); + return make_pair(c, d); +} + +static string directICAP(dev::Address _a) +{ + if (!!_a[0]) + return string(); + std::string d = toBase36(_a); + while (d.size() < 30) + d = "0" + d; + return iban("XE", d); +} + +static Address fromICAP(std::string const& _s) +{ + std::string country; + std::string data; + std::tie(country, data) = fromIban(_s); + if (country.empty()) + return Address(); + if (country == "XE" && data.size() == 30) + // Direct ICAP + return fromBase36(data); + // TODO: Indirect ICAP + return Address(); +} + QString Main::render(dev::Address _a) const { QString p = pretty(_a); - if (!p.isNull()) + if (!_a[0]) + p += QString(p.isEmpty() ? "" : " ") + QString::fromStdString(directICAP(_a)); + if (!p.isEmpty()) return p + " (" + QString::fromStdString(_a.abridged()) + ")"; return QString::fromStdString(_a.abridged()); } @@ -524,6 +597,8 @@ Address Main::fromString(QString const& _n) const return Address(); } } + else if (Address a = fromICAP(_n.toStdString())) + return a; else return Address(); } @@ -1012,7 +1087,7 @@ void Main::refreshBlockChain() h256 h(f.toStdString()); if (bc.isKnown(h)) blocks.insert(h); - for (auto const& b: bc.withBlockBloom(LogBloom().shiftBloom<3, 32>(sha3(h)), 0, -1)) + for (auto const& b: bc.withBlockBloom(LogBloom().shiftBloom<3>(sha3(h)), 0, -1)) blocks.insert(bc.numberHash(b)); } else if (f.toLongLong() <= bc.number()) @@ -1020,7 +1095,7 @@ void Main::refreshBlockChain() else if (f.size() == 40) { Address h(f.toStdString()); - for (auto const& b: bc.withBlockBloom(LogBloom().shiftBloom<3, 32>(sha3(h)), 0, -1)) + for (auto const& b: bc.withBlockBloom(LogBloom().shiftBloom<3>(sha3(h)), 0, -1)) blocks.insert(bc.numberHash(b)); } @@ -1171,7 +1246,7 @@ void Main::timerEvent(QTimerEvent*) for (auto const& i: m_handlers) { - auto ls = ethereum()->checkWatch(i.first); + auto ls = ethereum()->checkWatchSafe(i.first); if (ls.size()) { cnote << "FIRING WATCH" << i.first << ls.size(); @@ -1276,7 +1351,10 @@ void Main::on_transactionQueue_currentItemChanged() } s << "
Hex: " Span(Mono) << toHex(tx.rlp()) << "
"; s << "
"; - s << "
Log Bloom: " << receipt.bloom() << "
"; + if (!!receipt.bloom()) + s << "
Log Bloom: " << receipt.bloom() << "
"; + else + s << "
Log Bloom: Uneventful
"; auto r = receipt.rlp(); s << "
Receipt: " << toString(RLP(r)) << "
"; s << "
Receipt-Hex: " Span(Mono) << toHex(receipt.rlp()) << "
"; @@ -1351,11 +1429,11 @@ void Main::on_blocks_currentItemChanged() s << "

" << h << "

"; s << "

#" << info.number; s << "   " << timestamp << "

"; - s << "
D/TD: 2^" << log2((double)info.difficulty) << "/2^" << log2((double)details.totalDifficulty) << ""; + s << "
D/TD: " << info.difficulty << "/" << details.totalDifficulty << " = 2^" << log2((double)info.difficulty) << "/2^" << log2((double)details.totalDifficulty); s << "   Children: " << details.children.size() << ""; s << "
Gas used/limit: " << info.gasUsed << "/" << info.gasLimit << ""; s << "
Coinbase: " << pretty(info.coinbaseAddress).toHtmlEscaped().toStdString() << " " << info.coinbaseAddress; - s << "
Seed hash: " << info.seedHash << ""; + s << "
Seed hash: " << info.seedHash() << ""; s << "
Mix hash: " << info.mixHash << ""; s << "
Nonce: " << info.nonce << ""; s << "
Hash w/o nonce: " << info.headerHash(WithoutNonce) << ""; @@ -1364,12 +1442,18 @@ void Main::on_blocks_currentItemChanged() { auto e = Ethasher::eval(info); s << "
Proof-of-Work: " << e.value << " <= " << (h256)u256((bigint(1) << 256) / info.difficulty) << " (mixhash: " << e.mixHash.abridged() << ")"; + s << "
Parent: " << info.parentHash << ""; } else + { s << "
Proof-of-Work: Phil has nothing to prove"; - s << "
Parent: " << info.parentHash << ""; + s << "
Parent: It was a virgin birth"; + } // s << "
Bloom: " << details.bloom << ""; - s << "
Log Bloom: " << info.logBloom << ""; + if (!!info.logBloom) + s << "
Log Bloom: " << info.logBloom << "
"; + else + s << "
Log Bloom: Uneventful
"; s << "
Transactions: " << block[1].itemCount() << " @" << info.transactionsRoot << ""; s << "
Receipts: @" << info.receiptsRoot << ":"; s << "
Uncles: " << block[2].itemCount() << " @" << info.sha3Uncles << ""; @@ -1381,7 +1465,7 @@ void Main::on_blocks_currentItemChanged() s << line << "Parent: " << uncle.parentHash << ""; s << line << "Number: " << uncle.number << ""; s << line << "Coinbase: " << pretty(uncle.coinbaseAddress).toHtmlEscaped().toStdString() << " " << uncle.coinbaseAddress; - s << line << "Seed hash: " << uncle.seedHash << ""; + s << line << "Seed hash: " << uncle.seedHash() << ""; s << line << "Mix hash: " << uncle.mixHash << ""; s << line << "Nonce: " << uncle.nonce << ""; s << line << "Hash w/o nonce: " << uncle.headerHash(WithoutNonce) << ""; @@ -1426,23 +1510,23 @@ void Main::on_blocks_currentItemChanged() s << "
R: " << hex << nouppercase << tx.signature().r << ""; s << "
S: " << hex << nouppercase << tx.signature().s << ""; s << "
Msg: " << tx.sha3(eth::WithoutSignature) << ""; - if (tx.isCreation()) + if (!tx.data().empty()) { - if (tx.data().size()) + if (tx.isCreation()) s << "

Code

" << disassemble(tx.data()); - } - else - { - if (tx.data().size()) - s << dev::memDump(tx.data(), 16, true); + else + s << "

Data

" << dev::memDump(tx.data(), 16, true); } s << "
Hex: " Span(Mono) << toHex(block[1][txi].data()) << "
"; s << "
"; - s << "
Log Bloom: " << receipt.bloom() << "
"; + if (!!receipt.bloom()) + s << "
Log Bloom: " << receipt.bloom() << "
"; + else + s << "
Log Bloom: Uneventful
"; auto r = receipt.rlp(); s << "
Receipt: " << toString(RLP(r)) << "
"; s << "
Receipt-Hex: " Span(Mono) << toHex(receipt.rlp()) << "
"; - s << renderDiff(ethereum()->diff(txi, h)); + s << "

Diff

" << renderDiff(ethereum()->diff(txi, h)); ui->debugCurrent->setEnabled(true); ui->debugDumpState->setEnabled(true); ui->debugDumpStatePre->setEnabled(true); @@ -1710,9 +1794,9 @@ bool beginsWith(Address _a, bytes const& _b) void Main::on_newAccount_triggered() { bool ok = true; - enum { NoVanity = 0, FirstTwo, FirstTwoNextTwo, FirstThree, FirstFour, StringMatch }; - QStringList items = {"No vanity (instant)", "Two pairs first (a few seconds)", "Two pairs first and second (a few minutes)", "Three pairs first (a few minutes)", "Four pairs first (several hours)", "Specific hex string"}; - unsigned v = items.QList::indexOf(QInputDialog::getItem(this, "Vanity Key?", "Would you a vanity key? This could take several hours.", items, 0, false, &ok)); + enum { NoVanity = 0, DirectICAP, FirstTwo, FirstTwoNextTwo, FirstThree, FirstFour, StringMatch }; + QStringList items = {"No vanity (instant)", "Direct ICAP address", "Two pairs first (a few seconds)", "Two pairs first and second (a few minutes)", "Three pairs first (a few minutes)", "Four pairs first (several hours)", "Specific hex string"}; + unsigned v = items.QList::indexOf(QInputDialog::getItem(this, "Vanity Key?", "Would you a vanity key? This could take several hours.", items, 1, false, &ok)); if (!ok) return; @@ -1738,6 +1822,7 @@ void Main::on_newAccount_triggered() lp = KeyPair::create(); auto a = lp.address(); if (v == NoVanity || + (v == DirectICAP && !a[0]) || (v == FirstTwo && a[0] == a[1]) || (v == FirstTwoNextTwo && a[0] == a[1] && a[2] == a[3]) || (v == FirstThree && a[0] == a[1] && a[1] == a[2]) || diff --git a/chrono_io/chrono_io b/chrono_io/chrono_io deleted file mode 100644 index 8de9d4f45..000000000 --- a/chrono_io/chrono_io +++ /dev/null @@ -1,1140 +0,0 @@ -// chrono_io -// -// (C) Copyright Howard Hinnant -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). - -#ifndef _CHRONO_IO -#define _CHRONO_IO - -/* - - chrono_io synopsis - -#include -#include - -namespace std -{ -namespace chrono -{ - -template -class durationpunct - : public locale::facet -{ -public: - static locale::id id; - - typedef basic_string string_type; - enum {use_long, use_short}; - - explicit durationpunct(int use = use_long); - - durationpunct(int use, - const string_type& long_seconds, const string_type& long_minutes, - const string_type& long_hours, const string_type& short_seconds, - const string_type& short_minutes, const string_type& short_hours); - - durationpunct(int use, const durationpunct& d); - - template string_type short_name() const; - template string_type long_name() const; - template string_type name() const; - - bool is_short_name() const; - bool is_long_name() const; -}; - -template - basic_ostream& - duration_short(basic_ostream& os); - -template - basic_ostream& - duration_long(basic_ostream& os); - -template - basic_ostream& - operator<<(basic_ostream& os, const duration& d); - -template - basic_istream& - operator>>(basic_istream& is, duration& d); - -template - basic_ostream& - operator<<(basic_ostream& os, - const time_point& tp); - -template - basic_ostream& - operator<<(basic_ostream& os, - const time_point& tp); - -template - basic_ostream& - operator<<(basic_ostream& os, - const time_point& tp); - -template - basic_istream& - operator>>(basic_istream& is, - time_point& tp); - -template - basic_istream& - operator>>(basic_istream& is, - time_point& tp); - -template - basic_istream& - operator>>(basic_istream& is, - time_point& tp); - -template -class timepunct - : public std::locale::facet -{ -public: - typedef std::basic_string string_type; - - static std::locale::id id; - - explicit timepunct(std::size_t refs = 0, - const string_type& fmt = string_type(), - bool local = false); - - explicit timepunct(std::size_t refs, - string_type&& fmt, - bool local = false); - - const string_type& fmt() const {return fmt_;} - bool local() const {return local_;} -}; - -template - unspecfiied - local_fmt(std::basic_string fmt = std::basic_string()); - -template - unspecfiied - local_fmt(const CharT* fmt); - -template - unspecfiied - utc_fmt(std::basic_string fmt = std::basic_string()); - -template - unspecfiied - utc_fmt(const CharT* fmt); - -} // chrono -} // std - -*/ - -#include -#include "ratio_io" - -namespace std { - -namespace chrono -{ - -template -To -round(const duration& d) -{ - To t0 = duration_cast(d); - To t1 = t0; - ++t1; - typedef typename common_type >::type _D; - _D diff0 = d - t0; - _D diff1 = t1 - d; - if (diff0 == diff1) - { - if (t0.count() & 1) - return t1; - return t0; - } - else if (diff0 < diff1) - return t0; - return t1; -} - -template -class durationpunct - : public locale::facet -{ -public: - typedef basic_string<_CharT> string_type; - enum {use_long, use_short}; - -private: - bool __use_short_; - string_type __seconds_; - string_type __minutes_; - string_type __hours_; -public: - static locale::id id; - - explicit durationpunct(size_t refs = 0, - int __use = use_long) - : locale::facet(refs), __use_short_(__use) {} - - durationpunct(size_t refs, int __use, - string_type __seconds, string_type __minutes, - string_type __hours) - : locale::facet(refs), __use_short_(__use), - __seconds_(std::move(__seconds)), - __minutes_(std::move(__minutes)), - __hours_(std::move(__hours)) {} - - bool is_short_name() const {return __use_short_;} - bool is_long_name() const {return !__use_short_;} - - string_type seconds() const {return __seconds_;} - string_type minutes() const {return __minutes_;} - string_type hours() const {return __hours_;} -}; - -template -locale::id -durationpunct<_CharT>::id; - -enum {prefix, symbol}; -enum {utc, local}; - -template -struct __duration_manip -{ - bool __use_short_; - basic_string<_CharT> __seconds_; - basic_string<_CharT> __minutes_; - basic_string<_CharT> __hours_; - - __duration_manip(bool __use_short, basic_string<_CharT> __seconds, - basic_string<_CharT> __minutes, basic_string<_CharT> __hours) - : __use_short_(__use_short), - __seconds_(std::move(__seconds)), - __minutes_(std::move(__minutes)), - __hours_(std::move(__hours)) {} -}; - -class duration_fmt -{ - int form_; -public: - explicit duration_fmt(int f) : form_(f) {} - // explicit - operator int() const {return form_;} -}; - -template -std::basic_ostream& -operator <<(std::basic_ostream& os, duration_fmt d) -{ - os.imbue(std::locale(os.getloc(), new durationpunct(0, d == symbol))); - return os; -} - -template -std::basic_istream& -operator >>(std::basic_istream& is, duration_fmt d) -{ - is.imbue(std::locale(is.getloc(), new durationpunct(0, d == symbol))); - return is; -} - -template -std::basic_ostream& -operator <<(std::basic_ostream& os, __duration_manip m) -{ - os.imbue(std::locale(os.getloc(), new durationpunct(0, m.__use_short_, - std::move(m.__seconds_), std::move(m.__minutes_), std::move(m.__hours_)))); - return os; -} - -template -std::basic_istream& -operator >>(std::basic_istream& is, __duration_manip m) -{ - is.imbue(std::locale(is.getloc(), new durationpunct(0, m.__use_short_, - std::move(m.__seconds_), std::move(m.__minutes_), std::move(m.__hours_)))); - return is; -} - -inline -__duration_manip -duration_short() -{ - return __duration_manip(durationpunct::use_short, "", "", ""); -} - -template -inline -__duration_manip<_CharT> -duration_short(basic_string<_CharT> __seconds, - basic_string<_CharT> __minutes, - basic_string<_CharT> __hours) -{ - return __duration_manip<_CharT>(durationpunct<_CharT>::use_short, - std::move(__seconds), std::move(__minutes), - std::move(__hours)); -} - -inline -__duration_manip -duration_long() -{ - return __duration_manip(durationpunct::use_long, "", "", ""); -} - -template -inline -typename enable_if -< - is_convertible<_T2, basic_string<_CharT> >::value && - is_convertible<_T3, basic_string<_CharT> >::value, - __duration_manip<_CharT> ->::type -duration_long(basic_string<_CharT> __seconds, - _T2 __minutes, - _T3 __hours) -{ - typedef basic_string<_CharT> string_type; - return __duration_manip<_CharT>(durationpunct<_CharT>::use_long, - std::move(__seconds), - string_type(std::move(__minutes)), - string_type(std::move(__hours))); -} - -template -inline -typename enable_if -< - is_convertible<_T2, basic_string<_CharT> >::value && - is_convertible<_T3, basic_string<_CharT> >::value, - __duration_manip<_CharT> ->::type -duration_long(const _CharT* __seconds, - _T2 __minutes, - _T3 __hours) -{ - typedef basic_string<_CharT> string_type; - return __duration_manip<_CharT>(durationpunct<_CharT>::use_long, - string_type(__seconds), - string_type(std::move(__minutes)), - string_type(std::move(__hours))); -} - -template -basic_string<_CharT> -__get_unit(bool __is_long, const basic_string<_CharT>& __seconds, - const basic_string<_CharT>&, const basic_string<_CharT>&, _Period) -{ - if (__is_long) - { - if (__seconds.empty()) - { - _CharT __p[] = {'s', 'e', 'c', 'o', 'n', 'd', 's', 0}; - return ratio_string<_Period, _CharT>::prefix() + __p; - } - return ratio_string<_Period, _CharT>::prefix() + __seconds; - } - if (__seconds.empty()) - return ratio_string<_Period, _CharT>::symbol() + 's'; - return ratio_string<_Period, _CharT>::symbol() + __seconds; -} - -template -inline -basic_string<_CharT> -__get_unit(bool __is_long, const basic_string<_CharT>& __seconds, - const basic_string<_CharT>&, const basic_string<_CharT>&, ratio<1>) -{ - if (__seconds.empty()) - { - if (__is_long) - { - _CharT __p[] = {'s', 'e', 'c', 'o', 'n', 'd', 's'}; - return basic_string<_CharT>(__p, __p + sizeof(__p) / sizeof(_CharT)); - } - else - return basic_string<_CharT>(1, 's'); - } - return __seconds; -} - -template -basic_string<_CharT> -__get_unit(bool __is_long, const basic_string<_CharT>&, - const basic_string<_CharT>& __minutes, - const basic_string<_CharT>&, ratio<60>) -{ - if (__minutes.empty()) - { - if (__is_long) - { - _CharT __p[] = {'m', 'i', 'n', 'u', 't', 'e', 's'}; - return basic_string<_CharT>(__p, __p + sizeof(__p) / sizeof(_CharT)); - } - else - return basic_string<_CharT>(1, 'm'); - } - return __minutes; -} - -template -inline -basic_string<_CharT> -__get_unit(bool __is_long, const basic_string<_CharT>&, - const basic_string<_CharT>&, - const basic_string<_CharT>& __hours, ratio<3600>) -{ - if (__hours.empty()) - { - if (__is_long) - { - _CharT __p[] = {'h', 'o', 'u', 'r', 's'}; - return basic_string<_CharT>(__p, __p + sizeof(__p) / sizeof(_CharT)); - } - else - return basic_string<_CharT>(1, 'h'); - } - return __hours; -} - -template -basic_ostream<_CharT, _Traits>& -operator<<(basic_ostream<_CharT, _Traits>& __os, const duration<_Rep, _Period>& __d) -{ - typename basic_ostream<_CharT, _Traits>::sentry ok(__os); - if (ok) - { - typedef durationpunct<_CharT> _F; - typedef basic_string<_CharT> string_type; - bool failed = false; - try - { - bool __is_long = true; - string_type __seconds; - string_type __minutes; - string_type __hours; - locale __loc = __os.getloc(); - if (has_facet<_F>(__loc)) - { - const _F& f = use_facet<_F>(__loc); - __is_long = f.is_long_name(); - __seconds = f.seconds(); - __minutes = f.minutes(); - __hours = f.hours(); - } - string_type __unit = __get_unit(__is_long, __seconds, __minutes, - __hours, typename _Period::type()); - __os << __d.count() << ' ' << __unit; - } - catch (...) - { - failed = true; - } - if (failed) - __os.setstate(ios_base::failbit | ios_base::badbit); - } - return __os; -} - -template ::value> -struct __duration_io_intermediate -{ - typedef _Rep type; -}; - -template -struct __duration_io_intermediate<_Rep, true> -{ - typedef typename conditional - < - is_floating_point<_Rep>::value, - long double, - typename conditional - < - is_signed<_Rep>::value, - long long, - unsigned long long - >::type - >::type type; -}; - -template -T -__gcd(T x, T y) -{ - while (y != 0) - { - T old_x = x; - x = y; - y = old_x % y; - } - return x; -} - -template <> -long double -inline -__gcd(long double x, long double y) -{ - (void)x; - (void)y; - return 1; -} - -template -basic_istream<_CharT, _Traits>& -operator>>(basic_istream<_CharT, _Traits>& __is, duration<_Rep, _Period>& __d) -{ - typedef basic_string<_CharT> string_type; - typedef durationpunct<_CharT> _F; - typedef typename __duration_io_intermediate<_Rep>::type _IR; - _IR __r; - // read value into __r - __is >> __r; - if (__is.good()) - { - // now determine unit - typedef istreambuf_iterator<_CharT, _Traits> _I; - _I __i(__is); - _I __e; - if (__i != __e && *__i == ' ') // mandatory ' ' after value - { - ++__i; - if (__i != __e) - { - string_type __seconds; - string_type __minutes; - string_type __hours; - locale __loc = __is.getloc(); - if (has_facet<_F>(__loc)) - { - const _F& f = use_facet<_F>(__loc); - __seconds = f.seconds(); - __minutes = f.minutes(); - __hours = f.hours(); - } - // unit is num / den (yet to be determined) - unsigned long long num = 0; - unsigned long long den = 0; - if (*__i == '[') - { - // parse [N/D]s or [N/D]seconds format - ++__i; - _CharT __x; - __is >> num >> __x >> den; - if (!__is.good() || __x != '/') - { - __is.setstate(__is.failbit); - return __is; - } - __i = _I(__is); - if (*__i != ']') - { - __is.setstate(__is.failbit); - return __is; - } - ++__i; - const basic_string<_CharT> __units[] = - { - __get_unit(true, __seconds, __minutes, __hours, ratio<1>()), - __get_unit(false, __seconds, __minutes, __hours, ratio<1>()) - }; - ios_base::iostate __err = ios_base::goodbit; - const basic_string<_CharT>* __k = __scan_keyword(__i, __e, - __units, __units + sizeof(__units)/sizeof(__units[0]), - use_facet >(__loc), - __err); - switch ((__k - __units) / 2) - { - case 0: - break; - default: - __is.setstate(__err); - return __is; - } - } - else - { - // parse SI name, short or long - const basic_string<_CharT> __units[] = - { - __get_unit(true, __seconds, __minutes, __hours, atto()), - __get_unit(false, __seconds, __minutes, __hours, atto()), - __get_unit(true, __seconds, __minutes, __hours, femto()), - __get_unit(false, __seconds, __minutes, __hours, femto()), - __get_unit(true, __seconds, __minutes, __hours, pico()), - __get_unit(false, __seconds, __minutes, __hours, pico()), - __get_unit(true, __seconds, __minutes, __hours, nano()), - __get_unit(false, __seconds, __minutes, __hours, nano()), - __get_unit(true, __seconds, __minutes, __hours, micro()), - __get_unit(false, __seconds, __minutes, __hours, micro()), - __get_unit(true, __seconds, __minutes, __hours, milli()), - __get_unit(false, __seconds, __minutes, __hours, milli()), - __get_unit(true, __seconds, __minutes, __hours, centi()), - __get_unit(false, __seconds, __minutes, __hours, centi()), - __get_unit(true, __seconds, __minutes, __hours, deci()), - __get_unit(false, __seconds, __minutes, __hours, deci()), - __get_unit(true, __seconds, __minutes, __hours, deca()), - __get_unit(false, __seconds, __minutes, __hours, deca()), - __get_unit(true, __seconds, __minutes, __hours, hecto()), - __get_unit(false, __seconds, __minutes, __hours, hecto()), - __get_unit(true, __seconds, __minutes, __hours, kilo()), - __get_unit(false, __seconds, __minutes, __hours, kilo()), - __get_unit(true, __seconds, __minutes, __hours, mega()), - __get_unit(false, __seconds, __minutes, __hours, mega()), - __get_unit(true, __seconds, __minutes, __hours, giga()), - __get_unit(false, __seconds, __minutes, __hours, giga()), - __get_unit(true, __seconds, __minutes, __hours, tera()), - __get_unit(false, __seconds, __minutes, __hours, tera()), - __get_unit(true, __seconds, __minutes, __hours, peta()), - __get_unit(false, __seconds, __minutes, __hours, peta()), - __get_unit(true, __seconds, __minutes, __hours, exa()), - __get_unit(false, __seconds, __minutes, __hours, exa()), - __get_unit(true, __seconds, __minutes, __hours, ratio<1>()), - __get_unit(false, __seconds, __minutes, __hours, ratio<1>()), - __get_unit(true, __seconds, __minutes, __hours, ratio<60>()), - __get_unit(false, __seconds, __minutes, __hours, ratio<60>()), - __get_unit(true, __seconds, __minutes, __hours, ratio<3600>()), - __get_unit(false, __seconds, __minutes, __hours, ratio<3600>()) - }; - ios_base::iostate __err = ios_base::goodbit; - const basic_string<_CharT>* __k = __scan_keyword(__i, __e, - __units, __units + sizeof(__units)/sizeof(__units[0]), - use_facet >(__loc), - __err); - switch ((__k - __units) / 2) - { - case 0: - num = 1ULL; - den = 1000000000000000000ULL; - break; - case 1: - num = 1ULL; - den = 1000000000000000ULL; - break; - case 2: - num = 1ULL; - den = 1000000000000ULL; - break; - case 3: - num = 1ULL; - den = 1000000000ULL; - break; - case 4: - num = 1ULL; - den = 1000000ULL; - break; - case 5: - num = 1ULL; - den = 1000ULL; - break; - case 6: - num = 1ULL; - den = 100ULL; - break; - case 7: - num = 1ULL; - den = 10ULL; - break; - case 8: - num = 10ULL; - den = 1ULL; - break; - case 9: - num = 100ULL; - den = 1ULL; - break; - case 10: - num = 1000ULL; - den = 1ULL; - break; - case 11: - num = 1000000ULL; - den = 1ULL; - break; - case 12: - num = 1000000000ULL; - den = 1ULL; - break; - case 13: - num = 1000000000000ULL; - den = 1ULL; - break; - case 14: - num = 1000000000000000ULL; - den = 1ULL; - break; - case 15: - num = 1000000000000000000ULL; - den = 1ULL; - break; - case 16: - num = 1; - den = 1; - break; - case 17: - num = 60; - den = 1; - break; - case 18: - num = 3600; - den = 1; - break; - default: - __is.setstate(__err); - return __is; - } - } - // unit is num/den - // __r should be multiplied by (num/den) / _Period - // Reduce (num/den) / _Period to lowest terms - unsigned long long __gcd_n1_n2 = __gcd(num, _Period::num); - unsigned long long __gcd_d1_d2 = __gcd(den, _Period::den); - num /= __gcd_n1_n2; - den /= __gcd_d1_d2; - unsigned long long __n2 = _Period::num / __gcd_n1_n2; - unsigned long long __d2 = _Period::den / __gcd_d1_d2; - if (num > numeric_limits::max() / __d2 || - den > numeric_limits::max() / __n2) - { - // (num/den) / _Period overflows - __is.setstate(__is.failbit); - return __is; - } - num *= __d2; - den *= __n2; - // num / den is now factor to multiply by __r - typedef typename common_type<_IR, unsigned long long>::type _CT; - if (is_integral<_IR>::value) - { - // Reduce __r * num / den - _CT __t = __gcd<_CT>(__r, den); - __r /= __t; - den /= __t; - if (den != 1) - { - // Conversion to _Period is integral and not exact - __is.setstate(__is.failbit); - return __is; - } - } - if (__r > duration_values<_CT>::max() / num) - { - // Conversion to _Period overflowed - __is.setstate(__is.failbit); - return __is; - } - _CT __t = __r * num; - __t /= den; - if (duration_values<_Rep>::max() < __t) - { - // Conversion to _Period overflowed - __is.setstate(__is.failbit); - return __is; - } - // Success! Store it. - __r = _Rep(__t); - __d = duration<_Rep, _Period>(__r); - } - else - __is.setstate(__is.failbit | __is.eofbit); - } - else - { - if (__i == __e) - __is.setstate(__is.eofbit); - __is.setstate(__is.failbit); - } - } - else - __is.setstate(__is.failbit); - return __is; -} - -template -class timepunct - : public std::locale::facet -{ -public: - typedef std::basic_string string_type; - -private: - string_type fmt_; - bool local_; - -public: - static std::locale::id id; - - explicit timepunct(std::size_t refs = 0, - const string_type& fmt = string_type(), - bool local = false) - : std::locale::facet(refs), - fmt_(fmt), - local_(local) {} - - explicit timepunct(std::size_t refs, - string_type&& fmt, - bool local = false) - : std::locale::facet(refs), - fmt_(std::move(fmt)), - local_(local) {} - - const string_type& fmt() const {return fmt_;} - bool local() const {return local_;} -}; - -template -std::locale::id -timepunct::id; - -template -basic_ostream<_CharT, _Traits>& -operator<<(basic_ostream<_CharT, _Traits>& __os, - const time_point& __tp) -{ - return __os << __tp.time_since_epoch() << " since boot"; -} - -template -struct __time_manip -{ - std::basic_string fmt_; - bool local_; - - __time_manip(std::basic_string fmt, bool local) - : fmt_(std::move(fmt)), - local_(local) {} -}; - -template -std::basic_ostream& -operator <<(std::basic_ostream& os, __time_manip m) -{ - os.imbue(std::locale(os.getloc(), new timepunct(0, std::move(m.fmt_), m.local_))); - return os; -} - -template -std::basic_istream& -operator >>(std::basic_istream& is, __time_manip m) -{ - is.imbue(std::locale(is.getloc(), new timepunct(0, std::move(m.fmt_), m.local_))); - return is; -} - -template -inline -__time_manip -local_fmt(std::basic_string fmt) -{ - return __time_manip(std::move(fmt), true); -} - -template -inline -__time_manip -local_fmt(const charT* fmt) -{ - return __time_manip(fmt, true); -} - -inline -__time_manip -local_fmt() -{ - return __time_manip("", true); -} - -template -inline -__time_manip -utc_fmt(std::basic_string fmt) -{ - return __time_manip(std::move(fmt), false); -} - -template -inline -__time_manip -utc_fmt(const charT* fmt) -{ - return __time_manip(fmt, false); -} - -inline -__time_manip -utc_fmt() -{ - return __time_manip("", false); -} - -class __time_man -{ - int form_; -public: - explicit __time_man(int f) : form_(f) {} - // explicit - operator int() const {return form_;} -}; - -template -std::basic_ostream& -operator <<(std::basic_ostream& os, __time_man m) -{ - os.imbue(std::locale(os.getloc(), new timepunct(0, basic_string(), m == local))); - return os; -} - -template -std::basic_istream& -operator >>(std::basic_istream& is, __time_man m) -{ - is.imbue(std::locale(is.getloc(), new timepunct(0, basic_string(), m == local))); - return is; -} - - -inline -__time_man -time_fmt(int f) -{ - return __time_man(f); -} - -template -basic_istream<_CharT, _Traits>& -operator>>(basic_istream<_CharT, _Traits>& __is, - time_point& __tp) -{ - _Duration __d; - __is >> __d; - if (__is.good()) - { - const _CharT __u[] = {' ', 's', 'i', 'n', 'c', 'e', ' ', 'b', 'o', 'o', 't'}; - const basic_string<_CharT> __units(__u, __u + sizeof(__u)/sizeof(__u[0])); - ios_base::iostate __err = ios_base::goodbit; - typedef istreambuf_iterator<_CharT, _Traits> _I; - _I __i(__is); - _I __e; - ptrdiff_t __k = __scan_keyword(__i, __e, - &__units, &__units + 1, - use_facet >(__is.getloc()), - __err) - &__units; - if (__k == 1) - { - // failed to read epoch string - __is.setstate(__err); - return __is; - } - __tp = time_point(__d); - } - else - __is.setstate(__is.failbit); - return __is; -} - -template -basic_ostream<_CharT, _Traits>& -operator<<(basic_ostream<_CharT, _Traits>& __os, - const time_point& __tp) -{ - typename basic_ostream<_CharT, _Traits>::sentry ok(__os); - if (ok) - { - bool failed = false; - try - { - const _CharT* pb = nullptr; - const _CharT* pe = pb; - bool __local = false; - typedef timepunct<_CharT> F; - locale loc = __os.getloc(); - if (has_facet(loc)) - { - const F& f = use_facet(loc); - pb = f.fmt().data(); - pe = pb + f.fmt().size(); - __local = f.local(); - } - time_t __t = system_clock::to_time_t(__tp); - tm __tm; - if (__local) - { - if (localtime_r(&__t, &__tm) == 0) - failed = true; - } - else - { - if (gmtime_r(&__t, &__tm) == 0) - failed = true; - } - if (!failed) - { - const time_put<_CharT>& tp = use_facet >(loc); - if (pb == pe) - { - _CharT pattern[] = {'%', 'F', ' ', '%', 'H', ':', '%', 'M', ':'}; - pb = pattern; - pe = pb + sizeof(pattern) / sizeof(_CharT); - failed = tp.put(__os, __os, __os.fill(), &__tm, pb, pe).failed(); - if (!failed) - { - duration __d = __tp - system_clock::from_time_t(__t) + - seconds(__tm.tm_sec); - if (__d.count() < 10) - __os << _CharT('0'); - ios::fmtflags __flgs = __os.flags(); - __os.setf(ios::fixed, ios::floatfield); - __os << __d.count(); - __os.flags(__flgs); - if (__local) - { - _CharT sub_pattern[] = {' ', '%', 'z'}; - pb = sub_pattern; - pe = pb + + sizeof(sub_pattern) / sizeof(_CharT); - failed = tp.put(__os, __os, __os.fill(), &__tm, pb, pe).failed(); - } - else - { - _CharT sub_pattern[] = {' ', '+', '0', '0', '0', '0', 0}; - __os << sub_pattern; - } - } - } - else - failed = tp.put(__os, __os, __os.fill(), &__tm, pb, pe).failed(); - } - } - catch (...) - { - failed = true; - } - if (failed) - __os.setstate(ios_base::failbit | ios_base::badbit); - } - return __os; -} - -template -basic_istream<_CharT, _Traits>& -operator>>(basic_istream<_CharT, _Traits>& __is, - time_point& __tp) -{ - typename basic_istream<_CharT,_Traits>::sentry ok(__is); - if (ok) - { - ios_base::iostate err = ios_base::goodbit; - try - { - const _CharT* pb = nullptr; - const _CharT* pe = pb; - bool __local = false; - typedef timepunct<_CharT> F; - locale loc = __is.getloc(); - if (has_facet(loc)) - { - const F& f = use_facet(loc); - pb = f.fmt().data(); - pe = pb + f.fmt().size(); - __local = f.local(); - } - const time_get<_CharT>& tg = use_facet >(loc); - tm __tm = {0}; - if (pb == pe) - { - _CharT pattern[] = {'%', 'Y', '-', '%', 'm', '-', '%', 'd', - ' ', '%', 'H', ':', '%', 'M', ':'}; - pb = pattern; - pe = pb + sizeof(pattern) / sizeof(_CharT); - tg.get(__is, 0, __is, err, &__tm, pb, pe); - if (err & ios_base::failbit) - goto __exit; - typedef istreambuf_iterator<_CharT, _Traits> _I; - double __sec; - _CharT __c = _CharT(); - __is >> __sec; - if (__is.fail()) - { - err |= ios_base::failbit; - goto __exit; - } - _I __i(__is); - _I __eof; - __c = *__i; - if (++__i == __eof || __c != ' ') - { - err |= ios_base::failbit; - goto __exit; - } - __c = *__i; - if (++__i == __eof || (__c != '+' && __c != '-')) - { - err |= ios_base::failbit; - goto __exit; - } - int __n = __c == '-' ? 1 : -1; - __c = *__i; - if (++__i == __eof || !isdigit(__c)) - { - err |= ios_base::failbit; - goto __exit; - } - int __min = (__c - '0') * 600; - __c = *__i; - if (++__i == __eof || !isdigit(__c)) - { - err |= ios_base::failbit; - goto __exit; - } - __min += (__c - '0') * 60; - __c = *__i; - if (++__i == __eof || !isdigit(__c)) - { - err |= ios_base::failbit; - goto __exit; - } - __min += (__c - '0') * 10; - __c = *__i; - if (!isdigit(__c)) - { - err |= ios_base::failbit; - goto __exit; - } - ++__i; - __min += __c - '0'; - __min *= __n; - time_t __t; - __t = timegm(&__tm); - __tp = system_clock::from_time_t(__t) + minutes(__min) - + round(duration(__sec)); - } - else - { - tg.get(__is, 0, __is, err, &__tm, pb, pe); - } - } - catch (...) - { - err |= ios_base::badbit | ios_base::failbit; - } - __exit: - __is.setstate(err); - } - return __is; -} - -} // chrono - -} - -#endif // _CHRONO_IO diff --git a/chrono_io/ratio_io b/chrono_io/ratio_io deleted file mode 100644 index ade52376c..000000000 --- a/chrono_io/ratio_io +++ /dev/null @@ -1,601 +0,0 @@ -// ratio_io -// -// (C) Copyright Howard Hinnant -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). - -#ifndef _RATIO_IO -#define _RATIO_IO - -/* - - ratio_io synopsis - -#include -#include - -namespace std -{ - -template -struct ratio_string -{ - static basic_string symbol(); - static basic_string prefix(); -}; - -} // std - -*/ - -#include -#include -#include - -namespace std { - -template -struct ratio_string -{ - static basic_string<_CharT> symbol() {return prefix();} - static basic_string<_CharT> prefix(); -}; - -template -basic_string<_CharT> -ratio_string<_Ratio, _CharT>::prefix() -{ - basic_ostringstream<_CharT> __os; - __os << _CharT('[') << _Ratio::num << _CharT('/') - << _Ratio::den << _CharT(']'); - return __os.str(); -} - -// atto - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'a');} - static string prefix() {return string("atto");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'a');} - static u16string prefix() {return u16string(u"atto");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'a');} - static u32string prefix() {return u32string(U"atto");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'a');} - static wstring prefix() {return wstring(L"atto");} -}; - -// femto - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'f');} - static string prefix() {return string("femto");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'f');} - static u16string prefix() {return u16string(u"femto");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'f');} - static u32string prefix() {return u32string(U"femto");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'f');} - static wstring prefix() {return wstring(L"femto");} -}; - -// pico - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'p');} - static string prefix() {return string("pico");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'p');} - static u16string prefix() {return u16string(u"pico");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'p');} - static u32string prefix() {return u32string(U"pico");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'p');} - static wstring prefix() {return wstring(L"pico");} -}; - -// nano - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'n');} - static string prefix() {return string("nano");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'n');} - static u16string prefix() {return u16string(u"nano");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'n');} - static u32string prefix() {return u32string(U"nano");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'n');} - static wstring prefix() {return wstring(L"nano");} -}; - -// micro - -template <> -struct ratio_string -{ - static string symbol() {return string("\xC2\xB5");} - static string prefix() {return string("micro");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'\xB5');} - static u16string prefix() {return u16string(u"micro");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'\xB5');} - static u32string prefix() {return u32string(U"micro");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'\xB5');} - static wstring prefix() {return wstring(L"micro");} -}; - -// milli - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'm');} - static string prefix() {return string("milli");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'm');} - static u16string prefix() {return u16string(u"milli");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'm');} - static u32string prefix() {return u32string(U"milli");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'm');} - static wstring prefix() {return wstring(L"milli");} -}; - -// centi - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'c');} - static string prefix() {return string("centi");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'c');} - static u16string prefix() {return u16string(u"centi");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'c');} - static u32string prefix() {return u32string(U"centi");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'c');} - static wstring prefix() {return wstring(L"centi");} -}; - -// deci - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'd');} - static string prefix() {return string("deci");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'd');} - static u16string prefix() {return u16string(u"deci");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'd');} - static u32string prefix() {return u32string(U"deci");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'd');} - static wstring prefix() {return wstring(L"deci");} -}; - -// deca - -template <> -struct ratio_string -{ - static string symbol() {return string("da");} - static string prefix() {return string("deca");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(u"da");} - static u16string prefix() {return u16string(u"deca");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(U"da");} - static u32string prefix() {return u32string(U"deca");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(L"da");} - static wstring prefix() {return wstring(L"deca");} -}; - -// hecto - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'h');} - static string prefix() {return string("hecto");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'h');} - static u16string prefix() {return u16string(u"hecto");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'h');} - static u32string prefix() {return u32string(U"hecto");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'h');} - static wstring prefix() {return wstring(L"hecto");} -}; - -// kilo - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'k');} - static string prefix() {return string("kilo");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'k');} - static u16string prefix() {return u16string(u"kilo");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'k');} - static u32string prefix() {return u32string(U"kilo");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'k');} - static wstring prefix() {return wstring(L"kilo");} -}; - -// mega - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'M');} - static string prefix() {return string("mega");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'M');} - static u16string prefix() {return u16string(u"mega");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'M');} - static u32string prefix() {return u32string(U"mega");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'M');} - static wstring prefix() {return wstring(L"mega");} -}; - -// giga - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'G');} - static string prefix() {return string("giga");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'G');} - static u16string prefix() {return u16string(u"giga");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'G');} - static u32string prefix() {return u32string(U"giga");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'G');} - static wstring prefix() {return wstring(L"giga");} -}; - -// tera - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'T');} - static string prefix() {return string("tera");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'T');} - static u16string prefix() {return u16string(u"tera");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'T');} - static u32string prefix() {return u32string(U"tera");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'T');} - static wstring prefix() {return wstring(L"tera");} -}; - -// peta - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'P');} - static string prefix() {return string("peta");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'P');} - static u16string prefix() {return u16string(u"peta");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'P');} - static u32string prefix() {return u32string(U"peta");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'P');} - static wstring prefix() {return wstring(L"peta");} -}; - -// exa - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'E');} - static string prefix() {return string("exa");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'E');} - static u16string prefix() {return u16string(u"exa");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'E');} - static u32string prefix() {return u32string(U"exa");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'E');} - static wstring prefix() {return wstring(L"exa");} -}; - -} - -#endif // _RATIO_IO diff --git a/libdevcore/Common.cpp b/libdevcore/Common.cpp index 07e92f542..cf6bf44c4 100644 --- a/libdevcore/Common.cpp +++ b/libdevcore/Common.cpp @@ -27,7 +27,7 @@ using namespace dev; namespace dev { -char const* Version = "0.9.0"; +char const* Version = "0.9.1"; } diff --git a/libdevcore/CommonIO.h b/libdevcore/CommonIO.h index 314600e43..f42f449bb 100644 --- a/libdevcore/CommonIO.h +++ b/libdevcore/CommonIO.h @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include "Common.h" #include "Base64.h" @@ -76,6 +76,27 @@ template inline std::ostream& operator<<(std::ostream& _out, template inline std::ostream& operator<<(std::ostream& _out, std::multimap const& _e); template _S& operator<<(_S& _out, std::shared_ptr<_T> const& _p); +template inline std::string toString(std::chrono::time_point const& _e, std::string _format = "") +{ + unsigned long milliSecondsSinceEpoch = std::chrono::duration_cast(_e.time_since_epoch()).count(); + auto const durationSinceEpoch = std::chrono::milliseconds(milliSecondsSinceEpoch); + std::chrono::time_point const tpAfterDuration(durationSinceEpoch); + + tm timeValue; + auto time = std::chrono::system_clock::to_time_t(tpAfterDuration); +#ifdef _WIN32 + gmtime_s(&timeValue, &time); +#else + gmtime_r(&time, &timeValue); +#endif + + unsigned const millisRemainder = milliSecondsSinceEpoch % 1000; + char buffer[1024]; + if (strftime(buffer, sizeof(buffer), _format.c_str(), &timeValue)) + return std::string(buffer) + "." + (millisRemainder < 1 ? "000" : millisRemainder < 10 ? "00" : millisRemainder < 100 ? "0" : "") + std::to_string(millisRemainder) + "Z"; + return std::string(); +} + template inline S& streamout(S& _out, std::vector const& _e) { diff --git a/libdevcore/CommonJS.cpp b/libdevcore/CommonJS.cpp index f173e779e..262944b65 100644 --- a/libdevcore/CommonJS.cpp +++ b/libdevcore/CommonJS.cpp @@ -23,15 +23,17 @@ #include "CommonJS.h" +using namespace std; + namespace dev { -bytes jsToBytes(std::string const& _s) +bytes jsToBytes(string const& _s) { if (_s.substr(0, 2) == "0x") // Hex return fromHex(_s.substr(2)); - else if (_s.find_first_not_of("0123456789") == std::string::npos) + else if (_s.find_first_not_of("0123456789") == string::npos) // Decimal return toCompactBigEndian(bigint(_s)); else @@ -42,7 +44,7 @@ bytes padded(bytes _b, unsigned _l) { while (_b.size() < _l) _b.insert(_b.begin(), 0); - return asBytes(asString(_b).substr(_b.size() - std::max(_l, _l))); + return asBytes(asString(_b).substr(_b.size() - max(_l, _l))); } bytes paddedRight(bytes _b, unsigned _l) @@ -54,7 +56,7 @@ bytes paddedRight(bytes _b, unsigned _l) bytes unpadded(bytes _b) { auto p = asString(_b).find_last_not_of((char)0); - _b.resize(p == std::string::npos ? 0 : (p + 1)); + _b.resize(p == string::npos ? 0 : (p + 1)); return _b; } @@ -72,18 +74,18 @@ bytes unpadLeft(bytes _b) return _b; } -std::string fromRaw(h256 _n, unsigned* _inc) +string fromRaw(h256 _n, unsigned* _inc) { if (_n) { - std::string s((char const*)_n.data(), 32); + string s((char const*)_n.data(), 32); auto l = s.find_first_of('\0'); if (!l) return ""; - if (l != std::string::npos) + if (l != string::npos) { auto p = s.find_first_not_of('\0', l); - if (!(p == std::string::npos || (_inc && p == 31))) + if (!(p == string::npos || (_inc && p == 31))) return ""; if (_inc) *_inc = (byte)s[31]; diff --git a/libdevcore/CommonJS.h b/libdevcore/CommonJS.h index d3e8e6daa..cc487d54c 100644 --- a/libdevcore/CommonJS.h +++ b/libdevcore/CommonJS.h @@ -38,12 +38,21 @@ template std::string toJS(FixedHash const& _h) template std::string toJS(boost::multiprecision::number> const& _n) { - return "0x" + toHex(toCompactBigEndian(_n)); + return "0x" + toHex(toCompactBigEndian(_n, 1)); } -inline std::string toJS(dev::bytes const& _n) +inline std::string toJS(bytes const& _n, std::size_t _padding = 0) { - return "0x" + dev::toHex(_n); + bytes n = _n; + n.resize(std::max(n.size(), _padding)); + return "0x" + toHex(n); +} + +template< typename T >std::string toJS( T const& i ) +{ + std::stringstream stream; + stream << "0x" << std::hex << i; + return stream.str(); } /// Convert string to byte array. Input parameters can be hex or dec. Returns empty array if invalid input e.g neither dec or hex. @@ -74,7 +83,7 @@ template FixedHash jsToFixed(std::string const& _s) inline std::string jsToFixed(double _s) { - return toJS(dev::u256(_s * (double)(dev::u256(1) << 128))); + return toJS(u256(_s * (double)(u256(1) << 128))); } template boost::multiprecision::number> jsToInt(std::string const& _s) @@ -92,25 +101,16 @@ template boost::multiprecision::number(_s); } -inline std::string jsToDecimal(std::string const& _s) +inline int jsToInt(std::string const& _s) { - return dev::toString(jsToU256(_s)); + if (_s.size() > 2 && _s.substr(0, 2).compare("0x") == 0) + return std::stoi(_s, nullptr, 16); + return std::stoi(_s, nullptr, 10); } -inline std::string jsFromBinary(dev::bytes _s, unsigned _padding = 32) -{ - _s.resize(std::max(_s.size(), _padding)); - return "0x" + dev::toHex(_s); -} - -inline std::string jsFromBinary(std::string const& _s, unsigned _padding = 32) -{ - return jsFromBinary(asBytes(_s), _padding); -} - -inline double jsFromFixed(std::string const& _s) +inline std::string jsToDecimal(std::string const& _s) { - return (double)jsToU256(_s) / (double)(dev::u256(1) << 128); + return toString(jsToU256(_s)); } } diff --git a/libdevcore/FixedHash.h b/libdevcore/FixedHash.h index bbc40e66c..f5469ada8 100644 --- a/libdevcore/FixedHash.h +++ b/libdevcore/FixedHash.h @@ -87,6 +87,8 @@ public: bool operator!=(FixedHash const& _c) const { return m_data != _c.m_data; } bool operator<(FixedHash const& _c) const { for (unsigned i = 0; i < N; ++i) if (m_data[i] < _c.m_data[i]) return true; else if (m_data[i] > _c.m_data[i]) return false; return false; } bool operator>=(FixedHash const& _c) const { return !operator<(_c); } + bool operator<=(FixedHash const& _c) const { return operator==(_c) || operator<(_c); } + bool operator>(FixedHash const& _c) const { return !operator<=(_c); } // The obvious binary operators. FixedHash& operator^=(FixedHash const& _c) { for (unsigned i = 0; i < N; ++i) m_data[i] ^= _c.m_data[i]; return *this; } diff --git a/libethash/ethash.h b/libethash/ethash.h index 918a77413..b96e6347d 100644 --- a/libethash/ethash.h +++ b/libethash/ethash.h @@ -25,6 +25,17 @@ #include #include "compiler.h" +#define ETHASH_REVISION 19 +#define ETHASH_DAGSIZE_BYTES_INIT 1073741824U // 2**30 +#define ETHASH_DAG_GROWTH 113000000U +#define ETHASH_EPOCH_LENGTH 30000U +#define ETHASH_MIX_BYTES 128 +#define ETHASH_DAG_PARENTS 256 +#define ETHASH_CACHE_ROUNDS 3 +#define ETHASH_ACCESSES 64 + +// ********************* +// TODO: Remove once other code moved over to compliant naming scheme. #define REVISION 19 #define DAGSIZE_BYTES_INIT 1073741824U // 2**30 #define DAG_GROWTH 113000000U @@ -33,6 +44,7 @@ #define DAG_PARENTS 256 #define CACHE_ROUNDS 3 #define ACCESSES 64 +// ********************* #ifdef __cplusplus extern "C" { @@ -82,11 +94,11 @@ static inline int ethash_check_difficulty( return 1; } -int ethash_quick_check_difficulty( +void ethash_quick_hash( + uint8_t return_hash[32], const uint8_t header_hash[32], const uint64_t nonce, - const uint8_t mix_hash[32], - const uint8_t difficulty[32]); + const uint8_t mix_hash[32]); #ifdef __cplusplus } diff --git a/libethash/internal.h b/libethash/internal.h index bcbacdaa4..d77991d56 100644 --- a/libethash/internal.h +++ b/libethash/internal.h @@ -37,12 +37,6 @@ void ethash_calculate_dag_item( ethash_cache const *cache ); -void ethash_quick_hash( - uint8_t return_hash[32], - const uint8_t header_hash[32], - const uint64_t nonce, - const uint8_t mix_hash[32]); - #ifdef __cplusplus } #endif \ No newline at end of file diff --git a/libethcore/BlockInfo.cpp b/libethcore/BlockInfo.cpp index 0f37294c2..ef57264a1 100644 --- a/libethcore/BlockInfo.cpp +++ b/libethcore/BlockInfo.cpp @@ -55,12 +55,20 @@ void BlockInfo::setEmpty() gasUsed = 0; timestamp = 0; extraData.clear(); - seedHash = h256(); mixHash = h256(); nonce = Nonce(); + m_seedHash = h256(); hash = headerHash(WithNonce); } +h256 BlockInfo::seedHash() const +{ + if (!m_seedHash) + for (u256 n = number; n >= c_epochDuration; n -= c_epochDuration) + m_seedHash = sha3(m_seedHash); + return m_seedHash; +} + BlockInfo BlockInfo::fromHeader(bytesConstRef _block, Strictness _s) { BlockInfo ret; @@ -77,9 +85,9 @@ h256 BlockInfo::headerHash(IncludeNonce _n) const void BlockInfo::streamRLP(RLPStream& _s, IncludeNonce _n) const { - _s.appendList(_n == WithNonce ? 16 : 14) + _s.appendList(_n == WithNonce ? 15 : 13) << parentHash << sha3Uncles << coinbaseAddress << stateRoot << transactionsRoot << receiptsRoot << logBloom - << difficulty << number << gasLimit << gasUsed << timestamp << extraData << seedHash; + << difficulty << number << gasLimit << gasUsed << timestamp << extraData; if (_n == WithNonce) _s << mixHash << nonce; } @@ -109,9 +117,8 @@ void BlockInfo::populateFromHeader(RLP const& _header, Strictness _s) gasUsed = _header[field = 10].toInt(); timestamp = _header[field = 11].toInt(); extraData = _header[field = 12].toBytes(); - seedHash = _header[field = 13].toHash(RLP::VeryStrict); - mixHash = _header[field = 14].toHash(RLP::VeryStrict); - nonce = _header[field = 15].toHash(RLP::VeryStrict); + mixHash = _header[field = 13].toHash(RLP::VeryStrict); + nonce = _header[field = 14].toHash(RLP::VeryStrict); } catch (Exception const& _e) @@ -185,23 +192,18 @@ void BlockInfo::populateFromParent(BlockInfo const& _parent) stateRoot = _parent.stateRoot; parentHash = _parent.hash; number = _parent.number + 1; - gasLimit = calculateGasLimit(_parent); + gasLimit = selectGasLimit(_parent); gasUsed = 0; difficulty = calculateDifficulty(_parent); - seedHash = calculateSeedHash(_parent); } -h256 BlockInfo::calculateSeedHash(BlockInfo const& _parent) const -{ - return number % c_epochDuration == 0 ? sha3(_parent.seedHash.asBytes()) : _parent.seedHash; -} - -u256 BlockInfo::calculateGasLimit(BlockInfo const& _parent) const +u256 BlockInfo::selectGasLimit(BlockInfo const& _parent) const { if (!parentHash) return c_genesisGasLimit; else - return max(c_minGasLimit, (_parent.gasLimit * (c_gasLimitBoundDivisor - 1) + (_parent.gasUsed * 6 / 5)) / c_gasLimitBoundDivisor); + // target minimum of 3141592 + return max(max(c_minGasLimit, 3141592), (_parent.gasLimit * (c_gasLimitBoundDivisor - 1) + (_parent.gasUsed * 6 / 5)) / c_gasLimitBoundDivisor); } u256 BlockInfo::calculateDifficulty(BlockInfo const& _parent) const @@ -218,13 +220,11 @@ void BlockInfo::verifyParent(BlockInfo const& _parent) const if (difficulty != calculateDifficulty(_parent)) BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError((bigint)calculateDifficulty(_parent), (bigint)difficulty)); - if (gasLimit < _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor || + if (gasLimit < c_minGasLimit || + gasLimit < _parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor || gasLimit > _parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor) BOOST_THROW_EXCEPTION(InvalidGasLimit() << errinfo_min((bigint)_parent.gasLimit * (c_gasLimitBoundDivisor - 1) / c_gasLimitBoundDivisor) << errinfo_got((bigint)gasLimit) << errinfo_max((bigint)_parent.gasLimit * (c_gasLimitBoundDivisor + 1) / c_gasLimitBoundDivisor)); - if (seedHash != calculateSeedHash(_parent)) - BOOST_THROW_EXCEPTION(InvalidSeedHash()); - // Check timestamp is after previous timestamp. if (parentHash) { diff --git a/libethcore/BlockInfo.h b/libethcore/BlockInfo.h index 20134f059..912978ef0 100644 --- a/libethcore/BlockInfo.h +++ b/libethcore/BlockInfo.h @@ -67,6 +67,7 @@ enum Strictness struct BlockInfo { public: + // TODO: make them all private! h256 hash; ///< SHA3 hash of the block header! Not serialised (the only member not contained in a block header). h256 parentHash; h256 sha3Uncles; @@ -82,7 +83,6 @@ public: u256 timestamp; bytes extraData; h256 mixHash; - h256 seedHash; Nonce nonce; BlockInfo(); @@ -113,7 +113,6 @@ public: timestamp == _cmp.timestamp && extraData == _cmp.extraData && mixHash == _cmp.mixHash && - seedHash == _cmp.seedHash && nonce == _cmp.nonce; } bool operator!=(BlockInfo const& _cmp) const { return !operator==(_cmp); } @@ -128,19 +127,22 @@ public: void populateFromParent(BlockInfo const& parent); u256 calculateDifficulty(BlockInfo const& _parent) const; - u256 calculateGasLimit(BlockInfo const& _parent) const; - h256 calculateSeedHash(BlockInfo const& _parent) const; + u256 selectGasLimit(BlockInfo const& _parent) const; + h256 seedHash() const; /// sha3 of the header only. h256 headerHash(IncludeNonce _n) const; void streamRLP(RLPStream& _s, IncludeNonce _n) const; + +private: + mutable h256 m_seedHash; }; inline std::ostream& operator<<(std::ostream& _out, BlockInfo const& _bi) { _out << _bi.hash << " " << _bi.parentHash << " " << _bi.sha3Uncles << " " << _bi.coinbaseAddress << " " << _bi.stateRoot << " " << _bi.transactionsRoot << " " << _bi.receiptsRoot << " " << _bi.logBloom << " " << _bi.difficulty << " " << _bi.number << " " << _bi.gasLimit << " " << - _bi.gasUsed << " " << _bi.timestamp << " " << _bi.mixHash << " " << _bi.seedHash << " " << _bi.nonce; + _bi.gasUsed << " " << _bi.timestamp << " " << _bi.mixHash << " " << _bi.nonce << " (" << _bi.seedHash() << ")"; return _out; } diff --git a/libethcore/Common.cpp b/libethcore/Common.cpp index 8bd4ef143..76efc06a2 100644 --- a/libethcore/Common.cpp +++ b/libethcore/Common.cpp @@ -32,7 +32,7 @@ namespace dev namespace eth { -const unsigned c_protocolVersion = 56; +const unsigned c_protocolVersion = 58; const unsigned c_databaseBaseVersion = 8; #if ETH_FATDB const unsigned c_databaseVersionModifier = 1000; diff --git a/libethcore/Ethasher.cpp b/libethcore/Ethasher.cpp index a56026459..f80277cb2 100644 --- a/libethcore/Ethasher.cpp +++ b/libethcore/Ethasher.cpp @@ -25,11 +25,12 @@ #include #include #include +#include #include #include #include #include -#include +#include #include #include "BlockInfo.h" #include "Ethasher.h" @@ -43,19 +44,25 @@ Ethasher* dev::eth::Ethasher::s_this = nullptr; bytes const& Ethasher::cache(BlockInfo const& _header) { RecursiveGuard l(x_this); - if (!m_caches.count(_header.seedHash)) + if (_header.number > EPOCH_LENGTH*2048) { + std::ostringstream error; + error << "block number is too high; max is " << EPOCH_LENGTH*2048 << "(was " << _header.number << ")"; + throw std::invalid_argument( error.str() ); + } + + if (!m_caches.count(_header.seedHash())) { ethash_params p = params((unsigned)_header.number); - m_caches[_header.seedHash].resize(p.cache_size); - ethash_prep_light(m_caches[_header.seedHash].data(), &p, _header.seedHash.data()); + m_caches[_header.seedHash()].resize(p.cache_size); + ethash_prep_light(m_caches[_header.seedHash()].data(), &p, _header.seedHash().data()); } - return m_caches[_header.seedHash]; + return m_caches[_header.seedHash()]; } bytesConstRef Ethasher::full(BlockInfo const& _header) { RecursiveGuard l(x_this); - if (!m_fulls.count(_header.seedHash)) + if (!m_fulls.count(_header.seedHash())) { if (!m_fulls.empty()) { @@ -65,18 +72,18 @@ bytesConstRef Ethasher::full(BlockInfo const& _header) try { boost::filesystem::create_directories(getDataDir() + "/ethashcache"); } catch (...) {} - std::string memoFile = getDataDir() + "/ethashcache/" + toHex(_header.seedHash.ref().cropped(0, 4)) + ".full"; - m_fulls[_header.seedHash] = contentsNew(memoFile); - if (!m_fulls[_header.seedHash]) + std::string memoFile = getDataDir() + "/ethashcache/" + toHex(_header.seedHash().ref().cropped(0, 4)) + ".full"; + m_fulls[_header.seedHash()] = contentsNew(memoFile); + if (!m_fulls[_header.seedHash()]) { ethash_params p = params((unsigned)_header.number); - m_fulls[_header.seedHash] = bytesRef(new byte[p.full_size], p.full_size); + m_fulls[_header.seedHash()] = bytesRef(new byte[p.full_size], p.full_size); auto c = cache(_header); - ethash_prep_full(m_fulls[_header.seedHash].data(), &p, c.data()); - writeFile(memoFile, m_fulls[_header.seedHash]); + ethash_prep_full(m_fulls[_header.seedHash()].data(), &p, c.data()); + writeFile(memoFile, m_fulls[_header.seedHash()]); } } - return m_fulls[_header.seedHash]; + return m_fulls[_header.seedHash()]; } ethash_params Ethasher::params(BlockInfo const& _header) @@ -94,7 +101,19 @@ ethash_params Ethasher::params(unsigned _n) bool Ethasher::verify(BlockInfo const& _header) { - bigint boundary = (bigint(1) << 256) / _header.difficulty; + if (_header.number >= ETHASH_EPOCH_LENGTH * 2048) + return false; + h256 boundary = u256((bigint(1) << 256) / _header.difficulty); + uint8_t quickHashOut[32]; + ethash_quick_hash( + quickHashOut, + _header.headerHash(WithoutNonce).data(), + (uint64_t)(u64)_header.nonce, + _header.mixHash.data() + ); + h256 quickHashOut256 = h256(quickHashOut, h256::ConstructFromPointer); + if (quickHashOut256 > boundary) + return false; auto e = eval(_header, _header.nonce); return (u256)e.value <= boundary && e.mixHash == _header.mixHash; } @@ -106,4 +125,3 @@ Ethasher::Result Ethasher::eval(BlockInfo const& _header, Nonce const& _nonce) ethash_compute_light(&r, Ethasher::get()->cache(_header).data(), &p, _header.headerHash(WithoutNonce).data(), (uint64_t)(u64)_nonce); return Result{h256(r.result, h256::ConstructFromPointer), h256(r.mix_hash, h256::ConstructFromPointer)}; } - diff --git a/libethcore/Params.cpp b/libethcore/Params.cpp index d1154abcc..694219013 100644 --- a/libethcore/Params.cpp +++ b/libethcore/Params.cpp @@ -31,7 +31,7 @@ namespace eth u256 const c_genesisDifficulty = 131072; u256 const c_maximumExtraDataSize = 1024; u256 const c_epochDuration = 3000; -u256 const c_genesisGasLimit = 1000000; +u256 const c_genesisGasLimit = 3141592; u256 const c_minGasLimit = 125000; u256 const c_gasLimitBoundDivisor = 1024; u256 const c_minimumDifficulty = 131072; diff --git a/libethereum/BlockChain.cpp b/libethereum/BlockChain.cpp index 95bfcb015..19a16d193 100644 --- a/libethereum/BlockChain.cpp +++ b/libethereum/BlockChain.cpp @@ -65,13 +65,13 @@ std::ostream& dev::eth::operator<<(std::ostream& _out, BlockChain const& _bc) ldb::Slice dev::eth::toSlice(h256 _h, unsigned _sub) { #if ALL_COMPILERS_ARE_CPP11_COMPLIANT - static thread_local h256 h = _h ^ h256(u256(_sub)); + static thread_local h256 h = _h ^ sha3(h256(u256(_sub))); return ldb::Slice((char const*)&h, 32); #else static boost::thread_specific_ptr t_h; if (!t_h.get()) t_h.reset(new h256); - *t_h = _h ^ h256(u256(_sub)); + *t_h = _h ^ sha3(h256(u256(_sub))); return ldb::Slice((char const*)t_h.get(), 32); #endif } @@ -140,7 +140,7 @@ void BlockChain::open(std::string _path, bool _killExisting) // Insert details of genesis block. m_details[m_genesisHash] = BlockDetails(0, c_genesisDifficulty, h256(), {}); auto r = m_details[m_genesisHash].rlp(); - m_extrasDB->Put(m_writeOptions, ldb::Slice((char const*)&m_genesisHash, 32), (ldb::Slice)dev::ref(r)); + m_extrasDB->Put(m_writeOptions, toSlice(m_genesisHash, ExtraDetails), (ldb::Slice)dev::ref(r)); } checkConsistency(); @@ -324,20 +324,22 @@ h256s BlockChain::import(bytes const& _block, OverlayDB const& _db) WriteGuard l(x_blockHashes); m_blockHashes[h256(bi.number)].value = newHash; } + h256s alteredBlooms; { WriteGuard l(x_blocksBlooms); LogBloom blockBloom = bi.logBloom; - blockBloom.shiftBloom<3, 32>(sha3(bi.coinbaseAddress.ref())); + blockBloom.shiftBloom<3>(sha3(bi.coinbaseAddress.ref())); unsigned index = (unsigned)bi.number; for (unsigned level = 0; level < c_bloomIndexLevels; level++, index /= c_bloomIndexSize) { - unsigned i = index / c_bloomIndexSize % c_bloomIndexSize; + unsigned i = index / c_bloomIndexSize; unsigned o = index % c_bloomIndexSize; - m_blocksBlooms[chunkId(level, i)].blooms[o] |= blockBloom; + alteredBlooms.push_back(chunkId(level, i)); + m_blocksBlooms[alteredBlooms.back()].blooms[o] |= blockBloom; } } // Collate transaction hashes and remember who they were. - h256s tas; + h256s newTransactionAddresses; { RLP blockRLP(_block); TransactionAddress ta; @@ -345,8 +347,8 @@ h256s BlockChain::import(bytes const& _block, OverlayDB const& _db) WriteGuard l(x_transactionAddresses); for (ta.index = 0; ta.index < blockRLP[1].itemCount(); ++ta.index) { - tas.push_back(sha3(blockRLP[1][ta.index].data())); - m_transactionAddresses[tas.back()] = ta; + newTransactionAddresses.push_back(sha3(blockRLP[1][ta.index].data())); + m_transactionAddresses[newTransactionAddresses.back()] = ta; } } { @@ -369,11 +371,12 @@ h256s BlockChain::import(bytes const& _block, OverlayDB const& _db) m_extrasDB->Put(m_writeOptions, toSlice(newHash, ExtraDetails), (ldb::Slice)dev::ref(m_details[newHash].rlp())); m_extrasDB->Put(m_writeOptions, toSlice(bi.parentHash, ExtraDetails), (ldb::Slice)dev::ref(m_details[bi.parentHash].rlp())); m_extrasDB->Put(m_writeOptions, toSlice(h256(bi.number), ExtraBlockHash), (ldb::Slice)dev::ref(m_blockHashes[h256(bi.number)].rlp())); - for (auto const& h: tas) + for (auto const& h: newTransactionAddresses) m_extrasDB->Put(m_writeOptions, toSlice(h, ExtraTransactionAddress), (ldb::Slice)dev::ref(m_transactionAddresses[h].rlp())); m_extrasDB->Put(m_writeOptions, toSlice(newHash, ExtraLogBlooms), (ldb::Slice)dev::ref(m_logBlooms[newHash].rlp())); m_extrasDB->Put(m_writeOptions, toSlice(newHash, ExtraReceipts), (ldb::Slice)dev::ref(m_receipts[newHash].rlp())); - m_extrasDB->Put(m_writeOptions, toSlice(newHash, ExtraBlocksBlooms), (ldb::Slice)dev::ref(m_blocksBlooms[newHash].rlp())); + for (auto const& h: alteredBlooms) + m_extrasDB->Put(m_writeOptions, toSlice(h, ExtraBlocksBlooms), (ldb::Slice)dev::ref(m_blocksBlooms[h].rlp())); } #if ETH_PARANOIA @@ -700,7 +703,7 @@ bool BlockChain::isKnown(h256 _hash) const return true; } string d; - m_blocksDB->Get(m_readOptions, ldb::Slice((char const*)&_hash, 32), &d); + m_blocksDB->Get(m_readOptions, toSlice(_hash), &d); return !!d.size(); } @@ -717,7 +720,7 @@ bytes BlockChain::block(h256 _hash) const } string d; - m_blocksDB->Get(m_readOptions, ldb::Slice((char const*)&_hash, 32), &d); + m_blocksDB->Get(m_readOptions, toSlice(_hash), &d); if (!d.size()) { diff --git a/libethereum/BlockChain.h b/libethereum/BlockChain.h index a6760a3f6..9676b4a78 100644 --- a/libethereum/BlockChain.h +++ b/libethereum/BlockChain.h @@ -155,6 +155,7 @@ public: /// Get a transaction from its hash. Thread-safe. bytes transaction(h256 _transactionHash) const { TransactionAddress ta = queryExtras(_transactionHash, m_transactionAddresses, x_transactionAddresses, NullTransactionAddress); if (!ta) return bytes(); return transaction(ta.blockHash, ta.index); } + std::pair transactionLocation(h256 _transactionHash) const { TransactionAddress ta = queryExtras(_transactionHash, m_transactionAddresses, x_transactionAddresses, NullTransactionAddress); if (!ta) return std::pair(h256(), 0); return std::make_pair(ta.blockHash, ta.index); } /// Get a block's transaction (RLP format) for the given block hash (or the most recent mined if none given) & index. Thread-safe. bytes transaction(h256 _blockHash, unsigned _i) const { bytes b = block(_blockHash); return RLP(b)[1][_i].data().toBytes(); } diff --git a/libethereum/CanonBlockChain.cpp b/libethereum/CanonBlockChain.cpp index 569bddca1..21b30d8ef 100644 --- a/libethereum/CanonBlockChain.cpp +++ b/libethereum/CanonBlockChain.cpp @@ -85,8 +85,8 @@ bytes CanonBlockChain::createGenesisBlock() stateRoot = state.root(); } - block.appendList(16) - << h256() << EmptyListSHA3 << h160() << stateRoot << EmptyTrie << EmptyTrie << LogBloom() << c_genesisDifficulty << 0 << 1000000 << 0 << (unsigned)0 << string() << h256() << h256() << Nonce(u64(42)); + block.appendList(15) + << h256() << EmptyListSHA3 << h160() << stateRoot << EmptyTrie << EmptyTrie << LogBloom() << c_genesisDifficulty << 0 << c_genesisGasLimit << 0 << (unsigned)0 << string() << h256() << Nonce(u64(42)); block.appendRaw(RLPEmptyList); block.appendRaw(RLPEmptyList); return block.out(); diff --git a/libethereum/Client.cpp b/libethereum/Client.cpp index 165ac20ca..bd8b3da40 100644 --- a/libethereum/Client.cpp +++ b/libethereum/Client.cpp @@ -282,7 +282,7 @@ unsigned Client::installWatch(LogFilter const& _f) return installWatch(h); } -void Client::uninstallWatch(unsigned _i) +bool Client::uninstallWatch(unsigned _i) { cwatch << "XXX" << _i; @@ -290,7 +290,7 @@ void Client::uninstallWatch(unsigned _i) auto it = m_watches.find(_i); if (it == m_watches.end()) - return; + return false; auto id = it->second.id; m_watches.erase(it); @@ -301,6 +301,7 @@ void Client::uninstallWatch(unsigned _i) cwatch << "*X*" << fit->first << ":" << fit->second.filter; m_filters.erase(fit); } + return true; } void Client::noteChanged(h256Set const& _filters) @@ -327,19 +328,15 @@ LocalisedLogEntries Client::peekWatch(unsigned _watchId) const { Guard l(m_filterLock); - try { #if ETH_DEBUG - cdebug << "peekWatch" << _watchId; + cdebug << "peekWatch" << _watchId; #endif - auto& w = m_watches.at(_watchId); + auto& w = m_watches.at(_watchId); #if ETH_DEBUG - cdebug << "lastPoll updated to " << chrono::duration_cast(chrono::system_clock::now().time_since_epoch()).count(); + cdebug << "lastPoll updated to " << chrono::duration_cast(chrono::system_clock::now().time_since_epoch()).count(); #endif - w.lastPoll = chrono::system_clock::now(); - return w.changes; - } catch (...) {} - - return LocalisedLogEntries(); + w.lastPoll = chrono::system_clock::now(); + return w.changes; } LocalisedLogEntries Client::checkWatch(unsigned _watchId) @@ -347,17 +344,15 @@ LocalisedLogEntries Client::checkWatch(unsigned _watchId) Guard l(m_filterLock); LocalisedLogEntries ret; - try { #if ETH_DEBUG && 0 - cdebug << "checkWatch" << _watchId; + cdebug << "checkWatch" << _watchId; #endif - auto& w = m_watches.at(_watchId); + auto& w = m_watches.at(_watchId); #if ETH_DEBUG && 0 - cdebug << "lastPoll updated to " << chrono::duration_cast(chrono::system_clock::now().time_since_epoch()).count(); + cdebug << "lastPoll updated to " << chrono::duration_cast(chrono::system_clock::now().time_since_epoch()).count(); #endif - std::swap(ret, w.changes); - w.lastPoll = chrono::system_clock::now(); - } catch (...) {} + std::swap(ret, w.changes); + w.lastPoll = chrono::system_clock::now(); return ret; } @@ -493,7 +488,7 @@ void Client::transact(Secret _secret, u256 _value, Address _dest, bytes const& _ m_tq.attemptImport(t.rlp()); } -bytes Client::call(Secret _secret, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice) +bytes Client::call(Secret _secret, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, int _blockNumber) { bytes out; try @@ -503,7 +498,7 @@ bytes Client::call(Secret _secret, u256 _value, Address _dest, bytes const& _dat // cdebug << "Nonce at " << toAddress(_secret) << " pre:" << m_preMine.transactionsFrom(toAddress(_secret)) << " post:" << m_postMine.transactionsFrom(toAddress(_secret)); { ReadGuard l(x_stateDB); - temp = m_postMine; + temp = asOf(_blockNumber); n = temp.transactionsFrom(toAddress(_secret)); } Transaction t(_value, _gasPrice, _gas, _dest, _data, n, _secret); @@ -794,6 +789,11 @@ bytes Client::codeAt(Address _a, int _block) const return asOf(_block).code(_a); } +Transaction Client::transaction(h256 _transactionHash) const +{ + return Transaction(m_bc.transaction(_transactionHash), CheckSignature::Range); +} + Transaction Client::transaction(h256 _blockHash, unsigned _i) const { auto bl = m_bc.block(_blockHash); @@ -828,6 +828,36 @@ unsigned Client::uncleCount(h256 _blockHash) const return b[2].itemCount(); } +Transactions Client::transactions(h256 _blockHash) const +{ + auto bl = m_bc.block(_blockHash); + RLP b(bl); + Transactions res; + for (unsigned i = 0; i < b[1].itemCount(); i++) + res.emplace_back(b[1][i].data(), CheckSignature::Range); + return res; +} + +TransactionHashes Client::transactionHashes(h256 _blockHash) const +{ + return m_bc.transactionHashes(_blockHash); +} + +LocalisedLogEntries Client::logs(unsigned _watchId) const +{ + LogFilter f; + try + { + Guard l(m_filterLock); + f = m_filters.at(m_watches.at(_watchId).id).filter; + } + catch (...) + { + return LocalisedLogEntries(); + } + return logs(f); +} + LocalisedLogEntries Client::logs(LogFilter const& _f) const { LocalisedLogEntries ret; diff --git a/libethereum/Client.h b/libethereum/Client.h index 2c8db2aed..cdfdcd1eb 100644 --- a/libethereum/Client.h +++ b/libethereum/Client.h @@ -225,7 +225,7 @@ public: virtual void flushTransactions(); /// Makes the given call. Nothing is recorded into the state. - virtual bytes call(Secret _secret, u256 _value, Address _dest, bytes const& _data = bytes(), u256 _gas = 10000, u256 _gasPrice = 10 * szabo); + virtual bytes call(Secret _secret, u256 _value, Address _dest, bytes const& _data = bytes(), u256 _gas = 10000, u256 _gasPrice = 10 * szabo, int _blockNumber = 0); /// Makes the given call. Nothing is recorded into the state. This cheats by creating a null address and endowing it with a lot of ETH. virtual bytes call(Address _dest, bytes const& _data = bytes(), u256 _gas = 125000, u256 _value = 0, u256 _gasPrice = 1 * ether); @@ -246,13 +246,13 @@ public: virtual bytes codeAt(Address _a, int _block) const; virtual std::map storageAt(Address _a, int _block) const; - virtual unsigned installWatch(LogFilter const& _filter); - virtual unsigned installWatch(h256 _filterId); - virtual void uninstallWatch(unsigned _watchId); + virtual unsigned installWatch(LogFilter const& _filter) override; + virtual unsigned installWatch(h256 _filterId) override; + virtual bool uninstallWatch(unsigned _watchId) override; virtual LocalisedLogEntries peekWatch(unsigned _watchId) const; virtual LocalisedLogEntries checkWatch(unsigned _watchId); - virtual LocalisedLogEntries logs(unsigned _watchId) const { try { Guard l(m_filterLock); return logs(m_filters.at(m_watches.at(_watchId).id).filter); } catch (...) { return LocalisedLogEntries(); } } + virtual LocalisedLogEntries logs(unsigned _watchId) const; virtual LocalisedLogEntries logs(LogFilter const& _filter) const; // [EXTRA API]: @@ -267,10 +267,13 @@ public: virtual h256 hashFromNumber(unsigned _number) const { return m_bc.numberHash(_number); } virtual BlockInfo blockInfo(h256 _hash) const { return BlockInfo(m_bc.block(_hash)); } virtual BlockDetails blockDetails(h256 _hash) const { return m_bc.details(_hash); } + virtual Transaction transaction(h256 _transactionHash) const; virtual Transaction transaction(h256 _blockHash, unsigned _i) const; virtual BlockInfo uncle(h256 _blockHash, unsigned _i) const; virtual unsigned transactionCount(h256 _blockHash) const; virtual unsigned uncleCount(h256 _blockHash) const; + virtual Transactions transactions(h256 _blockHash) const; + virtual TransactionHashes transactionHashes(h256 _blockHash) const; /// Differences between transactions. using Interface::diff; diff --git a/libethereum/Interface.h b/libethereum/Interface.h index 817a5e4b0..728cb5030 100644 --- a/libethereum/Interface.h +++ b/libethereum/Interface.h @@ -37,6 +37,8 @@ namespace dev namespace eth { +using TransactionHashes = h256s; + /** * @brief Main API hub for interfacing with Ethereum. */ @@ -65,7 +67,7 @@ public: virtual void flushTransactions() = 0; /// Makes the given call. Nothing is recorded into the state. - virtual bytes call(Secret _secret, u256 _value, Address _dest, bytes const& _data = bytes(), u256 _gas = 10000, u256 _gasPrice = 10 * szabo) = 0; + virtual bytes call(Secret _secret, u256 _value, Address _dest, bytes const& _data = bytes(), u256 _gas = 10000, u256 _gasPrice = 10 * szabo, int _blockNumber = 0) = 0; // [STATE-QUERY API] @@ -92,7 +94,9 @@ public: /// Install, uninstall and query watches. virtual unsigned installWatch(LogFilter const& _filter) = 0; virtual unsigned installWatch(h256 _filterId) = 0; - virtual void uninstallWatch(unsigned _watchId) = 0; + virtual bool uninstallWatch(unsigned _watchId) = 0; + LocalisedLogEntries peekWatchSafe(unsigned _watchId) const { try { return peekWatch(_watchId); } catch (...) { return LocalisedLogEntries(); } } + LocalisedLogEntries checkWatchSafe(unsigned _watchId) { try { return checkWatch(_watchId); } catch (...) { return LocalisedLogEntries(); } } virtual LocalisedLogEntries peekWatch(unsigned _watchId) const = 0; virtual LocalisedLogEntries checkWatch(unsigned _watchId) = 0; @@ -101,10 +105,13 @@ public: virtual h256 hashFromNumber(unsigned _number) const = 0; virtual BlockInfo blockInfo(h256 _hash) const = 0; virtual BlockDetails blockDetails(h256 _hash) const = 0; + virtual Transaction transaction(h256 _transactionHash) const = 0; virtual Transaction transaction(h256 _blockHash, unsigned _i) const = 0; virtual BlockInfo uncle(h256 _blockHash, unsigned _i) const = 0; virtual unsigned transactionCount(h256 _blockHash) const = 0; virtual unsigned uncleCount(h256 _blockHash) const = 0; + virtual Transactions transactions(h256 _blockHash) const = 0; + virtual TransactionHashes transactionHashes(h256 _blockHash) const = 0; // [EXTRA API]: diff --git a/libethereum/LogFilter.cpp b/libethereum/LogFilter.cpp index d1b3cf437..45716a949 100644 --- a/libethereum/LogFilter.cpp +++ b/libethereum/LogFilter.cpp @@ -79,7 +79,7 @@ vector LogFilter::bloomPossibilities() const vector ret; // TODO proper combinatorics. for (auto i: m_addresses) - ret.push_back(LogBloom().shiftBloom<3, 32>(dev::sha3(i))); + ret.push_back(LogBloom().shiftBloom<3>(dev::sha3(i))); return ret; } diff --git a/libevm/ExtVMFace.h b/libevm/ExtVMFace.h index 4c6bcad0c..79b97a252 100644 --- a/libevm/ExtVMFace.h +++ b/libevm/ExtVMFace.h @@ -47,9 +47,9 @@ struct LogEntry LogBloom bloom() const { LogBloom ret; - ret.shiftBloom<3, 32>(sha3(address.ref())); + ret.shiftBloom<3>(sha3(address.ref())); for (auto t: topics) - ret.shiftBloom<3, 32>(sha3(t.ref())); + ret.shiftBloom<3>(sha3(t.ref())); return ret; } diff --git a/libjsqrc/ethereumjs/.travis.yml b/libjsqrc/ethereumjs/.travis.yml index 558fd1537..6dcfc17d1 100644 --- a/libjsqrc/ethereumjs/.travis.yml +++ b/libjsqrc/ethereumjs/.travis.yml @@ -1,13 +1,17 @@ language: node_js node_js: + - "0.12" - "0.11" - "0.10" before_script: - npm install - npm install jshint + - export DISPLAY=:99.0 + - sh -e /etc/init.d/xvfb start script: - "jshint *.js lib" after_script: - npm run-script build + - npm run-script karma - npm run-script test-coveralls diff --git a/libjsqrc/ethereumjs/.versions b/libjsqrc/ethereumjs/.versions new file mode 100644 index 000000000..ed4a55b6a --- /dev/null +++ b/libjsqrc/ethereumjs/.versions @@ -0,0 +1,4 @@ +3stack:bignumber@2.0.0 +ethereum:js@0.0.15-rc12 +meteor@1.1.4 +underscore@1.0.2 diff --git a/libjsqrc/ethereumjs/README.md b/libjsqrc/ethereumjs/README.md index 30c20aafa..a153b89ba 100644 --- a/libjsqrc/ethereumjs/README.md +++ b/libjsqrc/ethereumjs/README.md @@ -1,57 +1,64 @@ # Ethereum JavaScript API This is the Ethereum compatible [JavaScript API](https://github.com/ethereum/wiki/wiki/JavaScript-API) -which implements the [Generic JSON RPC](https://github.com/ethereum/wiki/wiki/JSON-RPC) spec. It's available on npm as a node module and also for bower and component as an embeddable js +which implements the [Generic JSON RPC](https://github.com/ethereum/wiki/wiki/JSON-RPC) spec. It's available on npm as a node module, for bower and component as an embeddable js and as a meteor.js package. [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![dependency status][dep-image]][dep-url] [![dev dependency status][dep-dev-image]][dep-dev-url][![Coverage Status][coveralls-image]][coveralls-url] +You need to run a local ethrereum node to use this library. + +[Documentation](https://github.com/ethereum/wiki/wiki/JavaScript-API) + ## Installation ### Node.js - npm install ethereum.js + $ npm install ethereum.js + +### Meteor.js -### For browser + $ meteor add ethereum:js + +### As Browser module Bower - bower install ethereum.js + $ bower install ethereum.js Component - component install ethereum/ethereum.js + $ component install ethereum/ethereum.js -* Include `ethereum.min.js` in your html file. -* Include [bignumber.js](https://github.com/MikeMcl/bignumber.js/) +* Include `ethereum.min.js` in your html file. (not required for the meteor package) +* Include [bignumber.js](https://github.com/MikeMcl/bignumber.js/) (not required for the meteor package) ## Usage -Require the library: +Require the library (not required for the meteor package): var web3 = require('web3'); -Set a provider (QtSyncProvider, HttpSyncProvider) +Set a provider (QtSyncProvider, HttpProvider) - web3.setProvider(new web3.providers.HttpSyncProvider()); + web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545')); There you go, now you can use it: ``` var coinbase = web3.eth.coinbase; -var balance = web3.eth.balanceAt(coinbase); +var balance = web3.eth.getBalance(coinbase); ``` For another example see `example/index.html`. + ## Contribute! ### Requirements * Node.js * npm -* gulp (build) -* mocha (tests) ```bash sudo apt-get update @@ -73,6 +80,15 @@ npm run-script build npm test ``` +### Testing (karma) +Karma allows testing within one or several browsers. + +```bash +npm run-script karma # default browsers are Chrome and Firefox +npm run-script karma -- --browsers="Chrome,Safari" # custom browsers +``` + + **Please note this repo is in it's early stage.** If you'd like to run a Http ethereum node check out diff --git a/libjsqrc/ethereumjs/bower.json b/libjsqrc/ethereumjs/bower.json index f0cb33321..5fe92754b 100644 --- a/libjsqrc/ethereumjs/bower.json +++ b/libjsqrc/ethereumjs/bower.json @@ -1,7 +1,7 @@ { "name": "ethereum.js", "namespace": "ethereum", - "version": "0.0.16", + "version": "0.1.2", "description": "Ethereum Compatible JavaScript API", "main": [ "./dist/ethereum.js", @@ -33,6 +33,11 @@ "name": "Marian Oancea", "email": "marian@ethdev.com", "homepage": "https://github.com/cubedro" + }, + { + "name": "Fabian Vogelsteller", + "email": "fabian@ethdev.com", + "homepage": "https://github.com/frozeman" } ], "license": "LGPL-3.0", @@ -41,6 +46,8 @@ "lib", "node_modules", "package.json", + "package.js", + ".versions", ".bowerrc", ".editorconfig", ".gitignore", diff --git a/libjsqrc/ethereumjs/dist/ethereum.js b/libjsqrc/ethereumjs/dist/ethereum.js index 69d393699..88a5180a9 100644 --- a/libjsqrc/ethereumjs/dist/ethereum.js +++ b/libjsqrc/ethereumjs/dist/ethereum.js @@ -22,34 +22,57 @@ require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof requ * @date 2014 */ -var utils = require('./utils'); +var utils = require('../utils/utils'); +var c = require('../utils/config'); var types = require('./types'); -var c = require('./const'); var f = require('./formatters'); -var displayTypeError = function (type) { - console.error('parser does not support type: ' + type); +/** + * throw incorrect type error + * + * @method throwTypeError + * @param {String} type + * @throws incorrect type error + */ +var throwTypeError = function (type) { + throw new Error('parser does not support type: ' + type); }; -/// This method should be called if we want to check if givent type is an array type -/// @returns true if it is, otherwise false -var arrayType = function (type) { +/** This method should be called if we want to check if givent type is an array type + * + * @method isArrayType + * @param {String} type name + * @returns {Boolean} true if it is, otherwise false + */ +var isArrayType = function (type) { return type.slice(-2) === '[]'; }; +/** + * This method should be called to return dynamic type length in hex + * + * @method dynamicTypeBytes + * @param {String} type + * @param {String|Array} dynamic type + * @return {String} length of dynamic type in hex or empty string if type is not dynamic + */ var dynamicTypeBytes = function (type, value) { // TODO: decide what to do with array of strings - if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length. + if (isArrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length. return f.formatInputInt(value.length); return ""; }; var inputTypes = types.inputTypes(); -/// Formats input params to bytes -/// @param abi contract method inputs -/// @param array of params that will be formatted to bytes -/// @returns bytes representation of input params +/** + * Formats input params to bytes + * + * @method formatInput + * @param {Array} abi inputs of method + * @param {Array} params that will be formatted to bytes + * @returns bytes representation of input params + */ var formatInput = function (inputs, params) { var bytes = ""; var toAppendConstant = ""; @@ -67,12 +90,12 @@ var formatInput = function (inputs, params) { typeMatch = inputTypes[j].type(inputs[i].type, params[i]); } if (!typeMatch) { - displayTypeError(inputs[i].type); + throwTypeError(inputs[i].type); } var formatter = inputTypes[j - 1].format; - if (arrayType(inputs[i].type)) + if (isArrayType(inputs[i].type)) toAppendArrayContent += params[i].reduce(function (acc, curr) { return acc + formatter(curr); }, ""); @@ -87,18 +110,29 @@ var formatInput = function (inputs, params) { return bytes; }; +/** + * This method should be called to predict the length of dynamic type + * + * @method dynamicBytesLength + * @param {String} type + * @returns {Number} length of dynamic type, 0 or multiplication of ETH_PADDING (32) + */ var dynamicBytesLength = function (type) { - if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length. + if (isArrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length. return c.ETH_PADDING * 2; return 0; }; var outputTypes = types.outputTypes(); -/// Formats output bytes back to param list -/// @param contract abi method outputs -/// @param bytes representtion of output -/// @returns array of output params +/** + * Formats output bytes back to param list + * + * @method formatOutput + * @param {Array} abi outputs of method + * @param {String} bytes represention of output + * @returns {Array} output params + */ var formatOutput = function (outs, output) { output = output.slice(2); @@ -120,11 +154,11 @@ var formatOutput = function (outs, output) { } if (!typeMatch) { - displayTypeError(outs[i].type); + throwTypeError(outs[i].type); } var formatter = outputTypes[j - 1].format; - if (arrayType(outs[i].type)) { + if (isArrayType(outs[i].type)) { var size = f.formatOutputUInt(dynamicPart.slice(0, padding)); dynamicPart = dynamicPart.slice(padding); var array = []; @@ -147,9 +181,14 @@ var formatOutput = function (outs, output) { return result; }; -/// @param json abi for contract -/// @returns input parser object for given json abi -/// TODO: refactor creating the parser, do not double logic from contract +/** + * Should be called to create input parser for contract with given abi + * + * @method inputParser + * @param {Array} contract abi + * @returns {Object} input parser object for given json abi + * TODO: refactor creating the parser, do not double logic from contract + */ var inputParser = function (json) { var parser = {}; json.forEach(function (method) { @@ -171,8 +210,13 @@ var inputParser = function (json) { return parser; }; -/// @param json abi for contract -/// @returns output parser for given json abi +/** + * Should be called to create output parser for contract with given abi + * + * @method outputParser + * @param {Array} contract abi + * @returns {Object} output parser for given json abi + */ var outputParser = function (json) { var parser = {}; json.forEach(function (method) { @@ -201,7 +245,7 @@ module.exports = { formatOutput: formatOutput }; -},{"./const":2,"./formatters":8,"./types":15,"./utils":16}],2:[function(require,module,exports){ +},{"../utils/config":4,"../utils/utils":5,"./formatters":2,"./types":3}],2:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -218,49 +262,206 @@ module.exports = { You should have received a copy of the GNU Lesser General Public License along with ethereum.js. If not, see . */ -/** @file const.js +/** @file formatters.js * @authors: * Marek Kotewicz * @date 2015 */ -/// required to define ETH_BIGNUMBER_ROUNDING_MODE if ("build" !== 'build') {/* var BigNumber = require('bignumber.js'); // jshint ignore:line */} -var ETH_UNITS = [ - 'wei', - 'Kwei', - 'Mwei', - 'Gwei', - 'szabo', - 'finney', - 'ether', - 'grand', - 'Mether', - 'Gether', - 'Tether', - 'Pether', - 'Eether', - 'Zether', - 'Yether', - 'Nether', - 'Dether', - 'Vether', - 'Uether' -]; +var utils = require('../utils/utils'); +var c = require('../utils/config'); + +/** + * Should be called to pad string to expected length + * + * @method padLeft + * @param {String} string to be padded + * @param {Number} characters that result string should have + * @param {String} sign, by default 0 + * @returns {String} right aligned string + */ +var padLeft = function (string, chars, sign) { + return new Array(chars - string.length + 1).join(sign ? sign : "0") + string; +}; + +/** + * Formats input value to byte representation of int + * If value is negative, return it's two's complement + * If the value is floating point, round it down + * + * @method formatInputInt + * @param {String|Number|BigNumber} value that needs to be formatted + * @returns {String} right-aligned byte representation of int + */ +var formatInputInt = function (value) { + var padding = c.ETH_PADDING * 2; + BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE); + return padLeft(utils.toTwosComplement(value).round().toString(16), padding); +}; + +/** + * Formats input value to byte representation of string + * + * @method formatInputString + * @param {String} + * @returns {String} left-algined byte representation of string + */ +var formatInputString = function (value) { + return utils.fromAscii(value, c.ETH_PADDING).substr(2); +}; + +/** + * Formats input value to byte representation of bool + * + * @method formatInputBool + * @param {Boolean} + * @returns {String} right-aligned byte representation bool + */ +var formatInputBool = function (value) { + return '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0'); +}; + +/** + * Formats input value to byte representation of real + * Values are multiplied by 2^m and encoded as integers + * + * @method formatInputReal + * @param {String|Number|BigNumber} + * @returns {String} byte representation of real + */ +var formatInputReal = function (value) { + return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128))); +}; + +/** + * Check if input value is negative + * + * @method signedIsNegative + * @param {String} value is hex format + * @returns {Boolean} true if it is negative, otherwise false + */ +var signedIsNegative = function (value) { + return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1'; +}; + +/** + * Formats right-aligned output bytes to int + * + * @method formatOutputInt + * @param {String} bytes + * @returns {BigNumber} right-aligned output bytes formatted to big number + */ +var formatOutputInt = function (value) { + + value = value || "0"; + + // check if it's negative number + // it it is, return two's complement + if (signedIsNegative(value)) { + return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1); + } + return new BigNumber(value, 16); +}; + +/** + * Formats right-aligned output bytes to uint + * + * @method formatOutputUInt + * @param {String} bytes + * @returns {BigNumeber} right-aligned output bytes formatted to uint + */ +var formatOutputUInt = function (value) { + value = value || "0"; + return new BigNumber(value, 16); +}; + +/** + * Formats right-aligned output bytes to real + * + * @method formatOutputReal + * @param {String} + * @returns {BigNumber} input bytes formatted to real + */ +var formatOutputReal = function (value) { + return formatOutputInt(value).dividedBy(new BigNumber(2).pow(128)); +}; + +/** + * Formats right-aligned output bytes to ureal + * + * @method formatOutputUReal + * @param {String} + * @returns {BigNumber} input bytes formatted to ureal + */ +var formatOutputUReal = function (value) { + return formatOutputUInt(value).dividedBy(new BigNumber(2).pow(128)); +}; + +/** + * Should be used to format output hash + * + * @method formatOutputHash + * @param {String} + * @returns {String} right-aligned output bytes formatted to hex + */ +var formatOutputHash = function (value) { + return "0x" + value; +}; + +/** + * Should be used to format output bool + * + * @method formatOutputBool + * @param {String} + * @returns {Boolean} right-aligned input bytes formatted to bool + */ +var formatOutputBool = function (value) { + return value === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false; +}; + +/** + * Should be used to format output string + * + * @method formatOutputString + * @param {Sttring} left-aligned hex representation of string + * @returns {String} ascii string + */ +var formatOutputString = function (value) { + return utils.toAscii(value); +}; + +/** + * Should be used to format output address + * + * @method formatOutputAddress + * @param {String} right-aligned input bytes + * @returns {String} address + */ +var formatOutputAddress = function (value) { + return "0x" + value.slice(value.length - 40, value.length); +}; module.exports = { - ETH_PADDING: 32, - ETH_SIGNATURE_LENGTH: 4, - ETH_UNITS: ETH_UNITS, - ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN }, - ETH_POLLING_TIMEOUT: 1000 + formatInputInt: formatInputInt, + formatInputString: formatInputString, + formatInputBool: formatInputBool, + formatInputReal: formatInputReal, + formatOutputInt: formatOutputInt, + formatOutputUInt: formatOutputUInt, + formatOutputReal: formatOutputReal, + formatOutputUReal: formatOutputUReal, + formatOutputHash: formatOutputHash, + formatOutputBool: formatOutputBool, + formatOutputString: formatOutputString, + formatOutputAddress: formatOutputAddress }; -},{}],3:[function(require,module,exports){ +},{"../utils/config":4,"../utils/utils":5}],3:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -277,63 +478,957 @@ module.exports = { You should have received a copy of the GNU Lesser General Public License along with ethereum.js. If not, see . */ -/** @file contract.js +/** @file types.js * @authors: * Marek Kotewicz - * @date 2014 + * @date 2015 */ -var web3 = require('./web3'); -var abi = require('./abi'); -var utils = require('./utils'); -var eventImpl = require('./event'); -var signature = require('./signature'); +var f = require('./formatters'); -var exportNatspecGlobals = function (vars) { - // it's used byt natspec.js - // TODO: figure out better way to solve this - web3._currentContractAbi = vars.abi; - web3._currentContractAddress = vars.address; - web3._currentContractMethodName = vars.method; - web3._currentContractMethodParams = vars.params; +/// @param expected type prefix (string) +/// @returns function which checks if type has matching prefix. if yes, returns true, otherwise false +var prefixedType = function (prefix) { + return function (type) { + return type.indexOf(prefix) === 0; + }; }; -var addFunctionRelatedPropertiesToContract = function (contract) { - - contract.call = function (options) { - contract._isTransact = false; - contract._options = options; - return contract; +/// @param expected type name (string) +/// @returns function which checks if type is matching expected one. if yes, returns true, otherwise false +var namedType = function (name) { + return function (type) { + return name === type; }; +}; - contract.transact = function (options) { - contract._isTransact = true; - contract._options = options; - return contract; - }; +/// Setups input formatters for solidity types +/// @returns an array of input formatters +var inputTypes = function () { + + return [ + { type: prefixedType('uint'), format: f.formatInputInt }, + { type: prefixedType('int'), format: f.formatInputInt }, + { type: prefixedType('hash'), format: f.formatInputInt }, + { type: prefixedType('string'), format: f.formatInputString }, + { type: prefixedType('real'), format: f.formatInputReal }, + { type: prefixedType('ureal'), format: f.formatInputReal }, + { type: namedType('address'), format: f.formatInputInt }, + { type: namedType('bool'), format: f.formatInputBool } + ]; +}; - contract._options = {}; - ['gas', 'gasPrice', 'value', 'from'].forEach(function(p) { - contract[p] = function (v) { - contract._options[p] = v; - return contract; - }; - }); +/// Setups output formaters for solidity types +/// @returns an array of output formatters +var outputTypes = function () { + return [ + { type: prefixedType('uint'), format: f.formatOutputUInt }, + { type: prefixedType('int'), format: f.formatOutputInt }, + { type: prefixedType('hash'), format: f.formatOutputHash }, + { type: prefixedType('string'), format: f.formatOutputString }, + { type: prefixedType('real'), format: f.formatOutputReal }, + { type: prefixedType('ureal'), format: f.formatOutputUReal }, + { type: namedType('address'), format: f.formatOutputAddress }, + { type: namedType('bool'), format: f.formatOutputBool } + ]; }; -var addFunctionsToContract = function (contract, desc, address) { - var inputParser = abi.inputParser(desc); - var outputParser = abi.outputParser(desc); +module.exports = { + prefixedType: prefixedType, + namedType: namedType, + inputTypes: inputTypes, + outputTypes: outputTypes +}; - // create contract functions - utils.filterFunctions(desc).forEach(function (method) { - var displayName = utils.extractDisplayName(method.name); - var typeName = utils.extractTypeName(method.name); +},{"./formatters":2}],4:[function(require,module,exports){ +/* + This file is part of ethereum.js. - var impl = function () { - /*jshint maxcomplexity:7 */ + ethereum.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + ethereum.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with ethereum.js. If not, see . +*/ +/** @file config.js + * @authors: + * Marek Kotewicz + * @date 2015 + */ + +/** + * Utils + * + * @module utils + */ + +/** + * Utility functions + * + * @class [utils] config + * @constructor + */ + +/// required to define ETH_BIGNUMBER_ROUNDING_MODE +if ("build" !== 'build') {/* + var BigNumber = require('bignumber.js'); // jshint ignore:line +*/} + +var ETH_UNITS = [ + 'wei', + 'Kwei', + 'Mwei', + 'Gwei', + 'szabo', + 'finney', + 'ether', + 'grand', + 'Mether', + 'Gether', + 'Tether', + 'Pether', + 'Eether', + 'Zether', + 'Yether', + 'Nether', + 'Dether', + 'Vether', + 'Uether' +]; + +module.exports = { + ETH_PADDING: 32, + ETH_SIGNATURE_LENGTH: 4, + ETH_UNITS: ETH_UNITS, + ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN }, + ETH_POLLING_TIMEOUT: 1000, + ETH_DEFAULTBLOCK: 'latest' +}; + + +},{}],5:[function(require,module,exports){ +/* + This file is part of ethereum.js. + + ethereum.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + ethereum.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with ethereum.js. If not, see . +*/ +/** @file utils.js + * @authors: + * Marek Kotewicz + * @date 2015 + */ + +/** + * Utils + * + * @module utils + */ + +/** + * Utility functions + * + * @class [utils] utils + * @constructor + */ + +if ("build" !== 'build') {/* + var BigNumber = require('bignumber.js'); // jshint ignore:line +*/} + +var unitMap = { + 'wei': '1', + 'kwei': '1000', + 'ada': '1000', + 'mwei': '1000000', + 'babbage': '1000000', + 'gwei': '1000000000', + 'shannon': '1000000000', + 'szabo': '1000000000000', + 'finney': '1000000000000000', + 'ether': '1000000000000000000', + 'kether': '1000000000000000000000', + 'grand': '1000000000000000000000', + 'einstein': '1000000000000000000000', + 'mether': '1000000000000000000000000', + 'gether': '1000000000000000000000000000', + 'tether': '1000000000000000000000000000000' +}; + + +/** Finds first index of array element matching pattern + * + * @method findIndex + * @param {Array} + * @param {Function} pattern + * @returns {Number} index of element + */ +var findIndex = function (array, callback) { + var end = false; + var i = 0; + for (; i < array.length && !end; i++) { + end = callback(array[i]); + } + return end ? i - 1 : -1; +}; + +/** + * Should be called to get sting from it's hex representation + * + * @method toAscii + * @param {String} string in hex + * @returns {String} ascii string representation of hex value + */ +var toAscii = function(hex) { +// Find termination + var str = ""; + var i = 0, l = hex.length; + if (hex.substring(0, 2) === '0x') { + i = 2; + } + for (; i < l; i+=2) { + var code = parseInt(hex.substr(i, 2), 16); + if (code === 0) { + break; + } + + str += String.fromCharCode(code); + } + + return str; +}; + +/** + * Shold be called to get hex representation (prefixed by 0x) of ascii string + * + * @method fromAscii + * @param {String} string + * @returns {String} hex representation of input string + */ +var toHexNative = function(str) { + var hex = ""; + for(var i = 0; i < str.length; i++) { + var n = str.charCodeAt(i).toString(16); + hex += n.length < 2 ? '0' + n : n; + } + + return hex; +}; + +/** + * Shold be called to get hex representation (prefixed by 0x) of ascii string + * + * @method fromAscii + * @param {String} string + * @param {Number} optional padding + * @returns {String} hex representation of input string + */ +var fromAscii = function(str, pad) { + pad = pad === undefined ? 0 : pad; + var hex = toHexNative(str); + while (hex.length < pad*2) + hex += "00"; + return "0x" + hex; +}; + +/** + * Should be called to get display name of contract function + * + * @method extractDisplayName + * @param {String} name of function/event + * @returns {String} display name for function/event eg. multiply(uint256) -> multiply + */ +var extractDisplayName = function (name) { + var length = name.indexOf('('); + return length !== -1 ? name.substr(0, length) : name; +}; + +/// @returns overloaded part of function/event name +var extractTypeName = function (name) { + /// TODO: make it invulnerable + var length = name.indexOf('('); + return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : ""; +}; + +/** + * Filters all functions from input abi + * + * @method filterFunctions + * @param {Array} abi + * @returns {Array} abi array with filtered objects of type 'function' + */ +var filterFunctions = function (json) { + return json.filter(function (current) { + return current.type === 'function'; + }); +}; + +/** + * Filters all events from input abi + * + * @method filterEvents + * @param {Array} abi + * @returns {Array} abi array with filtered objects of type 'event' + */ +var filterEvents = function (json) { + return json.filter(function (current) { + return current.type === 'event'; + }); +}; + +/** + * Converts value to it's decimal representation in string + * + * @method toDecimal + * @param {String|Number|BigNumber} + * @return {String} + */ +var toDecimal = function (value) { + return toBigNumber(value).toNumber(); +}; + +/** + * Converts value to it's hex representation + * + * @method fromDecimal + * @param {String|Number|BigNumber} + * @return {String} + */ +var fromDecimal = function (value) { + var number = toBigNumber(value); + var result = number.toString(16); + + return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result; +}; + +/** + * Auto converts any given value into it's hex representation. + * + * And even stringifys objects before. + * + * @method toHex + * @param {String|Number|BigNumber|Object} + * @return {String} + */ +var toHex = function (val) { + /*jshint maxcomplexity:7 */ + + if(isBoolean(val)) + return val; + + if(isBigNumber(val)) + return fromDecimal(val); + + if(isObject(val)) + return fromAscii(JSON.stringify(val)); + + // if its a negative number, pass it through fromDecimal + if (isString(val)) { + if (val.indexOf('-0x') === 0) + return fromDecimal(val); + else if (!isFinite(val)) + return fromAscii(val); + } + + return fromDecimal(val); +}; + +/** + * Returns value of unit in Wei + * + * @method getValueOfUnit + * @param {String} unit the unit to convert to, default ether + * @returns {BigNumber} value of the unit (in Wei) + * @throws error if the unit is not correct:w + */ +var getValueOfUnit = function (unit) { + unit = unit ? unit.toLowerCase() : 'ether'; + var unitValue = unitMap[unit]; + if (unitValue === undefined) { + throw new Error('This unit doesn\'t exists, please use the one of the following units' + JSON.stringify(unitMap, null, 2)); + } + return new BigNumber(unitValue, 10); +}; + +/** + * Takes a number of wei and converts it to any other ether unit. + * + * Possible units are: + * - kwei/ada + * - mwei/babbage + * - gwei/shannon + * - szabo + * - finney + * - ether + * - kether/grand/einstein + * - mether + * - gether + * - tether + * + * @method fromWei + * @param {Number|String} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert to, default ether + * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number +*/ +var fromWei = function(number, unit) { + var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit)); + + return isBigNumber(number) ? returnValue : returnValue.toString(10); +}; + +/** + * Takes a number of a unit and converts it to wei. + * + * Possible units are: + * - kwei/ada + * - mwei/babbage + * - gwei/shannon + * - szabo + * - finney + * - ether + * - kether/grand/einstein + * - mether + * - gether + * - tether + * + * @method toWei + * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert from, default ether + * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number +*/ +var toWei = function(number, unit) { + var returnValue = toBigNumber(number).times(getValueOfUnit(unit)); + + return isBigNumber(number) ? returnValue : returnValue.toString(10); +}; + +/** + * Takes an input and transforms it into an bignumber + * + * @method toBigNumber + * @param {Number|String|BigNumber} a number, string, HEX string or BigNumber + * @return {BigNumber} BigNumber +*/ +var toBigNumber = function(number) { + /*jshint maxcomplexity:5 */ + number = number || 0; + if (isBigNumber(number)) + return number; + + if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) { + return new BigNumber(number.replace('0x',''), 16); + } + + return new BigNumber(number.toString(10), 10); +}; + +/** + * Takes and input transforms it into bignumber and if it is negative value, into two's complement + * + * @method toTwosComplement + * @param {Number|String|BigNumber} + * @return {BigNumber} + */ +var toTwosComplement = function (number) { + var bigNumber = toBigNumber(number); + if (bigNumber.lessThan(0)) { + return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1); + } + return bigNumber; +}; + +/** + * Checks if the given string has proper length + * + * @method isAddress + * @param {String} address the given HEX adress + * @return {Boolean} +*/ +var isAddress = function(address) { + if (!isString(address)) { + return false; + } + + return ((address.indexOf('0x') === 0 && address.length === 42) || + (address.indexOf('0x') === -1 && address.length === 40)); +}; + +/** + * Returns true if object is BigNumber, otherwise false + * + * @method isBigNumber + * @param {Object} + * @return {Boolean} + */ +var isBigNumber = function (object) { + return object instanceof BigNumber || + (object && object.constructor && object.constructor.name === 'BigNumber'); +}; + +/** + * Returns true if object is string, otherwise false + * + * @method isString + * @param {Object} + * @return {Boolean} + */ +var isString = function (object) { + return typeof object === 'string' || + (object && object.constructor && object.constructor.name === 'String'); +}; + +/** + * Returns true if object is function, otherwise false + * + * @method isFunction + * @param {Object} + * @return {Boolean} + */ +var isFunction = function (object) { + return typeof object === 'function'; +}; + +/** + * Returns true if object is Objet, otherwise false + * + * @method isObject + * @param {Object} + * @return {Boolean} + */ +var isObject = function (object) { + return typeof object === 'object'; +}; + +/** + * Returns true if object is boolean, otherwise false + * + * @method isBoolean + * @param {Object} + * @return {Boolean} + */ +var isBoolean = function (object) { + return typeof object === 'boolean'; +}; + +/** + * Returns true if object is array, otherwise false + * + * @method isArray + * @param {Object} + * @return {Boolean} + */ +var isArray = function (object) { + return object instanceof Array; +}; + +module.exports = { + findIndex: findIndex, + toHex: toHex, + toDecimal: toDecimal, + fromDecimal: fromDecimal, + toAscii: toAscii, + fromAscii: fromAscii, + extractDisplayName: extractDisplayName, + extractTypeName: extractTypeName, + filterFunctions: filterFunctions, + filterEvents: filterEvents, + toWei: toWei, + fromWei: fromWei, + toBigNumber: toBigNumber, + toTwosComplement: toTwosComplement, + isBigNumber: isBigNumber, + isAddress: isAddress, + isFunction: isFunction, + isString: isString, + isObject: isObject, + isBoolean: isBoolean, + isArray: isArray +}; + + +},{}],6:[function(require,module,exports){ +/* + This file is part of ethereum.js. + + ethereum.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + ethereum.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with ethereum.js. If not, see . +*/ +/** @file web3.js + * @authors: + * Jeffrey Wilcke + * Marek Kotewicz + * Marian Oancea + * Gav Wood + * @date 2014 + */ + +var net = require('./web3/net'); +var eth = require('./web3/eth'); +var db = require('./web3/db'); +var shh = require('./web3/shh'); +var watches = require('./web3/watches'); +var filter = require('./web3/filter'); +var utils = require('./utils/utils'); +var formatters = require('./solidity/formatters'); +var requestManager = require('./web3/requestmanager'); +var c = require('./utils/config'); + +/// @returns an array of objects describing web3 api methods +var web3Methods = function () { + return [ + { name: 'sha3', call: 'web3_sha3' } + ]; +}; + +/// creates methods in a given object based on method description on input +/// setups api calls for these methods +var setupMethods = function (obj, methods) { + methods.forEach(function (method) { + // allow for object methods 'myObject.method' + var objectMethods = method.name.split('.'), + callFunction = function () { + /*jshint maxcomplexity:8 */ + + var callback = null, + args = Array.prototype.slice.call(arguments), + call = typeof method.call === 'function' ? method.call(args) : method.call; + + // get the callback if one is available + if(typeof args[args.length-1] === 'function'){ + callback = args[args.length-1]; + Array.prototype.pop.call(args); + } + + // add the defaultBlock if not given + if(method.addDefaultblock) { + if(args.length !== method.addDefaultblock) + Array.prototype.push.call(args, (isFinite(c.ETH_DEFAULTBLOCK) ? utils.fromDecimal(c.ETH_DEFAULTBLOCK) : c.ETH_DEFAULTBLOCK)); + else + args[args.length-1] = isFinite(args[args.length-1]) ? utils.fromDecimal(args[args.length-1]) : args[args.length-1]; + } + + // show deprecated warning + if(method.newMethod) + console.warn('This method is deprecated please use web3.'+ method.newMethod +'() instead.'); + + return web3.manager.send({ + method: call, + params: args, + outputFormatter: method.outputFormatter, + inputFormatter: method.inputFormatter, + addDefaultblock: method.addDefaultblock + }, callback); + }; + + if(objectMethods.length > 1) { + if(!obj[objectMethods[0]]) + obj[objectMethods[0]] = {}; + + obj[objectMethods[0]][objectMethods[1]] = callFunction; + + } else { + + obj[objectMethods[0]] = callFunction; + } + + }); +}; + +/// creates properties in a given object based on properties description on input +/// setups api calls for these properties +var setupProperties = function (obj, properties) { + properties.forEach(function (property) { + var proto = {}; + proto.get = function () { + + // show deprecated warning + if(property.newProperty) + console.warn('This property is deprecated please use web3.'+ property.newProperty +' instead.'); + + + return web3.manager.send({ + method: property.getter, + outputFormatter: property.outputFormatter + }); + }; + + if (property.setter) { + proto.set = function (val) { + + // show deprecated warning + if(property.newProperty) + console.warn('This property is deprecated please use web3.'+ property.newProperty +' instead.'); + + return web3.manager.send({ + method: property.setter, + params: [val], + inputFormatter: property.inputFormatter + }); + }; + } + + proto.enumerable = !property.newProperty; + Object.defineProperty(obj, property.name, proto); + + }); +}; + +/*jshint maxparams:4 */ +var startPolling = function (method, id, callback, uninstall) { + web3.manager.startPolling({ + method: method, + params: [id] + }, id, callback, uninstall); +}; +/*jshint maxparams:3 */ + +var stopPolling = function (id) { + web3.manager.stopPolling(id); +}; + +var ethWatch = { + startPolling: startPolling.bind(null, 'eth_getFilterChanges'), + stopPolling: stopPolling +}; + +var shhWatch = { + startPolling: startPolling.bind(null, 'shh_getFilterChanges'), + stopPolling: stopPolling +}; + +/// setups web3 object, and it's in-browser executed methods +var web3 = { + manager: requestManager(), + providers: {}, + + setProvider: function (provider) { + web3.manager.setProvider(provider); + }, + + /// Should be called to reset state of web3 object + /// Resets everything except manager + reset: function () { + web3.manager.reset(); + }, + + /// @returns hex string of the input + toHex: utils.toHex, + + /// @returns ascii string representation of hex value prefixed with 0x + toAscii: utils.toAscii, + + /// @returns hex representation (prefixed by 0x) of ascii string + fromAscii: utils.fromAscii, + + /// @returns decimal representaton of hex value prefixed by 0x + toDecimal: utils.toDecimal, + + /// @returns hex representation (prefixed by 0x) of decimal value + fromDecimal: utils.fromDecimal, + + /// @returns a BigNumber object + toBigNumber: utils.toBigNumber, + + toWei: utils.toWei, + fromWei: utils.fromWei, + isAddress: utils.isAddress, + + // provide network information + net: { + // peerCount: + }, + + + /// eth object prototype + eth: { + // DEPRECATED + contractFromAbi: function (abi) { + console.warn('Initiating a contract like this is deprecated please use var MyContract = eth.contract(abi); new MyContract(address); instead.'); + + return function(addr) { + // Default to address of Config. TODO: rremove prior to genesis. + addr = addr || '0xc6d9d2cd449a754c494264e1809c50e34d64562b'; + var ret = web3.eth.contract(addr, abi); + ret.address = addr; + return ret; + }; + }, + + /// @param filter may be a string, object or event + /// @param eventParams is optional, this is an object with optional event eventParams params + /// @param options is optional, this is an object with optional event options ('max'...) + /*jshint maxparams:4 */ + filter: function (fil, eventParams, options) { + + // if its event, treat it differently + if (fil._isEvent) + return fil(eventParams, options); + + return filter(fil, ethWatch, formatters.outputLogFormatter); + }, + // DEPRECATED + watch: function (fil, eventParams, options) { + console.warn('eth.watch() is deprecated please use eth.filter() instead.'); + return this.filter(fil, eventParams, options); + } + /*jshint maxparams:3 */ + }, + + /// db object prototype + db: {}, + + /// shh object prototype + shh: { + /// @param filter may be a string, object or event + filter: function (fil) { + return filter(fil, shhWatch, formatters.outputPostFormatter); + }, + // DEPRECATED + watch: function (fil) { + console.warn('shh.watch() is deprecated please use shh.filter() instead.'); + return this.filter(fil); + } + } +}; + + +// ADD defaultblock +Object.defineProperty(web3.eth, 'defaultBlock', { + get: function () { + return c.ETH_DEFAULTBLOCK; + }, + set: function (val) { + c.ETH_DEFAULTBLOCK = val; + return c.ETH_DEFAULTBLOCK; + } +}); + + +/// setups all api methods +setupMethods(web3, web3Methods()); +setupMethods(web3.net, net.methods); +setupProperties(web3.net, net.properties); +setupMethods(web3.eth, eth.methods); +setupProperties(web3.eth, eth.properties); +setupMethods(web3.db, db.methods()); +setupMethods(web3.shh, shh.methods()); +setupMethods(ethWatch, watches.eth()); +setupMethods(shhWatch, watches.shh()); + +module.exports = web3; + + +},{"./solidity/formatters":2,"./utils/config":4,"./utils/utils":5,"./web3/db":8,"./web3/eth":9,"./web3/filter":11,"./web3/net":15,"./web3/requestmanager":17,"./web3/shh":18,"./web3/watches":20}],7:[function(require,module,exports){ +/* + This file is part of ethereum.js. + + ethereum.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + ethereum.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with ethereum.js. If not, see . +*/ +/** @file contract.js + * @authors: + * Marek Kotewicz + * @date 2014 + */ + +var web3 = require('../web3'); +var abi = require('../solidity/abi'); +var utils = require('../utils/utils'); +var eventImpl = require('./event'); +var signature = require('./signature'); + +var exportNatspecGlobals = function (vars) { + // it's used byt natspec.js + // TODO: figure out better way to solve this + web3._currentContractAbi = vars.abi; + web3._currentContractAddress = vars.address; + web3._currentContractMethodName = vars.method; + web3._currentContractMethodParams = vars.params; +}; + +var addFunctionRelatedPropertiesToContract = function (contract) { + + contract.call = function (options) { + contract._isTransaction = false; + contract._options = options; + return contract; + }; + + + contract.sendTransaction = function (options) { + contract._isTransaction = true; + contract._options = options; + return contract; + }; + // DEPRECATED + contract.transact = function (options) { + + console.warn('myContract.transact() is deprecated please use myContract.sendTransaction() instead.'); + + return contract.sendTransaction(options); + }; + + contract._options = {}; + ['gas', 'gasPrice', 'value', 'from'].forEach(function(p) { + contract[p] = function (v) { + contract._options[p] = v; + return contract; + }; + }); + +}; + +var addFunctionsToContract = function (contract, desc, address) { + var inputParser = abi.inputParser(desc); + var outputParser = abi.outputParser(desc); + + // create contract functions + utils.filterFunctions(desc).forEach(function (method) { + + var displayName = utils.extractDisplayName(method.name); + var typeName = utils.extractTypeName(method.name); + + var impl = function () { + /*jshint maxcomplexity:7 */ var params = Array.prototype.slice.call(arguments); var sign = signature.functionSignatureFromAscii(method.name); var parsed = inputParser[displayName][typeName].apply(null, params); @@ -342,14 +1437,14 @@ var addFunctionsToContract = function (contract, desc, address) { options.to = address; options.data = sign + parsed; - var isTransact = contract._isTransact === true || (contract._isTransact !== false && !method.constant); + var isTransaction = contract._isTransaction === true || (contract._isTransaction !== false && !method.constant); var collapse = options.collapse !== false; // reset contract._options = {}; - contract._isTransact = null; + contract._isTransaction = null; - if (isTransact) { + if (isTransaction) { exportNatspecGlobals({ abi: desc, @@ -359,7 +1454,7 @@ var addFunctionsToContract = function (contract, desc, address) { }); // transactions do not have any output, cause we do not know, when they will be processed - web3.eth.transact(options); + web3.eth.sendTransaction(options); return; } @@ -391,7 +1486,7 @@ var addEventRelatedPropertiesToContract = function (contract, desc, address) { return parser(data); }; - Object.defineProperty(contract, 'topic', { + Object.defineProperty(contract, 'topics', { get: function() { return utils.filterEvents(desc).map(function (e) { return signature.eventSignatureFromAscii(e.name); @@ -414,7 +1509,7 @@ var addEventsToContract = function (contract, desc, address) { var parser = eventImpl.outputParser(e); return parser(data); }; - return web3.eth.watch(o, undefined, undefined, outputFormatter); + return web3.eth.filter(o, undefined, undefined, outputFormatter); }; // this property should be used by eth.filter to check if object is an event @@ -444,24 +1539,40 @@ var addEventsToContract = function (contract, desc, address) { * outputs: [{name: 'd', type: 'string' }] * }]; // contract abi * - * var myContract = web3.eth.contract('0x0123123121', abi); // creation of contract object + * var MyContract = web3.eth.contract(abi); // creation of contract prototype + * + * var contractInstance = new MyContract('0x0123123121'); * - * myContract.myMethod('this is test string param for call'); // myMethod call (implicit, default) - * myContract.call().myMethod('this is test string param for call'); // myMethod call (explicit) - * myContract.transact().myMethod('this is test string param for transact'); // myMethod transact + * contractInstance.myMethod('this is test string param for call'); // myMethod call (implicit, default) + * contractInstance.call().myMethod('this is test string param for call'); // myMethod call (explicit) + * contractInstance.sendTransaction().myMethod('this is test string param for transact'); // myMethod sendTransaction * - * @param address - address of the contract, which should be called - * @param desc - abi json description of the contract, which is being created + * @param abi - abi json description of the contract, which is being created * @returns contract object */ +var contract = function (abi) { + + // return prototype + if(abi instanceof Array && arguments.length === 1) { + return Contract.bind(null, abi); + + // deprecated: auto initiate contract + } else { -var contract = function (address, desc) { + console.warn('Initiating a contract like this is deprecated please use var MyContract = eth.contract(abi); new MyContract(address); instead.'); + + return new Contract(arguments[1], arguments[0]); + } + +}; + +function Contract(abi, address) { // workaround for invalid assumption that method.name is the full anonymous prototype of the method. // it's not. it's just the name. the rest of the code assumes it's actually the anonymous // prototype, so we make it so as a workaround. // TODO: we may not want to modify input params, maybe use copy instead? - desc.forEach(function (method) { + abi.forEach(function (method) { if (method.name.indexOf('(') === -1) { var displayName = method.name; var typeName = method.inputs.map(function(i){return i.type; }).join(); @@ -471,17 +1582,17 @@ var contract = function (address, desc) { var result = {}; addFunctionRelatedPropertiesToContract(result); - addFunctionsToContract(result, desc, address); - addEventRelatedPropertiesToContract(result, desc, address); - addEventsToContract(result, desc, address); + addFunctionsToContract(result, abi, address); + addEventRelatedPropertiesToContract(result, abi, address); + addEventsToContract(result, abi, address); return result; -}; +} module.exports = contract; -},{"./abi":1,"./event":6,"./signature":14,"./utils":16,"./web3":18}],4:[function(require,module,exports){ +},{"../solidity/abi":1,"../utils/utils":5,"../web3":6,"./event":10,"./signature":19}],8:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -518,7 +1629,7 @@ module.exports = { methods: methods }; -},{}],5:[function(require,module,exports){ +},{}],9:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -541,63 +1652,126 @@ module.exports = { * @date 2015 */ -/// @returns an array of objects describing web3.eth api methods -var methods = function () { - var blockCall = function (args) { - return typeof args[0] === "string" ? "eth_blockByHash" : "eth_blockByNumber"; - }; +/** + * Web3 + * + * @module web3 + */ - var transactionCall = function (args) { - return typeof args[0] === "string" ? 'eth_transactionByHash' : 'eth_transactionByNumber'; - }; +/** + * Eth methods and properties + * + * An example method object can look as follows: + * + * { + * name: 'getBlock', + * call: blockCall, + * outputFormatter: formatters.outputBlockFormatter, + * inputFormatter: [ // can be a formatter funciton or an array of functions. Where each item in the array will be used for one parameter + * utils.toHex, // formats paramter 1 + * function(param){ if(!param) return false; } // formats paramter 2 + * ] + * }, + * + * @class [web3] eth + * @constructor + */ - var uncleCall = function (args) { - return typeof args[0] === "string" ? 'eth_uncleByHash' : 'eth_uncleByNumber'; - }; - var transactionCountCall = function (args) { - return typeof args[0] === "string" ? 'eth_transactionCountByHash' : 'eth_transactionCountByNumber'; - }; +var formatters = require('./formatters'); +var utils = require('../utils/utils'); - var uncleCountCall = function (args) { - return typeof args[0] === "string" ? 'eth_uncleCountByHash' : 'eth_uncleCountByNumber'; - }; - return [ - { name: 'balanceAt', call: 'eth_balanceAt' }, - { name: 'stateAt', call: 'eth_stateAt' }, - { name: 'storageAt', call: 'eth_storageAt' }, - { name: 'countAt', call: 'eth_countAt'}, - { name: 'codeAt', call: 'eth_codeAt' }, - { name: 'transact', call: 'eth_transact' }, - { name: 'call', call: 'eth_call' }, - { name: 'block', call: blockCall }, - { name: 'transaction', call: transactionCall }, - { name: 'uncle', call: uncleCall }, - { name: 'compilers', call: 'eth_compilers' }, - { name: 'flush', call: 'eth_flush' }, - { name: 'lll', call: 'eth_lll' }, - { name: 'solidity', call: 'eth_solidity' }, - { name: 'serpent', call: 'eth_serpent' }, - { name: 'logs', call: 'eth_logs' }, - { name: 'transactionCount', call: transactionCountCall }, - { name: 'uncleCount', call: uncleCountCall } - ]; +var blockCall = function (args) { + return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? "eth_getBlockByHash" : "eth_getBlockByNumber"; +}; + +var transactionFromBlockCall = function (args) { + return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex'; +}; + +var uncleCall = function (args) { + return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex'; +}; + +var getBlockTransactionCountCall = function (args) { + return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber'; +}; + +var uncleCountCall = function (args) { + return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber'; }; +/// @returns an array of objects describing web3.eth api methods +var methods = [ + { name: 'getBalance', call: 'eth_getBalance', addDefaultblock: 2, + outputFormatter: formatters.convertToBigNumber}, + { name: 'getStorage', call: 'eth_getStorage', addDefaultblock: 2}, + { name: 'getStorageAt', call: 'eth_getStorageAt', addDefaultblock: 3, + inputFormatter: utils.toHex}, + { name: 'getData', call: 'eth_getData', addDefaultblock: 2}, + { name: 'getBlock', call: blockCall, + outputFormatter: formatters.outputBlockFormatter, + inputFormatter: [utils.toHex, function(param){ return (!param) ? false : true; }]}, + { name: 'getUncle', call: uncleCall, + outputFormatter: formatters.outputBlockFormatter, + inputFormatter: [utils.toHex, utils.toHex, function(param){ return (!param) ? false : true; }]}, + { name: 'getCompilers', call: 'eth_getCompilers' }, + { name: 'getBlockTransactionCount', call: getBlockTransactionCountCall, + outputFormatter: utils.toDecimal, + inputFormatter: utils.toHex }, + { name: 'getBlockUncleCount', call: uncleCountCall, + outputFormatter: utils.toDecimal, + inputFormatter: utils.toHex }, + { name: 'getTransaction', call: 'eth_getTransactionByHash', + outputFormatter: formatters.outputTransactionFormatter }, + { name: 'getTransactionFromBlock', call: transactionFromBlockCall, + outputFormatter: formatters.outputTransactionFormatter, + inputFormatter: utils.toHex }, + { name: 'getTransactionCount', call: 'eth_getTransactionCount', addDefaultblock: 2, + outputFormatter: utils.toDecimal}, + { name: 'sendTransaction', call: 'eth_sendTransaction', + inputFormatter: formatters.inputTransactionFormatter }, + { name: 'call', call: 'eth_call', addDefaultblock: 2, + inputFormatter: formatters.inputCallFormatter }, + { name: 'compile.solidity', call: 'eth_compileSolidity', inputFormatter: utils.toHex }, + { name: 'compile.lll', call: 'eth_compileLLL', inputFormatter: utils.toHex }, + { name: 'compile.serpent', call: 'eth_compileSerpent', inputFormatter: utils.toHex }, + { name: 'flush', call: 'eth_flush' }, + + // deprecated methods + { name: 'balanceAt', call: 'eth_balanceAt', newMethod: 'eth.getBalance' }, + { name: 'stateAt', call: 'eth_stateAt', newMethod: 'eth.getStorageAt' }, + { name: 'storageAt', call: 'eth_storageAt', newMethod: 'eth.getStorage' }, + { name: 'countAt', call: 'eth_countAt', newMethod: 'eth.getTransactionCount' }, + { name: 'codeAt', call: 'eth_codeAt', newMethod: 'eth.getData' }, + { name: 'transact', call: 'eth_transact', newMethod: 'eth.sendTransaction' }, + { name: 'block', call: blockCall, newMethod: 'eth.getBlock' }, + { name: 'transaction', call: transactionFromBlockCall, newMethod: 'eth.getTransaction' }, + { name: 'uncle', call: uncleCall, newMethod: 'eth.getUncle' }, + { name: 'compilers', call: 'eth_compilers', newMethod: 'eth.getCompilers' }, + { name: 'solidity', call: 'eth_solidity', newMethod: 'eth.compile.solidity' }, + { name: 'lll', call: 'eth_lll', newMethod: 'eth.compile.lll' }, + { name: 'serpent', call: 'eth_serpent', newMethod: 'eth.compile.serpent' }, + { name: 'transactionCount', call: getBlockTransactionCountCall, newMethod: 'eth.getBlockTransactionCount' }, + { name: 'uncleCount', call: uncleCountCall, newMethod: 'eth.getBlockUncleCount' }, + { name: 'logs', call: 'eth_logs' } +]; + /// @returns an array of objects describing web3.eth api properties -var properties = function () { - return [ - { name: 'coinbase', getter: 'eth_coinbase', setter: 'eth_setCoinbase' }, - { name: 'listening', getter: 'eth_listening', setter: 'eth_setListening' }, - { name: 'mining', getter: 'eth_mining', setter: 'eth_setMining' }, - { name: 'gasPrice', getter: 'eth_gasPrice' }, +var properties = [ + { name: 'coinbase', getter: 'eth_coinbase'}, + { name: 'mining', getter: 'eth_mining'}, + { name: 'gasPrice', getter: 'eth_gasPrice', outputFormatter: formatters.convertToBigNumber}, { name: 'accounts', getter: 'eth_accounts' }, - { name: 'peerCount', getter: 'eth_peerCount' }, - { name: 'defaultBlock', getter: 'eth_defaultBlock', setter: 'eth_setDefaultBlock' }, - { name: 'number', getter: 'eth_number'} - ]; -}; + { name: 'blockNumber', getter: 'eth_blockNumber', outputFormatter: utils.toDecimal}, + + // deprecated properties + { name: 'listening', getter: 'net_listening', setter: 'eth_setListening', newProperty: 'net.listening'}, + { name: 'peerCount', getter: 'net_peerCount', newProperty: 'net.peerCount'}, + { name: 'number', getter: 'eth_number', newProperty: 'eth.blockNumber'} +]; + module.exports = { methods: methods, @@ -605,7 +1779,7 @@ module.exports = { }; -},{}],6:[function(require,module,exports){ +},{"../utils/utils":5,"./formatters":12}],10:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -628,8 +1802,8 @@ module.exports = { * @date 2014 */ -var abi = require('./abi'); -var utils = require('./utils'); +var abi = require('../solidity/abi'); +var utils = require('../utils/utils'); var signature = require('./signature'); /// filter inputs array && returns only indexed (or not) inputs @@ -671,14 +1845,14 @@ var indexedParamsToTopics = function (event, indexed) { var inputParser = function (address, sign, event) { - // valid options are 'earliest', 'latest', 'offset' and 'max', as defined for 'eth.watch' + // valid options are 'earliest', 'latest', 'offset' and 'max', as defined for 'eth.filter' return function (indexed, options) { var o = options || {}; o.address = address; - o.topic = []; - o.topic.push(sign); + o.topics = []; + o.topics.push(sign); if (indexed) { - o.topic = o.topic.concat(indexedParamsToTopics(event, indexed)); + o.topics = o.topics.concat(indexedParamsToTopics(event, indexed)); } return o; }; @@ -710,12 +1884,12 @@ var outputParser = function (event) { }; output.topics = output.topic; // fallback for go-ethereum - if (!output.topic) { + if (!output.topics) { return result; } var indexedOutputs = filterInputs(event.inputs, true); - var indexedData = "0x" + output.topic.slice(1, output.topic.length).map(function (topic) { return topic.slice(2); }).join(""); + var indexedData = "0x" + output.topics.slice(1, output.topics.length).map(function (topics) { return topics.slice(2); }).join(""); var indexedRes = abi.formatOutput(indexedOutputs, indexedData); var notIndexedOutputs = filterInputs(event.inputs, false); @@ -730,344 +1904,22 @@ var outputParser = function (event) { var getMatchingEvent = function (events, payload) { for (var i = 0; i < events.length; i++) { var sign = signature.eventSignatureFromAscii(events[i].name); - if (sign === payload.topic[0]) { + if (sign === payload.topics[0]) { return events[i]; } - } - return undefined; -}; - - -module.exports = { - inputParser: inputParser, - outputParser: outputParser, - getMatchingEvent: getMatchingEvent -}; - - -},{"./abi":1,"./signature":14,"./utils":16}],7:[function(require,module,exports){ -/* - This file is part of ethereum.js. - - ethereum.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - ethereum.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with ethereum.js. If not, see . -*/ -/** @file filter.js - * @authors: - * Jeffrey Wilcke - * Marek Kotewicz - * Marian Oancea - * Gav Wood - * @date 2014 - */ - -/// Should be called to check if filter implementation is valid -/// @returns true if it is, otherwise false -var implementationIsValid = function (i) { - return !!i && - typeof i.newFilter === 'function' && - typeof i.getMessages === 'function' && - typeof i.uninstallFilter === 'function' && - typeof i.startPolling === 'function' && - typeof i.stopPolling === 'function'; -}; - -/// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones -/// @param should be string or object -/// @returns options string or object -var getOptions = function (options) { - if (typeof options === 'string') { - return options; - } - - options = options || {}; - - if (options.topics) { - console.warn('"topics" is deprecated, is "topic" instead'); - } - - // evaluate lazy properties - return { - to: options.to, - topic: options.topic, - earliest: options.earliest, - latest: options.latest, - max: options.max, - skip: options.skip, - address: options.address - }; -}; - -/// Should be used when we want to watch something -/// it's using inner polling mechanism and is notified about changes -/// @param options are filter options -/// @param implementation, an abstract polling implementation -/// @param formatter (optional), callback function which formats output before 'real' callback -var filter = function(options, implementation, formatter) { - if (!implementationIsValid(implementation)) { - console.error('filter implemenation is invalid'); - return; - } - - options = getOptions(options); - var callbacks = []; - var filterId = implementation.newFilter(options); - var onMessages = function (messages) { - messages.forEach(function (message) { - message = formatter ? formatter(message) : message; - callbacks.forEach(function (callback) { - callback(message); - }); - }); - }; - - implementation.startPolling(filterId, onMessages, implementation.uninstallFilter); - - var changed = function (callback) { - callbacks.push(callback); - }; - - var messages = function () { - return implementation.getMessages(filterId); - }; - - var uninstall = function () { - implementation.stopPolling(filterId); - implementation.uninstallFilter(filterId); - callbacks = []; - }; - - return { - changed: changed, - arrived: changed, - happened: changed, - messages: messages, - logs: messages, - uninstall: uninstall - }; -}; - -module.exports = filter; - - -},{}],8:[function(require,module,exports){ -/* - This file is part of ethereum.js. - - ethereum.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - ethereum.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with ethereum.js. If not, see . -*/ -/** @file formatters.js - * @authors: - * Marek Kotewicz - * @date 2015 - */ - -if ("build" !== 'build') {/* - var BigNumber = require('bignumber.js'); // jshint ignore:line -*/} - -var utils = require('./utils'); -var c = require('./const'); - -/// @param string string to be padded -/// @param number of characters that result string should have -/// @param sign, by default 0 -/// @returns right aligned string -var padLeft = function (string, chars, sign) { - return new Array(chars - string.length + 1).join(sign ? sign : "0") + string; -}; - -/// Formats input value to byte representation of int -/// If value is negative, return it's two's complement -/// If the value is floating point, round it down -/// @returns right-aligned byte representation of int -var formatInputInt = function (value) { - /*jshint maxcomplexity:7 */ - var padding = c.ETH_PADDING * 2; - if (value instanceof BigNumber || typeof value === 'number') { - if (typeof value === 'number') - value = new BigNumber(value); - BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE); - value = value.round(); - - if (value.lessThan(0)) - value = new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(value).plus(1); - value = value.toString(16); - } - else if (value.indexOf('0x') === 0) - value = value.substr(2); - else if (typeof value === 'string') - value = formatInputInt(new BigNumber(value)); - else - value = (+value).toString(16); - return padLeft(value, padding); -}; - -/// Formats input value to byte representation of string -/// @returns left-algined byte representation of string -var formatInputString = function (value) { - return utils.fromAscii(value, c.ETH_PADDING).substr(2); -}; - -/// Formats input value to byte representation of bool -/// @returns right-aligned byte representation bool -var formatInputBool = function (value) { - return '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0'); -}; - -/// Formats input value to byte representation of real -/// Values are multiplied by 2^m and encoded as integers -/// @returns byte representation of real -var formatInputReal = function (value) { - return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128))); -}; - - -/// Check if input value is negative -/// @param value is hex format -/// @returns true if it is negative, otherwise false -var signedIsNegative = function (value) { - return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1'; -}; - -/// Formats input right-aligned input bytes to int -/// @returns right-aligned input bytes formatted to int -var formatOutputInt = function (value) { - value = value || "0"; - // check if it's negative number - // it it is, return two's complement - if (signedIsNegative(value)) { - return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1); - } - return new BigNumber(value, 16); -}; - -/// Formats big right-aligned input bytes to uint -/// @returns right-aligned input bytes formatted to uint -var formatOutputUInt = function (value) { - value = value || "0"; - return new BigNumber(value, 16); -}; - -/// @returns input bytes formatted to real -var formatOutputReal = function (value) { - return formatOutputInt(value).dividedBy(new BigNumber(2).pow(128)); -}; - -/// @returns input bytes formatted to ureal -var formatOutputUReal = function (value) { - return formatOutputUInt(value).dividedBy(new BigNumber(2).pow(128)); -}; - -/// @returns right-aligned input bytes formatted to hex -var formatOutputHash = function (value) { - return "0x" + value; -}; - -/// @returns right-aligned input bytes formatted to bool -var formatOutputBool = function (value) { - return value === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false; -}; - -/// @returns left-aligned input bytes formatted to ascii string -var formatOutputString = function (value) { - return utils.toAscii(value); -}; - -/// @returns right-aligned input bytes formatted to address -var formatOutputAddress = function (value) { - return "0x" + value.slice(value.length - 40, value.length); -}; - - -module.exports = { - formatInputInt: formatInputInt, - formatInputString: formatInputString, - formatInputBool: formatInputBool, - formatInputReal: formatInputReal, - formatOutputInt: formatOutputInt, - formatOutputUInt: formatOutputUInt, - formatOutputReal: formatOutputReal, - formatOutputUReal: formatOutputUReal, - formatOutputHash: formatOutputHash, - formatOutputBool: formatOutputBool, - formatOutputString: formatOutputString, - formatOutputAddress: formatOutputAddress -}; - - -},{"./const":2,"./utils":16}],9:[function(require,module,exports){ -/* - This file is part of ethereum.js. - - ethereum.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - ethereum.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with ethereum.js. If not, see . -*/ -/** @file httpsync.js - * @authors: - * Marek Kotewicz - * Marian Oancea - * @date 2014 - */ - -if ("build" !== 'build') {/* - var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line -*/} - -var HttpSyncProvider = function (host) { - this.handlers = []; - this.host = host || 'http://127.0.0.1:8080'; + } + return undefined; }; -HttpSyncProvider.prototype.send = function (payload) { - //var data = formatJsonRpcObject(payload); - - var request = new XMLHttpRequest(); - request.open('POST', this.host, false); - request.send(JSON.stringify(payload)); - var result = request.responseText; - // check request.status - if(request.status !== 200) - return; - return JSON.parse(result); +module.exports = { + inputParser: inputParser, + outputParser: outputParser, + getMatchingEvent: getMatchingEvent }; -module.exports = HttpSyncProvider; - -},{}],10:[function(require,module,exports){ +},{"../solidity/abi":1,"../utils/utils":5,"./signature":19}],11:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -1084,57 +1936,167 @@ module.exports = HttpSyncProvider; You should have received a copy of the GNU Lesser General Public License along with ethereum.js. If not, see . */ -/** @file jsonrpc.js +/** @file filter.js * @authors: + * Jeffrey Wilcke * Marek Kotewicz - * @date 2015 + * Marian Oancea + * Gav Wood + * @date 2014 */ -var messageId = 1; +var utils = require('../utils/utils'); -/// Should be called to valid json create payload object -/// @param method of jsonrpc call, required -/// @param params, an array of method params, optional -/// @returns valid jsonrpc payload object -var toPayload = function (method, params) { - if (!method) - console.error('jsonrpc method should be specified!'); +/// Should be called to check if filter implementation is valid +/// @returns true if it is, otherwise false +var implementationIsValid = function (i) { + return !!i && + typeof i.newFilter === 'function' && + typeof i.getLogs === 'function' && + typeof i.uninstallFilter === 'function' && + typeof i.startPolling === 'function' && + typeof i.stopPolling === 'function'; +}; + +/// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones +/// @param should be string or object +/// @returns options string or object +var getOptions = function (options) { + /*jshint maxcomplexity:9 */ + + if (typeof options === 'string') { + return options; + } + + options = options || {}; + + if (options.topic) { + console.warn('"topic" is deprecated, is "topics" instead'); + options.topics = options.topic; + } + + if (options.earliest) { + console.warn('"earliest" is deprecated, is "fromBlock" instead'); + options.fromBlock = options.earliest; + } + + if (options.latest) { + console.warn('"latest" is deprecated, is "toBlock" instead'); + options.toBlock = options.latest; + } + + if (options.skip) { + console.warn('"skip" is deprecated, is "offset" instead'); + options.offset = options.skip; + } + + if (options.max) { + console.warn('"max" is deprecated, is "limit" instead'); + options.limit = options.max; + } + + // make sure topics, get converted to hex + if(options.topics instanceof Array) { + options.topics = options.topics.map(function(topic){ + return utils.toHex(topic); + }); + } + + // evaluate lazy properties return { - jsonrpc: '2.0', - method: method, - params: params || [], - id: messageId++ - }; + fromBlock: utils.toHex(options.fromBlock), + toBlock: utils.toHex(options.toBlock), + limit: utils.toHex(options.limit), + offset: utils.toHex(options.offset), + to: options.to, + address: options.address, + topics: options.topics + }; }; -/// Should be called to check if jsonrpc response is valid -/// @returns true if response is valid, otherwise false -var isValidResponse = function (response) { - return !!response && - !response.error && - response.jsonrpc === '2.0' && - typeof response.id === 'number' && - response.result !== undefined; // only undefined is not valid json object -}; +/// Should be used when we want to watch something +/// it's using inner polling mechanism and is notified about changes +/// @param options are filter options +/// @param implementation, an abstract polling implementation +/// @param formatter (optional), callback function which formats output before 'real' callback +var filter = function(options, implementation, formatter) { + if (!implementationIsValid(implementation)) { + console.error('filter implemenation is invalid'); + return; + } -/// Should be called to create batch payload object -/// @param messages, an array of objects with method (required) and params (optional) fields -var toBatchPayload = function (messages) { - return messages.map(function (message) { - return toPayload(message.method, message.params); - }); -}; + options = getOptions(options); + var callbacks = []; + var filterId = implementation.newFilter(options); -module.exports = { - toPayload: toPayload, - isValidResponse: isValidResponse, - toBatchPayload: toBatchPayload + // call the callbacks + var onMessages = function (messages) { + messages.forEach(function (message) { + message = formatter ? formatter(message) : message; + callbacks.forEach(function (callback) { + callback(message); + }); + }); + }; + + implementation.startPolling(filterId, onMessages, implementation.uninstallFilter); + + var watch = function(callback) { + callbacks.push(callback); + }; + + var stopWatching = function() { + implementation.stopPolling(filterId); + implementation.uninstallFilter(filterId); + callbacks = []; + }; + + var get = function () { + var results = implementation.getLogs(filterId); + + return utils.isArray(results) ? results.map(function(message){ + return formatter ? formatter(message) : message; + }) : results; + }; + + return { + watch: watch, + stopWatching: stopWatching, + get: get, + + // DEPRECATED methods + changed: function(){ + console.warn('watch().changed() is deprecated please use filter().watch() instead.'); + return watch.apply(this, arguments); + }, + arrived: function(){ + console.warn('watch().arrived() is deprecated please use filter().watch() instead.'); + return watch.apply(this, arguments); + }, + happened: function(){ + console.warn('watch().happened() is deprecated please use filter().watch() instead.'); + return watch.apply(this, arguments); + }, + uninstall: function(){ + console.warn('watch().uninstall() is deprecated please use filter().stopWatching() instead.'); + return stopWatching.apply(this, arguments); + }, + messages: function(){ + console.warn('watch().messages() is deprecated please use filter().get() instead.'); + return get.apply(this, arguments); + }, + logs: function(){ + console.warn('watch().logs() is deprecated please use filter().get() instead.'); + return get.apply(this, arguments); + } + }; }; +module.exports = filter; -},{}],11:[function(require,module,exports){ +},{"../utils/utils":5}],12:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -1151,139 +2113,195 @@ module.exports = { You should have received a copy of the GNU Lesser General Public License along with ethereum.js. If not, see . */ -/** @file qtsync.js +/** @file formatters.js * @authors: * Marek Kotewicz - * Marian Oancea - * @date 2014 + * Fabian Vogelsteller + * @date 2015 */ -var QtSyncProvider = function () { +var utils = require('../utils/utils'); + +/** + * Should the input to a big number + * + * @method convertToBigNumber + * @param {String|Number|BigNumber} + * @returns {BigNumber} object + */ +var convertToBigNumber = function (value) { + return utils.toBigNumber(value); }; -QtSyncProvider.prototype.send = function (payload) { - var result = navigator.qt.callMethod(JSON.stringify(payload)); - return JSON.parse(result); +/** + * Formats the input of a transaction and converts all values to HEX + * + * @method inputTransactionFormatter + * @param {Object} transaction options + * @returns object +*/ +var inputTransactionFormatter = function (options){ + + // make code -> data + if (options.code) { + options.data = options.code; + delete options.code; + } + + ['gasPrice', 'gas', 'value'].forEach(function(key){ + options[key] = utils.fromDecimal(options[key]); + }); + + return options; }; -module.exports = QtSyncProvider; +/** + * Formats the output of a transaction to its proper values + * + * @method outputTransactionFormatter + * @param {Object} transaction + * @returns {Object} transaction +*/ +var outputTransactionFormatter = function (tx){ + tx.gas = utils.toDecimal(tx.gas); + tx.gasPrice = utils.toBigNumber(tx.gasPrice); + tx.value = utils.toBigNumber(tx.value); + return tx; +}; +/** + * Formats the input of a call and converts all values to HEX + * + * @method inputCallFormatter + * @param {Object} transaction options + * @returns object +*/ +var inputCallFormatter = function (options){ -},{}],12:[function(require,module,exports){ -/* - This file is part of ethereum.js. + // make code -> data + if (options.code) { + options.data = options.code; + delete options.code; + } - ethereum.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + return options; +}; - ethereum.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with ethereum.js. If not, see . +/** + * Formats the output of a block to its proper values + * + * @method outputBlockFormatter + * @param {Object} block object + * @returns {Object} block object */ -/** @file requestmanager.js - * @authors: - * Jeffrey Wilcke - * Marek Kotewicz - * Marian Oancea - * Gav Wood - * @date 2014 - */ +var outputBlockFormatter = function(block){ + + // transform to number + block.gasLimit = utils.toDecimal(block.gasLimit); + block.gasUsed = utils.toDecimal(block.gasUsed); + block.size = utils.toDecimal(block.size); + block.timestamp = utils.toDecimal(block.timestamp); + block.number = utils.toDecimal(block.number); + + block.minGasPrice = utils.toBigNumber(block.minGasPrice); + block.difficulty = utils.toBigNumber(block.difficulty); + block.totalDifficulty = utils.toBigNumber(block.totalDifficulty); + + if(block.transactions instanceof Array) { + block.transactions.forEach(function(item){ + if(!utils.isString(item)) + return outputTransactionFormatter(item); + }); + } -var jsonrpc = require('./jsonrpc'); -var c = require('./const'); + return block; +}; /** - * It's responsible for passing messages to providers - * It's also responsible for polling the ethereum node for incoming messages - * Default poll timeout is 1 second - */ -var requestManager = function() { - var polls = []; - var timeout = null; - var provider; + * Formats the output of a log + * + * @method outputLogFormatter + * @param {Object} log object + * @returns {Object} log +*/ +var outputLogFormatter = function(log){ + log.blockNumber = utils.toDecimal(log.blockNumber); + log.transactionIndex = utils.toDecimal(log.transactionIndex); + log.logIndex = utils.toDecimal(log.logIndex); - var send = function (data) { - var payload = jsonrpc.toPayload(data.method, data.params); - - if (!provider) { - console.error('provider is not set'); - return null; - } + return log; +}; - var result = provider.send(payload); - if (!jsonrpc.isValidResponse(result)) { - console.log(result); - return null; - } - - return result.result; - }; +/** + * Formats the input of a whisper post and converts all values to HEX + * + * @method inputPostFormatter + * @param {Object} transaction object + * @returns {Object} +*/ +var inputPostFormatter = function(post){ - var setProvider = function (p) { - provider = p; - }; + post.payload = utils.toHex(post.payload); + post.ttl = utils.fromDecimal(post.ttl); + post.priority = utils.fromDecimal(post.priority); - /*jshint maxparams:4 */ - var startPolling = function (data, pollId, callback, uninstall) { - polls.push({data: data, id: pollId, callback: callback, uninstall: uninstall}); - }; - /*jshint maxparams:3 */ + if(!(post.topics instanceof Array)) + post.topics = [post.topics]; - var stopPolling = function (pollId) { - for (var i = polls.length; i--;) { - var poll = polls[i]; - if (poll.id === pollId) { - polls.splice(i, 1); - } - } - }; - var reset = function () { - polls.forEach(function (poll) { - poll.uninstall(poll.id); - }); - polls = []; + // format the following options + post.topics = post.topics.map(function(topic){ + return utils.fromAscii(topic); + }); - if (timeout) { - clearTimeout(timeout); - timeout = null; - } - poll(); - }; + return post; +}; - var poll = function () { - polls.forEach(function (data) { - var result = send(data.data); - if (!(result instanceof Array) || result.length === 0) { - return; - } - data.callback(result); - }); - timeout = setTimeout(poll, c.ETH_POLLING_TIMEOUT); - }; - - poll(); +/** + * Formats the output of a received post message + * + * @method outputPostFormatter + * @param {Object} + * @returns {Object} + */ +var outputPostFormatter = function(post){ + + post.expiry = utils.toDecimal(post.expiry); + post.sent = utils.toDecimal(post.sent); + post.ttl = utils.toDecimal(post.ttl); + post.workProved = utils.toDecimal(post.workProved); + post.payloadRaw = post.payload; + post.payload = utils.toAscii(post.payload); + + if(post.payload.indexOf('{') === 0 || post.payload.indexOf('[') === 0) { + try { + post.payload = JSON.parse(post.payload); + } catch (e) { } + } + + // format the following options + post.topics = post.topics.map(function(topic){ + return utils.toAscii(topic); + }); - return { - send: send, - setProvider: setProvider, - startPolling: startPolling, - stopPolling: stopPolling, - reset: reset - }; + return post; }; -module.exports = requestManager; +module.exports = { + convertToBigNumber: convertToBigNumber, + inputTransactionFormatter: inputTransactionFormatter, + outputTransactionFormatter: outputTransactionFormatter, + inputCallFormatter: inputCallFormatter, + outputBlockFormatter: outputBlockFormatter, + outputLogFormatter: outputLogFormatter, + inputPostFormatter: inputPostFormatter, + outputPostFormatter: outputPostFormatter +}; -},{"./const":2,"./jsonrpc":10}],13:[function(require,module,exports){ +},{"../utils/utils":5}],13:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -1300,27 +2318,59 @@ module.exports = requestManager; You should have received a copy of the GNU Lesser General Public License along with ethereum.js. If not, see . */ -/** @file shh.js +/** @file httpprovider.js * @authors: * Marek Kotewicz - * @date 2015 + * Marian Oancea + * @date 2014 */ -/// @returns an array of objects describing web3.shh api methods -var methods = function () { - return [ - { name: 'post', call: 'shh_post' }, - { name: 'newIdentity', call: 'shh_newIdentity' }, - { name: 'haveIdentity', call: 'shh_haveIdentity' }, - { name: 'newGroup', call: 'shh_newGroup' }, - { name: 'addToGroup', call: 'shh_addToGroup' } - ]; +if ("build" !== 'build') {/* + var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line +*/} + +var HttpProvider = function (host) { + this.name = 'HTTP'; + this.handlers = []; + this.host = host || 'http://localhost:8080'; }; -module.exports = { - methods: methods +HttpProvider.prototype.send = function (payload, callback) { + var request = new XMLHttpRequest(); + request.open('POST', this.host, false); + + // ASYNC + if(typeof callback === 'function') { + request.onreadystatechange = function() { + if(request.readyState === 4) { + var result = ''; + try { + result = JSON.parse(request.responseText); + } catch(error) { + result = error; + } + callback(result, request.status); + } + }; + + request.open('POST', this.host, true); + request.send(JSON.stringify(payload)); + + // SYNC + } else { + request.open('POST', this.host, false); + request.send(JSON.stringify(payload)); + + // check request.status + if(request.status !== 200) + return; + return JSON.parse(request.responseText); + + } }; +module.exports = HttpProvider; + },{}],14:[function(require,module,exports){ /* @@ -1339,34 +2389,57 @@ module.exports = { You should have received a copy of the GNU Lesser General Public License along with ethereum.js. If not, see . */ -/** @file signature.js +/** @file jsonrpc.js * @authors: * Marek Kotewicz * @date 2015 */ -var web3 = require('./web3'); -var c = require('./const'); +var messageId = 1; -/// @param function name for which we want to get signature -/// @returns signature of function with given name -var functionSignatureFromAscii = function (name) { - return web3.sha3(web3.fromAscii(name)).slice(0, 2 + c.ETH_SIGNATURE_LENGTH * 2); +/// Should be called to valid json create payload object +/// @param method of jsonrpc call, required +/// @param params, an array of method params, optional +/// @returns valid jsonrpc payload object +var toPayload = function (method, params) { + if (!method) + console.error('jsonrpc method should be specified!'); + + return { + jsonrpc: '2.0', + method: method, + params: params || [], + id: messageId++ + }; }; -/// @param event name for which we want to get signature -/// @returns signature of event with given name -var eventSignatureFromAscii = function (name) { - return web3.sha3(web3.fromAscii(name)); +/// Should be called to check if jsonrpc response is valid +/// @returns true if response is valid, otherwise false +var isValidResponse = function (response) { + return !!response && + !response.error && + response.jsonrpc === '2.0' && + typeof response.id === 'number' && + response.result !== undefined; // only undefined is not valid json object +}; + +/// Should be called to create batch payload object +/// @param messages, an array of objects with method (required) and params (optional) fields +var toBatchPayload = function (messages) { + return messages.map(function (message) { + return toPayload(message.method, message.params); + }); }; module.exports = { - functionSignatureFromAscii: functionSignatureFromAscii, - eventSignatureFromAscii: eventSignatureFromAscii + toPayload: toPayload, + isValidResponse: isValidResponse, + toBatchPayload: toBatchPayload }; -},{"./const":2,"./web3":18}],15:[function(require,module,exports){ + +},{}],15:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -1383,71 +2456,68 @@ module.exports = { You should have received a copy of the GNU Lesser General Public License along with ethereum.js. If not, see . */ -/** @file types.js +/** @file eth.js * @authors: * Marek Kotewicz * @date 2015 */ -var f = require('./formatters'); +var utils = require('../utils/utils'); -/// @param expected type prefix (string) -/// @returns function which checks if type has matching prefix. if yes, returns true, otherwise false -var prefixedType = function (prefix) { - return function (type) { - return type.indexOf(prefix) === 0; - }; -}; +/// @returns an array of objects describing web3.eth api methods +var methods = [ + // { name: 'getBalance', call: 'eth_balanceAt', outputFormatter: formatters.convertToBigNumber}, +]; -/// @param expected type name (string) -/// @returns function which checks if type is matching expected one. if yes, returns true, otherwise false -var namedType = function (name) { - return function (type) { - return name === type; - }; -}; +/// @returns an array of objects describing web3.eth api properties +var properties = [ + { name: 'listening', getter: 'net_listening'}, + { name: 'peerCount', getter: 'net_peerCount', outputFormatter: utils.toDecimal }, +]; -/// Setups input formatters for solidity types -/// @returns an array of input formatters -var inputTypes = function () { - - return [ - { type: prefixedType('uint'), format: f.formatInputInt }, - { type: prefixedType('int'), format: f.formatInputInt }, - { type: prefixedType('hash'), format: f.formatInputInt }, - { type: prefixedType('string'), format: f.formatInputString }, - { type: prefixedType('real'), format: f.formatInputReal }, - { type: prefixedType('ureal'), format: f.formatInputReal }, - { type: namedType('address'), format: f.formatInputInt }, - { type: namedType('bool'), format: f.formatInputBool } - ]; + +module.exports = { + methods: methods, + properties: properties }; -/// Setups output formaters for solidity types -/// @returns an array of output formatters -var outputTypes = function () { - return [ - { type: prefixedType('uint'), format: f.formatOutputUInt }, - { type: prefixedType('int'), format: f.formatOutputInt }, - { type: prefixedType('hash'), format: f.formatOutputHash }, - { type: prefixedType('string'), format: f.formatOutputString }, - { type: prefixedType('real'), format: f.formatOutputReal }, - { type: prefixedType('ureal'), format: f.formatOutputUReal }, - { type: namedType('address'), format: f.formatOutputAddress }, - { type: namedType('bool'), format: f.formatOutputBool } - ]; +},{"../utils/utils":5}],16:[function(require,module,exports){ +/* + This file is part of ethereum.js. + + ethereum.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + ethereum.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with ethereum.js. If not, see . +*/ +/** @file qtsync.js + * @authors: + * Marek Kotewicz + * Marian Oancea + * @date 2014 + */ + +var QtSyncProvider = function () { }; -module.exports = { - prefixedType: prefixedType, - namedType: namedType, - inputTypes: inputTypes, - outputTypes: outputTypes +QtSyncProvider.prototype.send = function (payload) { + var result = navigator.qt.callMethod(JSON.stringify(payload)); + return JSON.parse(result); }; +module.exports = QtSyncProvider; + -},{"./formatters":8}],16:[function(require,module,exports){ +},{}],17:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -1464,135 +2534,153 @@ module.exports = { You should have received a copy of the GNU Lesser General Public License along with ethereum.js. If not, see . */ -/** @file utils.js +/** @file requestmanager.js * @authors: + * Jeffrey Wilcke * Marek Kotewicz - * @date 2015 + * Marian Oancea + * Gav Wood + * @date 2014 */ -var c = require('./const'); +var jsonrpc = require('./jsonrpc'); +var c = require('../utils/config'); -/// Finds first index of array element matching pattern -/// @param array -/// @param callback pattern -/// @returns index of element -var findIndex = function (array, callback) { - var end = false; - var i = 0; - for (; i < array.length && !end; i++) { - end = callback(array[i]); - } - return end ? i - 1 : -1; -}; +/** + * It's responsible for passing messages to providers + * It's also responsible for polling the ethereum node for incoming messages + * Default poll timeout is 1 second + */ +var requestManager = function() { + var polls = []; + var timeout = null; + var provider; -/// @returns ascii string representation of hex value prefixed with 0x -var toAscii = function(hex) { -// Find termination - var str = ""; - var i = 0, l = hex.length; - if (hex.substring(0, 2) === '0x') { - i = 2; - } - for (; i < l; i+=2) { - var code = parseInt(hex.substr(i, 2), 16); - if (code === 0) { - break; + var send = function (data, callback) { + /*jshint maxcomplexity: 8 */ + + // FORMAT BASED ON ONE FORMATTER function + if(typeof data.inputFormatter === 'function') { + data.params = Array.prototype.map.call(data.params, function(item, index){ + // format everything besides the defaultblock, which is already formated + return (!data.addDefaultblock || index+1 < data.addDefaultblock) ? data.inputFormatter(item) : item; + }); + + // FORMAT BASED ON the input FORMATTER ARRAY + } else if(data.inputFormatter instanceof Array) { + data.params = Array.prototype.map.call(data.inputFormatter, function(formatter, index){ + // format everything besides the defaultblock, which is already formated + return (!data.addDefaultblock || index+1 < data.addDefaultblock) ? formatter(data.params[index]) : data.params[index]; + }); } - str += String.fromCharCode(code); - } - return str; -}; - -var toHex = function(str) { - var hex = ""; - for(var i = 0; i < str.length; i++) { - var n = str.charCodeAt(i).toString(16); - hex += n.length < 2 ? '0' + n : n; - } + var payload = jsonrpc.toPayload(data.method, data.params); + + if (!provider) { + console.error('provider is not set'); + return null; + } - return hex; -}; + // HTTP ASYNC (only when callback is given, and it a HttpProvidor) + if(typeof callback === 'function' && provider.name === 'HTTP'){ + provider.send(payload, function(result, status){ + + if (!jsonrpc.isValidResponse(result)) { + if(typeof result === 'object' && result.error && result.error.message) { + console.error(result.error.message); + callback(result.error); + } else { + callback(new Error({ + status: status, + error: result, + message: 'Bad Request' + })); + } + return null; + } + + // format the output + callback(null, (typeof data.outputFormatter === 'function') ? data.outputFormatter(result.result) : result.result); + }); -/// @returns hex representation (prefixed by 0x) of ascii string -var fromAscii = function(str, pad) { - pad = pad === undefined ? 0 : pad; - var hex = toHex(str); - while (hex.length < pad*2) - hex += "00"; - return "0x" + hex; -}; + // SYNC + } else { + var result = provider.send(payload); -/// @returns display name for function/event eg. multiply(uint256) -> multiply -var extractDisplayName = function (name) { - var length = name.indexOf('('); - return length !== -1 ? name.substr(0, length) : name; -}; + if (!jsonrpc.isValidResponse(result)) { + console.log(result); + if(typeof result === 'object' && result.error && result.error.message) + console.error(result.error.message); + return null; + } + + // format the output + return (typeof data.outputFormatter === 'function') ? data.outputFormatter(result.result) : result.result; + } + + }; + + var setProvider = function (p) { + provider = p; + }; + + /*jshint maxparams:4 */ + var startPolling = function (data, pollId, callback, uninstall) { + polls.push({data: data, id: pollId, callback: callback, uninstall: uninstall}); + }; + /*jshint maxparams:3 */ -/// @returns overloaded part of function/event name -var extractTypeName = function (name) { - /// TODO: make it invulnerable - var length = name.indexOf('('); - return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : ""; -}; + var stopPolling = function (pollId) { + for (var i = polls.length; i--;) { + var poll = polls[i]; + if (poll.id === pollId) { + polls.splice(i, 1); + } + } + }; -/// Filters all function from input abi -/// @returns abi array with filtered objects of type 'function' -var filterFunctions = function (json) { - return json.filter(function (current) { - return current.type === 'function'; - }); -}; + var reset = function () { + polls.forEach(function (poll) { + poll.uninstall(poll.id); + }); + polls = []; -/// Filters all events form input abi -/// @returns abi array with filtered objects of type 'event' -var filterEvents = function (json) { - return json.filter(function (current) { - return current.type === 'event'; - }); -}; + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + poll(); + }; -/// used to transform value/string to eth string -/// TODO: use BigNumber.js to parse int -/// TODO: add tests for it! -var toEth = function (str) { - /*jshint maxcomplexity:7 */ - var val = typeof str === "string" ? str.indexOf('0x') === 0 ? parseInt(str.substr(2), 16) : parseInt(str) : str; - var unit = 0; - var units = c.ETH_UNITS; - while (val > 3000 && unit < units.length - 1) - { - val /= 1000; - unit++; - } - var s = val.toString().length < val.toFixed(2).length ? val.toString() : val.toFixed(2); - var replaceFunction = function($0, $1, $2) { - return $1 + ',' + $2; + var poll = function () { + polls.forEach(function (data) { + // send async + send(data.data, function(error, result){ + if (!(result instanceof Array) || result.length === 0) { + return; + } + data.callback(result); + }); + }); + timeout = setTimeout(poll, c.ETH_POLLING_TIMEOUT); }; + + poll(); - while (true) { - var o = s; - s = s.replace(/(\d)(\d\d\d[\.\,])/, replaceFunction); - if (o === s) - break; - } - return s + ' ' + units[unit]; + return { + send: send, + setProvider: setProvider, + startPolling: startPolling, + stopPolling: stopPolling, + reset: reset + }; }; -module.exports = { - findIndex: findIndex, - toAscii: toAscii, - fromAscii: fromAscii, - extractDisplayName: extractDisplayName, - extractTypeName: extractTypeName, - filterFunctions: filterFunctions, - filterEvents: filterEvents, - toEth: toEth -}; +module.exports = requestManager; -},{"./const":2}],17:[function(require,module,exports){ +},{"../utils/config":4,"./jsonrpc":14}],18:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -1609,41 +2697,34 @@ module.exports = { You should have received a copy of the GNU Lesser General Public License along with ethereum.js. If not, see . */ -/** @file watches.js +/** @file shh.js * @authors: * Marek Kotewicz * @date 2015 */ -/// @returns an array of objects describing web3.eth.watch api methods -var eth = function () { - var newFilter = function (args) { - return typeof args[0] === 'string' ? 'eth_newFilterString' : 'eth_newFilter'; - }; +var formatters = require('./formatters'); +/// @returns an array of objects describing web3.shh api methods +var methods = function () { return [ - { name: 'newFilter', call: newFilter }, - { name: 'uninstallFilter', call: 'eth_uninstallFilter' }, - { name: 'getMessages', call: 'eth_filterLogs' } - ]; -}; + { name: 'post', call: 'shh_post', inputFormatter: formatters.inputPostFormatter }, + { name: 'newIdentity', call: 'shh_newIdentity' }, + { name: 'hasIdentity', call: 'shh_hasIdentity' }, + { name: 'newGroup', call: 'shh_newGroup' }, + { name: 'addToGroup', call: 'shh_addToGroup' }, -/// @returns an array of objects describing web3.shh.watch api methods -var shh = function () { - return [ - { name: 'newFilter', call: 'shh_newFilter' }, - { name: 'uninstallFilter', call: 'shh_uninstallFilter' }, - { name: 'getMessages', call: 'shh_getMessages' } + // deprecated + { name: 'haveIdentity', call: 'shh_haveIdentity', newMethod: 'shh.hasIdentity' }, ]; }; module.exports = { - eth: eth, - shh: shh + methods: methods }; -},{}],18:[function(require,module,exports){ +},{"./formatters":12}],19:[function(require,module,exports){ /* This file is part of ethereum.js. @@ -1660,198 +2741,94 @@ module.exports = { You should have received a copy of the GNU Lesser General Public License along with ethereum.js. If not, see . */ -/** @file web3.js +/** @file signature.js * @authors: - * Jeffrey Wilcke * Marek Kotewicz - * Marian Oancea - * Gav Wood - * @date 2014 + * @date 2015 */ -if ("build" !== 'build') {/* - var BigNumber = require('bignumber.js'); -*/} - -var eth = require('./eth'); -var db = require('./db'); -var shh = require('./shh'); -var watches = require('./watches'); -var filter = require('./filter'); -var utils = require('./utils'); -var requestManager = require('./requestmanager'); - -/// @returns an array of objects describing web3 api methods -var web3Methods = function () { - return [ - { name: 'sha3', call: 'web3_sha3' } - ]; -}; - -/// creates methods in a given object based on method description on input -/// setups api calls for these methods -var setupMethods = function (obj, methods) { - methods.forEach(function (method) { - obj[method.name] = function () { - var args = Array.prototype.slice.call(arguments); - var call = typeof method.call === 'function' ? method.call(args) : method.call; - return web3.manager.send({ - method: call, - params: args - }); - }; - }); -}; - -/// creates properties in a given object based on properties description on input -/// setups api calls for these properties -var setupProperties = function (obj, properties) { - properties.forEach(function (property) { - var proto = {}; - proto.get = function () { - return web3.manager.send({ - method: property.getter - }); - }; - - if (property.setter) { - proto.set = function (val) { - return web3.manager.send({ - method: property.setter, - params: [val] - }); - }; - } - Object.defineProperty(obj, property.name, proto); - }); -}; - -/*jshint maxparams:4 */ -var startPolling = function (method, id, callback, uninstall) { - web3.manager.startPolling({ - method: method, - params: [id] - }, id, callback, uninstall); -}; -/*jshint maxparams:3 */ +var web3 = require('../web3'); +var c = require('../utils/config'); -var stopPolling = function (id) { - web3.manager.stopPolling(id); +/// @param function name for which we want to get signature +/// @returns signature of function with given name +var functionSignatureFromAscii = function (name) { + return web3.sha3(web3.fromAscii(name)).slice(0, 2 + c.ETH_SIGNATURE_LENGTH * 2); }; -var ethWatch = { - startPolling: startPolling.bind(null, 'eth_changed'), - stopPolling: stopPolling +/// @param event name for which we want to get signature +/// @returns signature of event with given name +var eventSignatureFromAscii = function (name) { + return web3.sha3(web3.fromAscii(name)); }; -var shhWatch = { - startPolling: startPolling.bind(null, 'shh_changed'), - stopPolling: stopPolling +module.exports = { + functionSignatureFromAscii: functionSignatureFromAscii, + eventSignatureFromAscii: eventSignatureFromAscii }; -/// setups web3 object, and it's in-browser executed methods -var web3 = { - manager: requestManager(), - providers: {}, - - /// @returns ascii string representation of hex value prefixed with 0x - toAscii: utils.toAscii, - - /// @returns hex representation (prefixed by 0x) of ascii string - fromAscii: utils.fromAscii, - - /// @returns decimal representaton of hex value prefixed by 0x - toDecimal: function (val) { - // remove 0x and place 0, if it's required - val = val.length > 2 ? val.substring(2) : "0"; - return (new BigNumber(val, 16).toString(10)); - }, - - /// @returns hex representation (prefixed by 0x) of decimal value - fromDecimal: function (val) { - return "0x" + (new BigNumber(val).toString(16)); - }, - /// used to transform value/string to eth string - toEth: utils.toEth, +},{"../utils/config":4,"../web3":6}],20:[function(require,module,exports){ +/* + This file is part of ethereum.js. - /// eth object prototype - eth: { - contractFromAbi: function (abi) { - return function(addr) { - // Default to address of Config. TODO: rremove prior to genesis. - addr = addr || '0xc6d9d2cd449a754c494264e1809c50e34d64562b'; - var ret = web3.eth.contract(addr, abi); - ret.address = addr; - return ret; - }; - }, + ethereum.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - canary: function (abi) { - return function(addr) { - // Default to address of Config. TODO: rremove prior to genesis. - addr = addr || '0xc6d9d2cd449a754c494264e1809c50e34d64562b'; - return addr; - }; - }, + ethereum.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. - /// @param filter may be a string, object or event - /// @param indexed is optional, this is an object with optional event indexed params - /// @param options is optional, this is an object with optional event options ('max'...) - /// TODO: fix it, 4 params? no way - /*jshint maxparams:4 */ - watch: function (fil, indexed, options, formatter) { - if (fil._isEvent) { - return fil(indexed, options); - } - return filter(fil, ethWatch, formatter); - } - /*jshint maxparams:3 */ - }, + You should have received a copy of the GNU Lesser General Public License + along with ethereum.js. If not, see . +*/ +/** @file watches.js + * @authors: + * Marek Kotewicz + * @date 2015 + */ - /// db object prototype - db: {}, +/// @returns an array of objects describing web3.eth.filter api methods +var eth = function () { + var newFilter = function (args) { + return typeof args[0] === 'string' ? 'eth_newBlockFilter' : 'eth_newFilter'; + }; - /// shh object prototype - shh: { - /// @param filter may be a string, object or event - watch: function (fil) { - return filter(fil, shhWatch); - } - }, - setProvider: function (provider) { - web3.manager.setProvider(provider); - }, - - /// Should be called to reset state of web3 object - /// Resets everything except manager - reset: function () { - web3.manager.reset(); - } + return [ + { name: 'newFilter', call: newFilter }, + { name: 'uninstallFilter', call: 'eth_uninstallFilter' }, + { name: 'getLogs', call: 'eth_getFilterLogs' } + ]; }; -/// setups all api methods -setupMethods(web3, web3Methods()); -setupMethods(web3.eth, eth.methods()); -setupProperties(web3.eth, eth.properties()); -setupMethods(web3.db, db.methods()); -setupMethods(web3.shh, shh.methods()); -setupMethods(ethWatch, watches.eth()); -setupMethods(shhWatch, watches.shh()); +/// @returns an array of objects describing web3.shh.watch api methods +var shh = function () { + return [ + { name: 'newFilter', call: 'shh_newFilter' }, + { name: 'uninstallFilter', call: 'shh_uninstallFilter' }, + { name: 'getLogs', call: 'shh_getMessages' } + ]; +}; -module.exports = web3; +module.exports = { + eth: eth, + shh: shh +}; -},{"./db":4,"./eth":5,"./filter":7,"./requestmanager":12,"./shh":13,"./utils":16,"./watches":17}],"web3":[function(require,module,exports){ +},{}],"web3":[function(require,module,exports){ var web3 = require('./lib/web3'); -web3.providers.HttpSyncProvider = require('./lib/httpsync'); -web3.providers.QtSyncProvider = require('./lib/qtsync'); -web3.eth.contract = require('./lib/contract'); -web3.abi = require('./lib/abi'); +web3.providers.HttpProvider = require('./lib/web3/httpprovider'); +web3.providers.QtSyncProvider = require('./lib/web3/qtsync'); +web3.eth.contract = require('./lib/web3/contract'); +web3.abi = require('./lib/solidity/abi'); module.exports = web3; -},{"./lib/abi":1,"./lib/contract":3,"./lib/httpsync":9,"./lib/qtsync":11,"./lib/web3":18}]},{},["web3"]) +},{"./lib/solidity/abi":1,"./lib/web3":6,"./lib/web3/contract":7,"./lib/web3/httpprovider":13,"./lib/web3/qtsync":16}]},{},["web3"]) //# sourceMappingURL=ethereum.js.map \ No newline at end of file diff --git a/libjsqrc/ethereumjs/dist/ethereum.js.map b/libjsqrc/ethereumjs/dist/ethereum.js.map index 2b788900e..6d9b9c45a 100644 --- a/libjsqrc/ethereumjs/dist/ethereum.js.map +++ b/libjsqrc/ethereumjs/dist/ethereum.js.map @@ -2,50 +2,54 @@ "version": 3, "sources": [ "node_modules/browserify/node_modules/browser-pack/_prelude.js", - "lib/abi.js", - "lib/const.js", - "lib/contract.js", - "lib/db.js", - "lib/eth.js", - "lib/event.js", - "lib/filter.js", - "lib/formatters.js", - "lib/httpsync.js", - "lib/jsonrpc.js", - "lib/qtsync.js", - "lib/requestmanager.js", - "lib/shh.js", - "lib/signature.js", - "lib/types.js", - "lib/utils.js", - "lib/watches.js", + "lib/solidity/abi.js", + "lib/solidity/formatters.js", + "lib/solidity/types.js", + "lib/utils/config.js", + "lib/utils/utils.js", "lib/web3.js", + "lib/web3/contract.js", + "lib/web3/db.js", + "lib/web3/eth.js", + "lib/web3/event.js", + "lib/web3/filter.js", + "lib/web3/formatters.js", + "lib/web3/httpprovider.js", + "lib/web3/jsonrpc.js", + "lib/web3/net.js", + "lib/web3/qtsync.js", + "lib/web3/requestmanager.js", + "lib/web3/shh.js", + "lib/web3/signature.js", + "lib/web3/watches.js", "index.js" ], "names": [], - "mappings": "AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA", + "mappings": "AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA", "file": "generated.js", "sourceRoot": "", "sourcesContent": [ "(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.\n*/\n/** @file abi.js\n * @authors:\n * Marek Kotewicz \n * Gav Wood \n * @date 2014\n */\n\nvar utils = require('./utils');\nvar types = require('./types');\nvar c = require('./const');\nvar f = require('./formatters');\n\nvar displayTypeError = function (type) {\n console.error('parser does not support type: ' + type);\n};\n\n/// This method should be called if we want to check if givent type is an array type\n/// @returns true if it is, otherwise false\nvar arrayType = function (type) {\n return type.slice(-2) === '[]';\n};\n\nvar dynamicTypeBytes = function (type, value) {\n // TODO: decide what to do with array of strings\n if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.\n return f.formatInputInt(value.length);\n return \"\";\n};\n\nvar inputTypes = types.inputTypes();\n\n/// Formats input params to bytes\n/// @param abi contract method inputs\n/// @param array of params that will be formatted to bytes\n/// @returns bytes representation of input params\nvar formatInput = function (inputs, params) {\n var bytes = \"\";\n var toAppendConstant = \"\";\n var toAppendArrayContent = \"\";\n\n /// first we iterate in search for dynamic\n inputs.forEach(function (input, index) {\n bytes += dynamicTypeBytes(input.type, params[index]);\n });\n\n inputs.forEach(function (input, i) {\n /*jshint maxcomplexity:5 */\n var typeMatch = false;\n for (var j = 0; j < inputTypes.length && !typeMatch; j++) {\n typeMatch = inputTypes[j].type(inputs[i].type, params[i]);\n }\n if (!typeMatch) {\n displayTypeError(inputs[i].type);\n }\n\n var formatter = inputTypes[j - 1].format;\n\n if (arrayType(inputs[i].type))\n toAppendArrayContent += params[i].reduce(function (acc, curr) {\n return acc + formatter(curr);\n }, \"\");\n else if (inputs[i].type === 'string')\n toAppendArrayContent += formatter(params[i]);\n else\n toAppendConstant += formatter(params[i]);\n });\n\n bytes += toAppendConstant + toAppendArrayContent;\n\n return bytes;\n};\n\nvar dynamicBytesLength = function (type) {\n if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.\n return c.ETH_PADDING * 2;\n return 0;\n};\n\nvar outputTypes = types.outputTypes();\n\n/// Formats output bytes back to param list\n/// @param contract abi method outputs\n/// @param bytes representtion of output\n/// @returns array of output params\nvar formatOutput = function (outs, output) {\n\n output = output.slice(2);\n var result = [];\n var padding = c.ETH_PADDING * 2;\n\n var dynamicPartLength = outs.reduce(function (acc, curr) {\n return acc + dynamicBytesLength(curr.type);\n }, 0);\n\n var dynamicPart = output.slice(0, dynamicPartLength);\n output = output.slice(dynamicPartLength);\n\n outs.forEach(function (out, i) {\n /*jshint maxcomplexity:6 */\n var typeMatch = false;\n for (var j = 0; j < outputTypes.length && !typeMatch; j++) {\n typeMatch = outputTypes[j].type(outs[i].type);\n }\n\n if (!typeMatch) {\n displayTypeError(outs[i].type);\n }\n\n var formatter = outputTypes[j - 1].format;\n if (arrayType(outs[i].type)) {\n var size = f.formatOutputUInt(dynamicPart.slice(0, padding));\n dynamicPart = dynamicPart.slice(padding);\n var array = [];\n for (var k = 0; k < size; k++) {\n array.push(formatter(output.slice(0, padding)));\n output = output.slice(padding);\n }\n result.push(array);\n }\n else if (types.prefixedType('string')(outs[i].type)) {\n dynamicPart = dynamicPart.slice(padding);\n result.push(formatter(output.slice(0, padding)));\n output = output.slice(padding);\n } else {\n result.push(formatter(output.slice(0, padding)));\n output = output.slice(padding);\n }\n });\n\n return result;\n};\n\n/// @param json abi for contract\n/// @returns input parser object for given json abi\n/// TODO: refactor creating the parser, do not double logic from contract\nvar inputParser = function (json) {\n var parser = {};\n json.forEach(function (method) {\n var displayName = utils.extractDisplayName(method.name);\n var typeName = utils.extractTypeName(method.name);\n\n var impl = function () {\n var params = Array.prototype.slice.call(arguments);\n return formatInput(method.inputs, params);\n };\n\n if (parser[displayName] === undefined) {\n parser[displayName] = impl;\n }\n\n parser[displayName][typeName] = impl;\n });\n\n return parser;\n};\n\n/// @param json abi for contract\n/// @returns output parser for given json abi\nvar outputParser = function (json) {\n var parser = {};\n json.forEach(function (method) {\n\n var displayName = utils.extractDisplayName(method.name);\n var typeName = utils.extractTypeName(method.name);\n\n var impl = function (output) {\n return formatOutput(method.outputs, output);\n };\n\n if (parser[displayName] === undefined) {\n parser[displayName] = impl;\n }\n\n parser[displayName][typeName] = impl;\n });\n\n return parser;\n};\n\nmodule.exports = {\n inputParser: inputParser,\n outputParser: outputParser,\n formatInput: formatInput,\n formatOutput: formatOutput\n};\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file const.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\n/// required to define ETH_BIGNUMBER_ROUNDING_MODE\nif (\"build\" !== 'build') {/*\n var BigNumber = require('bignumber.js'); // jshint ignore:line\n*/}\n\nvar ETH_UNITS = [ \n 'wei', \n 'Kwei', \n 'Mwei', \n 'Gwei', \n 'szabo', \n 'finney', \n 'ether', \n 'grand', \n 'Mether', \n 'Gether', \n 'Tether', \n 'Pether', \n 'Eether', \n 'Zether', \n 'Yether', \n 'Nether', \n 'Dether', \n 'Vether', \n 'Uether' \n];\n\nmodule.exports = {\n ETH_PADDING: 32,\n ETH_SIGNATURE_LENGTH: 4,\n ETH_UNITS: ETH_UNITS,\n ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN },\n ETH_POLLING_TIMEOUT: 1000\n};\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file contract.js\n * @authors:\n * Marek Kotewicz \n * @date 2014\n */\n\nvar web3 = require('./web3'); \nvar abi = require('./abi');\nvar utils = require('./utils');\nvar eventImpl = require('./event');\nvar signature = require('./signature');\n\nvar exportNatspecGlobals = function (vars) {\n // it's used byt natspec.js\n // TODO: figure out better way to solve this\n web3._currentContractAbi = vars.abi;\n web3._currentContractAddress = vars.address;\n web3._currentContractMethodName = vars.method;\n web3._currentContractMethodParams = vars.params;\n};\n\nvar addFunctionRelatedPropertiesToContract = function (contract) {\n \n contract.call = function (options) {\n contract._isTransact = false;\n contract._options = options;\n return contract;\n };\n\n contract.transact = function (options) {\n contract._isTransact = true;\n contract._options = options;\n return contract;\n };\n\n contract._options = {};\n ['gas', 'gasPrice', 'value', 'from'].forEach(function(p) {\n contract[p] = function (v) {\n contract._options[p] = v;\n return contract;\n };\n });\n\n};\n\nvar addFunctionsToContract = function (contract, desc, address) {\n var inputParser = abi.inputParser(desc);\n var outputParser = abi.outputParser(desc);\n\n // create contract functions\n utils.filterFunctions(desc).forEach(function (method) {\n\n var displayName = utils.extractDisplayName(method.name);\n var typeName = utils.extractTypeName(method.name);\n\n var impl = function () {\n /*jshint maxcomplexity:7 */\n var params = Array.prototype.slice.call(arguments);\n var sign = signature.functionSignatureFromAscii(method.name);\n var parsed = inputParser[displayName][typeName].apply(null, params);\n\n var options = contract._options || {};\n options.to = address;\n options.data = sign + parsed;\n \n var isTransact = contract._isTransact === true || (contract._isTransact !== false && !method.constant);\n var collapse = options.collapse !== false;\n \n // reset\n contract._options = {};\n contract._isTransact = null;\n\n if (isTransact) {\n \n exportNatspecGlobals({\n abi: desc,\n address: address,\n method: method.name,\n params: params\n });\n\n // transactions do not have any output, cause we do not know, when they will be processed\n web3.eth.transact(options);\n return;\n }\n \n var output = web3.eth.call(options);\n var ret = outputParser[displayName][typeName](output);\n if (collapse)\n {\n if (ret.length === 1)\n ret = ret[0];\n else if (ret.length === 0)\n ret = null;\n }\n return ret;\n };\n\n if (contract[displayName] === undefined) {\n contract[displayName] = impl;\n }\n\n contract[displayName][typeName] = impl;\n });\n};\n\nvar addEventRelatedPropertiesToContract = function (contract, desc, address) {\n contract.address = address;\n contract._onWatchEventResult = function (data) {\n var matchingEvent = event.getMatchingEvent(utils.filterEvents(desc));\n var parser = eventImpl.outputParser(matchingEvent);\n return parser(data);\n };\n \n Object.defineProperty(contract, 'topic', {\n get: function() {\n return utils.filterEvents(desc).map(function (e) {\n return signature.eventSignatureFromAscii(e.name);\n });\n }\n });\n\n};\n\nvar addEventsToContract = function (contract, desc, address) {\n // create contract events\n utils.filterEvents(desc).forEach(function (e) {\n\n var impl = function () {\n var params = Array.prototype.slice.call(arguments);\n var sign = signature.eventSignatureFromAscii(e.name);\n var event = eventImpl.inputParser(address, sign, e);\n var o = event.apply(null, params);\n var outputFormatter = function (data) {\n var parser = eventImpl.outputParser(e);\n return parser(data);\n };\n return web3.eth.watch(o, undefined, undefined, outputFormatter);\n };\n \n // this property should be used by eth.filter to check if object is an event\n impl._isEvent = true;\n\n var displayName = utils.extractDisplayName(e.name);\n var typeName = utils.extractTypeName(e.name);\n\n if (contract[displayName] === undefined) {\n contract[displayName] = impl;\n }\n\n contract[displayName][typeName] = impl;\n\n });\n};\n\n\n/**\n * This method should be called when we want to call / transact some solidity method from javascript\n * it returns an object which has same methods available as solidity contract description\n * usage example: \n *\n * var abi = [{\n * name: 'myMethod',\n * inputs: [{ name: 'a', type: 'string' }],\n * outputs: [{name: 'd', type: 'string' }]\n * }]; // contract abi\n *\n * var myContract = web3.eth.contract('0x0123123121', abi); // creation of contract object\n *\n * myContract.myMethod('this is test string param for call'); // myMethod call (implicit, default)\n * myContract.call().myMethod('this is test string param for call'); // myMethod call (explicit)\n * myContract.transact().myMethod('this is test string param for transact'); // myMethod transact\n *\n * @param address - address of the contract, which should be called\n * @param desc - abi json description of the contract, which is being created\n * @returns contract object\n */\n\nvar contract = function (address, desc) {\n\n // workaround for invalid assumption that method.name is the full anonymous prototype of the method.\n // it's not. it's just the name. the rest of the code assumes it's actually the anonymous\n // prototype, so we make it so as a workaround.\n // TODO: we may not want to modify input params, maybe use copy instead?\n desc.forEach(function (method) {\n if (method.name.indexOf('(') === -1) {\n var displayName = method.name;\n var typeName = method.inputs.map(function(i){return i.type; }).join();\n method.name = displayName + '(' + typeName + ')';\n }\n });\n\n var result = {};\n addFunctionRelatedPropertiesToContract(result);\n addFunctionsToContract(result, desc, address);\n addEventRelatedPropertiesToContract(result, desc, address);\n addEventsToContract(result, desc, address);\n\n return result;\n};\n\nmodule.exports = contract;\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file abi.js\n * @authors:\n * Marek Kotewicz \n * Gav Wood \n * @date 2014\n */\n\nvar utils = require('../utils/utils');\nvar c = require('../utils/config');\nvar types = require('./types');\nvar f = require('./formatters');\n\n/**\n * throw incorrect type error\n *\n * @method throwTypeError\n * @param {String} type\n * @throws incorrect type error\n */\nvar throwTypeError = function (type) {\n throw new Error('parser does not support type: ' + type);\n};\n\n/** This method should be called if we want to check if givent type is an array type\n *\n * @method isArrayType\n * @param {String} type name\n * @returns {Boolean} true if it is, otherwise false\n */\nvar isArrayType = function (type) {\n return type.slice(-2) === '[]';\n};\n\n/**\n * This method should be called to return dynamic type length in hex\n *\n * @method dynamicTypeBytes\n * @param {String} type\n * @param {String|Array} dynamic type\n * @return {String} length of dynamic type in hex or empty string if type is not dynamic\n */\nvar dynamicTypeBytes = function (type, value) {\n // TODO: decide what to do with array of strings\n if (isArrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.\n return f.formatInputInt(value.length);\n return \"\";\n};\n\nvar inputTypes = types.inputTypes();\n\n/**\n * Formats input params to bytes\n *\n * @method formatInput\n * @param {Array} abi inputs of method\n * @param {Array} params that will be formatted to bytes\n * @returns bytes representation of input params\n */\nvar formatInput = function (inputs, params) {\n var bytes = \"\";\n var toAppendConstant = \"\";\n var toAppendArrayContent = \"\";\n\n /// first we iterate in search for dynamic\n inputs.forEach(function (input, index) {\n bytes += dynamicTypeBytes(input.type, params[index]);\n });\n\n inputs.forEach(function (input, i) {\n /*jshint maxcomplexity:5 */\n var typeMatch = false;\n for (var j = 0; j < inputTypes.length && !typeMatch; j++) {\n typeMatch = inputTypes[j].type(inputs[i].type, params[i]);\n }\n if (!typeMatch) {\n throwTypeError(inputs[i].type);\n }\n\n var formatter = inputTypes[j - 1].format;\n\n if (isArrayType(inputs[i].type))\n toAppendArrayContent += params[i].reduce(function (acc, curr) {\n return acc + formatter(curr);\n }, \"\");\n else if (inputs[i].type === 'string')\n toAppendArrayContent += formatter(params[i]);\n else\n toAppendConstant += formatter(params[i]);\n });\n\n bytes += toAppendConstant + toAppendArrayContent;\n\n return bytes;\n};\n\n/**\n * This method should be called to predict the length of dynamic type\n *\n * @method dynamicBytesLength\n * @param {String} type\n * @returns {Number} length of dynamic type, 0 or multiplication of ETH_PADDING (32)\n */\nvar dynamicBytesLength = function (type) {\n if (isArrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.\n return c.ETH_PADDING * 2;\n return 0;\n};\n\nvar outputTypes = types.outputTypes();\n\n/** \n * Formats output bytes back to param list\n *\n * @method formatOutput\n * @param {Array} abi outputs of method\n * @param {String} bytes represention of output\n * @returns {Array} output params\n */\nvar formatOutput = function (outs, output) {\n\n output = output.slice(2);\n var result = [];\n var padding = c.ETH_PADDING * 2;\n\n var dynamicPartLength = outs.reduce(function (acc, curr) {\n return acc + dynamicBytesLength(curr.type);\n }, 0);\n\n var dynamicPart = output.slice(0, dynamicPartLength);\n output = output.slice(dynamicPartLength);\n\n outs.forEach(function (out, i) {\n /*jshint maxcomplexity:6 */\n var typeMatch = false;\n for (var j = 0; j < outputTypes.length && !typeMatch; j++) {\n typeMatch = outputTypes[j].type(outs[i].type);\n }\n\n if (!typeMatch) {\n throwTypeError(outs[i].type);\n }\n\n var formatter = outputTypes[j - 1].format;\n if (isArrayType(outs[i].type)) {\n var size = f.formatOutputUInt(dynamicPart.slice(0, padding));\n dynamicPart = dynamicPart.slice(padding);\n var array = [];\n for (var k = 0; k < size; k++) {\n array.push(formatter(output.slice(0, padding)));\n output = output.slice(padding);\n }\n result.push(array);\n }\n else if (types.prefixedType('string')(outs[i].type)) {\n dynamicPart = dynamicPart.slice(padding);\n result.push(formatter(output.slice(0, padding)));\n output = output.slice(padding);\n } else {\n result.push(formatter(output.slice(0, padding)));\n output = output.slice(padding);\n }\n });\n\n return result;\n};\n\n/**\n * Should be called to create input parser for contract with given abi\n *\n * @method inputParser\n * @param {Array} contract abi\n * @returns {Object} input parser object for given json abi\n * TODO: refactor creating the parser, do not double logic from contract\n */\nvar inputParser = function (json) {\n var parser = {};\n json.forEach(function (method) {\n var displayName = utils.extractDisplayName(method.name);\n var typeName = utils.extractTypeName(method.name);\n\n var impl = function () {\n var params = Array.prototype.slice.call(arguments);\n return formatInput(method.inputs, params);\n };\n\n if (parser[displayName] === undefined) {\n parser[displayName] = impl;\n }\n\n parser[displayName][typeName] = impl;\n });\n\n return parser;\n};\n\n/**\n * Should be called to create output parser for contract with given abi\n *\n * @method outputParser\n * @param {Array} contract abi\n * @returns {Object} output parser for given json abi\n */\nvar outputParser = function (json) {\n var parser = {};\n json.forEach(function (method) {\n\n var displayName = utils.extractDisplayName(method.name);\n var typeName = utils.extractTypeName(method.name);\n\n var impl = function (output) {\n return formatOutput(method.outputs, output);\n };\n\n if (parser[displayName] === undefined) {\n parser[displayName] = impl;\n }\n\n parser[displayName][typeName] = impl;\n });\n\n return parser;\n};\n\nmodule.exports = {\n inputParser: inputParser,\n outputParser: outputParser,\n formatInput: formatInput,\n formatOutput: formatOutput\n};\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file formatters.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\nif (\"build\" !== 'build') {/*\n var BigNumber = require('bignumber.js'); // jshint ignore:line\n*/}\n\nvar utils = require('../utils/utils');\nvar c = require('../utils/config');\n\n/**\n * Should be called to pad string to expected length\n *\n * @method padLeft\n * @param {String} string to be padded\n * @param {Number} characters that result string should have\n * @param {String} sign, by default 0\n * @returns {String} right aligned string\n */\nvar padLeft = function (string, chars, sign) {\n return new Array(chars - string.length + 1).join(sign ? sign : \"0\") + string;\n};\n\n/**\n * Formats input value to byte representation of int\n * If value is negative, return it's two's complement\n * If the value is floating point, round it down\n *\n * @method formatInputInt\n * @param {String|Number|BigNumber} value that needs to be formatted\n * @returns {String} right-aligned byte representation of int\n */\nvar formatInputInt = function (value) {\n var padding = c.ETH_PADDING * 2;\n BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);\n return padLeft(utils.toTwosComplement(value).round().toString(16), padding);\n};\n\n/**\n * Formats input value to byte representation of string\n *\n * @method formatInputString\n * @param {String}\n * @returns {String} left-algined byte representation of string\n */\nvar formatInputString = function (value) {\n return utils.fromAscii(value, c.ETH_PADDING).substr(2);\n};\n\n/**\n * Formats input value to byte representation of bool\n *\n * @method formatInputBool\n * @param {Boolean}\n * @returns {String} right-aligned byte representation bool\n */\nvar formatInputBool = function (value) {\n return '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');\n};\n\n/**\n * Formats input value to byte representation of real\n * Values are multiplied by 2^m and encoded as integers\n *\n * @method formatInputReal\n * @param {String|Number|BigNumber}\n * @returns {String} byte representation of real\n */\nvar formatInputReal = function (value) {\n return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128))); \n};\n\n/**\n * Check if input value is negative\n *\n * @method signedIsNegative\n * @param {String} value is hex format\n * @returns {Boolean} true if it is negative, otherwise false\n */\nvar signedIsNegative = function (value) {\n return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1';\n};\n\n/**\n * Formats right-aligned output bytes to int\n *\n * @method formatOutputInt\n * @param {String} bytes\n * @returns {BigNumber} right-aligned output bytes formatted to big number\n */\nvar formatOutputInt = function (value) {\n\n value = value || \"0\";\n\n // check if it's negative number\n // it it is, return two's complement\n if (signedIsNegative(value)) {\n return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1);\n }\n return new BigNumber(value, 16);\n};\n\n/**\n * Formats right-aligned output bytes to uint\n *\n * @method formatOutputUInt\n * @param {String} bytes\n * @returns {BigNumeber} right-aligned output bytes formatted to uint\n */\nvar formatOutputUInt = function (value) {\n value = value || \"0\";\n return new BigNumber(value, 16);\n};\n\n/**\n * Formats right-aligned output bytes to real\n *\n * @method formatOutputReal\n * @param {String}\n * @returns {BigNumber} input bytes formatted to real\n */\nvar formatOutputReal = function (value) {\n return formatOutputInt(value).dividedBy(new BigNumber(2).pow(128)); \n};\n\n/**\n * Formats right-aligned output bytes to ureal\n *\n * @method formatOutputUReal\n * @param {String}\n * @returns {BigNumber} input bytes formatted to ureal\n */\nvar formatOutputUReal = function (value) {\n return formatOutputUInt(value).dividedBy(new BigNumber(2).pow(128)); \n};\n\n/**\n * Should be used to format output hash\n *\n * @method formatOutputHash\n * @param {String}\n * @returns {String} right-aligned output bytes formatted to hex\n */\nvar formatOutputHash = function (value) {\n return \"0x\" + value;\n};\n\n/**\n * Should be used to format output bool\n *\n * @method formatOutputBool\n * @param {String}\n * @returns {Boolean} right-aligned input bytes formatted to bool\n */\nvar formatOutputBool = function (value) {\n return value === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;\n};\n\n/**\n * Should be used to format output string\n *\n * @method formatOutputString\n * @param {Sttring} left-aligned hex representation of string\n * @returns {String} ascii string\n */\nvar formatOutputString = function (value) {\n return utils.toAscii(value);\n};\n\n/**\n * Should be used to format output address\n *\n * @method formatOutputAddress\n * @param {String} right-aligned input bytes\n * @returns {String} address\n */\nvar formatOutputAddress = function (value) {\n return \"0x\" + value.slice(value.length - 40, value.length);\n};\n\nmodule.exports = {\n formatInputInt: formatInputInt,\n formatInputString: formatInputString,\n formatInputBool: formatInputBool,\n formatInputReal: formatInputReal,\n formatOutputInt: formatOutputInt,\n formatOutputUInt: formatOutputUInt,\n formatOutputReal: formatOutputReal,\n formatOutputUReal: formatOutputUReal,\n formatOutputHash: formatOutputHash,\n formatOutputBool: formatOutputBool,\n formatOutputString: formatOutputString,\n formatOutputAddress: formatOutputAddress\n};\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file types.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\nvar f = require('./formatters');\n\n/// @param expected type prefix (string)\n/// @returns function which checks if type has matching prefix. if yes, returns true, otherwise false\nvar prefixedType = function (prefix) {\n return function (type) {\n return type.indexOf(prefix) === 0;\n };\n};\n\n/// @param expected type name (string)\n/// @returns function which checks if type is matching expected one. if yes, returns true, otherwise false\nvar namedType = function (name) {\n return function (type) {\n return name === type;\n };\n};\n\n/// Setups input formatters for solidity types\n/// @returns an array of input formatters \nvar inputTypes = function () {\n \n return [\n { type: prefixedType('uint'), format: f.formatInputInt },\n { type: prefixedType('int'), format: f.formatInputInt },\n { type: prefixedType('hash'), format: f.formatInputInt },\n { type: prefixedType('string'), format: f.formatInputString }, \n { type: prefixedType('real'), format: f.formatInputReal },\n { type: prefixedType('ureal'), format: f.formatInputReal },\n { type: namedType('address'), format: f.formatInputInt },\n { type: namedType('bool'), format: f.formatInputBool }\n ];\n};\n\n/// Setups output formaters for solidity types\n/// @returns an array of output formatters\nvar outputTypes = function () {\n\n return [\n { type: prefixedType('uint'), format: f.formatOutputUInt },\n { type: prefixedType('int'), format: f.formatOutputInt },\n { type: prefixedType('hash'), format: f.formatOutputHash },\n { type: prefixedType('string'), format: f.formatOutputString },\n { type: prefixedType('real'), format: f.formatOutputReal },\n { type: prefixedType('ureal'), format: f.formatOutputUReal },\n { type: namedType('address'), format: f.formatOutputAddress },\n { type: namedType('bool'), format: f.formatOutputBool }\n ];\n};\n\nmodule.exports = {\n prefixedType: prefixedType,\n namedType: namedType,\n inputTypes: inputTypes,\n outputTypes: outputTypes\n};\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file config.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\n/**\n * Utils\n * \n * @module utils\n */\n\n/**\n * Utility functions\n * \n * @class [utils] config\n * @constructor\n */\n\n/// required to define ETH_BIGNUMBER_ROUNDING_MODE\nif (\"build\" !== 'build') {/*\n var BigNumber = require('bignumber.js'); // jshint ignore:line\n*/}\n\nvar ETH_UNITS = [ \n 'wei', \n 'Kwei', \n 'Mwei', \n 'Gwei', \n 'szabo', \n 'finney', \n 'ether', \n 'grand', \n 'Mether', \n 'Gether', \n 'Tether', \n 'Pether', \n 'Eether', \n 'Zether', \n 'Yether', \n 'Nether', \n 'Dether', \n 'Vether', \n 'Uether' \n];\n\nmodule.exports = {\n ETH_PADDING: 32,\n ETH_SIGNATURE_LENGTH: 4,\n ETH_UNITS: ETH_UNITS,\n ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN },\n ETH_POLLING_TIMEOUT: 1000,\n ETH_DEFAULTBLOCK: 'latest'\n};\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file utils.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\n/**\n * Utils\n * \n * @module utils\n */\n\n/**\n * Utility functions\n * \n * @class [utils] utils\n * @constructor\n */\n\nif (\"build\" !== 'build') {/*\n var BigNumber = require('bignumber.js'); // jshint ignore:line\n*/}\n\nvar unitMap = {\n 'wei': '1',\n 'kwei': '1000',\n 'ada': '1000',\n 'mwei': '1000000',\n 'babbage': '1000000',\n 'gwei': '1000000000',\n 'shannon': '1000000000',\n 'szabo': '1000000000000',\n 'finney': '1000000000000000',\n 'ether': '1000000000000000000',\n 'kether': '1000000000000000000000',\n 'grand': '1000000000000000000000',\n 'einstein': '1000000000000000000000',\n 'mether': '1000000000000000000000000',\n 'gether': '1000000000000000000000000000',\n 'tether': '1000000000000000000000000000000'\n};\n\n\n/** Finds first index of array element matching pattern\n *\n * @method findIndex\n * @param {Array}\n * @param {Function} pattern\n * @returns {Number} index of element\n */\nvar findIndex = function (array, callback) {\n var end = false;\n var i = 0;\n for (; i < array.length && !end; i++) {\n end = callback(array[i]);\n }\n return end ? i - 1 : -1;\n};\n\n/** \n * Should be called to get sting from it's hex representation\n *\n * @method toAscii\n * @param {String} string in hex\n * @returns {String} ascii string representation of hex value\n */\nvar toAscii = function(hex) {\n// Find termination\n var str = \"\";\n var i = 0, l = hex.length;\n if (hex.substring(0, 2) === '0x') {\n i = 2;\n }\n for (; i < l; i+=2) {\n var code = parseInt(hex.substr(i, 2), 16);\n if (code === 0) {\n break;\n }\n\n str += String.fromCharCode(code);\n }\n\n return str;\n};\n \n/**\n * Shold be called to get hex representation (prefixed by 0x) of ascii string \n *\n * @method fromAscii\n * @param {String} string\n * @returns {String} hex representation of input string\n */\nvar toHexNative = function(str) {\n var hex = \"\";\n for(var i = 0; i < str.length; i++) {\n var n = str.charCodeAt(i).toString(16);\n hex += n.length < 2 ? '0' + n : n;\n }\n\n return hex;\n};\n\n/**\n * Shold be called to get hex representation (prefixed by 0x) of ascii string \n *\n * @method fromAscii\n * @param {String} string\n * @param {Number} optional padding\n * @returns {String} hex representation of input string\n */\nvar fromAscii = function(str, pad) {\n pad = pad === undefined ? 0 : pad;\n var hex = toHexNative(str);\n while (hex.length < pad*2)\n hex += \"00\";\n return \"0x\" + hex;\n};\n\n/**\n * Should be called to get display name of contract function\n * \n * @method extractDisplayName\n * @param {String} name of function/event\n * @returns {String} display name for function/event eg. multiply(uint256) -> multiply\n */\nvar extractDisplayName = function (name) {\n var length = name.indexOf('('); \n return length !== -1 ? name.substr(0, length) : name;\n};\n\n/// @returns overloaded part of function/event name\nvar extractTypeName = function (name) {\n /// TODO: make it invulnerable\n var length = name.indexOf('(');\n return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : \"\";\n};\n\n/**\n * Filters all functions from input abi\n *\n * @method filterFunctions\n * @param {Array} abi\n * @returns {Array} abi array with filtered objects of type 'function'\n */\nvar filterFunctions = function (json) {\n return json.filter(function (current) {\n return current.type === 'function'; \n }); \n};\n\n/**\n * Filters all events from input abi\n *\n * @method filterEvents\n * @param {Array} abi\n * @returns {Array} abi array with filtered objects of type 'event'\n */\nvar filterEvents = function (json) {\n return json.filter(function (current) {\n return current.type === 'event';\n });\n};\n\n/**\n * Converts value to it's decimal representation in string\n *\n * @method toDecimal\n * @param {String|Number|BigNumber}\n * @return {String}\n */\nvar toDecimal = function (value) {\n return toBigNumber(value).toNumber();\n};\n\n/**\n * Converts value to it's hex representation\n *\n * @method fromDecimal\n * @param {String|Number|BigNumber}\n * @return {String}\n */\nvar fromDecimal = function (value) {\n var number = toBigNumber(value);\n var result = number.toString(16);\n\n return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result;\n};\n\n/**\n * Auto converts any given value into it's hex representation.\n *\n * And even stringifys objects before.\n *\n * @method toHex\n * @param {String|Number|BigNumber|Object}\n * @return {String}\n */\nvar toHex = function (val) {\n /*jshint maxcomplexity:7 */\n\n if(isBoolean(val))\n return val;\n\n if(isBigNumber(val))\n return fromDecimal(val);\n\n if(isObject(val))\n return fromAscii(JSON.stringify(val));\n\n // if its a negative number, pass it through fromDecimal\n if (isString(val)) {\n if (val.indexOf('-0x') === 0)\n return fromDecimal(val);\n else if (!isFinite(val))\n return fromAscii(val);\n }\n\n return fromDecimal(val);\n};\n\n/**\n * Returns value of unit in Wei\n *\n * @method getValueOfUnit\n * @param {String} unit the unit to convert to, default ether\n * @returns {BigNumber} value of the unit (in Wei)\n * @throws error if the unit is not correct:w\n */\nvar getValueOfUnit = function (unit) {\n unit = unit ? unit.toLowerCase() : 'ether';\n var unitValue = unitMap[unit];\n if (unitValue === undefined) {\n throw new Error('This unit doesn\\'t exists, please use the one of the following units' + JSON.stringify(unitMap, null, 2));\n }\n return new BigNumber(unitValue, 10);\n};\n\n/**\n * Takes a number of wei and converts it to any other ether unit.\n *\n * Possible units are:\n * - kwei/ada\n * - mwei/babbage\n * - gwei/shannon\n * - szabo\n * - finney\n * - ether\n * - kether/grand/einstein\n * - mether\n * - gether\n * - tether\n *\n * @method fromWei\n * @param {Number|String} number can be a number, number string or a HEX of a decimal\n * @param {String} unit the unit to convert to, default ether\n * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number\n*/\nvar fromWei = function(number, unit) {\n var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit));\n\n return isBigNumber(number) ? returnValue : returnValue.toString(10); \n};\n\n/**\n * Takes a number of a unit and converts it to wei.\n *\n * Possible units are:\n * - kwei/ada\n * - mwei/babbage\n * - gwei/shannon\n * - szabo\n * - finney\n * - ether\n * - kether/grand/einstein\n * - mether\n * - gether\n * - tether\n *\n * @method toWei\n * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal\n * @param {String} unit the unit to convert from, default ether\n * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number\n*/\nvar toWei = function(number, unit) {\n var returnValue = toBigNumber(number).times(getValueOfUnit(unit));\n\n return isBigNumber(number) ? returnValue : returnValue.toString(10); \n};\n\n/**\n * Takes an input and transforms it into an bignumber\n *\n * @method toBigNumber\n * @param {Number|String|BigNumber} a number, string, HEX string or BigNumber\n * @return {BigNumber} BigNumber\n*/\nvar toBigNumber = function(number) {\n /*jshint maxcomplexity:5 */\n number = number || 0;\n if (isBigNumber(number))\n return number;\n\n if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) {\n return new BigNumber(number.replace('0x',''), 16);\n }\n \n return new BigNumber(number.toString(10), 10);\n};\n\n/**\n * Takes and input transforms it into bignumber and if it is negative value, into two's complement\n *\n * @method toTwosComplement\n * @param {Number|String|BigNumber}\n * @return {BigNumber}\n */\nvar toTwosComplement = function (number) {\n var bigNumber = toBigNumber(number);\n if (bigNumber.lessThan(0)) {\n return new BigNumber(\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 16).plus(bigNumber).plus(1);\n }\n return bigNumber;\n};\n\n/**\n * Checks if the given string has proper length\n *\n * @method isAddress\n * @param {String} address the given HEX adress\n * @return {Boolean}\n*/\nvar isAddress = function(address) {\n if (!isString(address)) {\n return false;\n }\n\n return ((address.indexOf('0x') === 0 && address.length === 42) ||\n (address.indexOf('0x') === -1 && address.length === 40));\n};\n\n/**\n * Returns true if object is BigNumber, otherwise false\n *\n * @method isBigNumber\n * @param {Object}\n * @return {Boolean} \n */\nvar isBigNumber = function (object) {\n return object instanceof BigNumber ||\n (object && object.constructor && object.constructor.name === 'BigNumber');\n};\n\n/**\n * Returns true if object is string, otherwise false\n * \n * @method isString\n * @param {Object}\n * @return {Boolean}\n */\nvar isString = function (object) {\n return typeof object === 'string' ||\n (object && object.constructor && object.constructor.name === 'String');\n};\n\n/**\n * Returns true if object is function, otherwise false\n *\n * @method isFunction\n * @param {Object}\n * @return {Boolean}\n */\nvar isFunction = function (object) {\n return typeof object === 'function';\n};\n\n/**\n * Returns true if object is Objet, otherwise false\n *\n * @method isObject\n * @param {Object}\n * @return {Boolean}\n */\nvar isObject = function (object) {\n return typeof object === 'object';\n};\n\n/**\n * Returns true if object is boolean, otherwise false\n *\n * @method isBoolean\n * @param {Object}\n * @return {Boolean}\n */\nvar isBoolean = function (object) {\n return typeof object === 'boolean';\n};\n\n/**\n * Returns true if object is array, otherwise false\n *\n * @method isArray\n * @param {Object}\n * @return {Boolean}\n */\nvar isArray = function (object) {\n return object instanceof Array; \n};\n\nmodule.exports = {\n findIndex: findIndex,\n toHex: toHex,\n toDecimal: toDecimal,\n fromDecimal: fromDecimal,\n toAscii: toAscii,\n fromAscii: fromAscii,\n extractDisplayName: extractDisplayName,\n extractTypeName: extractTypeName,\n filterFunctions: filterFunctions,\n filterEvents: filterEvents,\n toWei: toWei,\n fromWei: fromWei,\n toBigNumber: toBigNumber,\n toTwosComplement: toTwosComplement,\n isBigNumber: isBigNumber,\n isAddress: isAddress,\n isFunction: isFunction,\n isString: isString,\n isObject: isObject,\n isBoolean: isBoolean,\n isArray: isArray\n};\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file web3.js\n * @authors:\n * Jeffrey Wilcke \n * Marek Kotewicz \n * Marian Oancea \n * Gav Wood \n * @date 2014\n */\n\nvar net = require('./web3/net');\nvar eth = require('./web3/eth');\nvar db = require('./web3/db');\nvar shh = require('./web3/shh');\nvar watches = require('./web3/watches');\nvar filter = require('./web3/filter');\nvar utils = require('./utils/utils');\nvar formatters = require('./solidity/formatters');\nvar requestManager = require('./web3/requestmanager');\nvar c = require('./utils/config');\n\n/// @returns an array of objects describing web3 api methods\nvar web3Methods = function () {\n return [\n { name: 'sha3', call: 'web3_sha3' }\n ];\n};\n\n/// creates methods in a given object based on method description on input\n/// setups api calls for these methods\nvar setupMethods = function (obj, methods) {\n methods.forEach(function (method) {\n // allow for object methods 'myObject.method'\n var objectMethods = method.name.split('.'),\n callFunction = function () {\n /*jshint maxcomplexity:8 */\n \n var callback = null,\n args = Array.prototype.slice.call(arguments),\n call = typeof method.call === 'function' ? method.call(args) : method.call;\n\n // get the callback if one is available\n if(typeof args[args.length-1] === 'function'){\n callback = args[args.length-1];\n Array.prototype.pop.call(args);\n }\n\n // add the defaultBlock if not given\n if(method.addDefaultblock) {\n if(args.length !== method.addDefaultblock)\n Array.prototype.push.call(args, (isFinite(c.ETH_DEFAULTBLOCK) ? utils.fromDecimal(c.ETH_DEFAULTBLOCK) : c.ETH_DEFAULTBLOCK));\n else\n args[args.length-1] = isFinite(args[args.length-1]) ? utils.fromDecimal(args[args.length-1]) : args[args.length-1];\n }\n\n // show deprecated warning\n if(method.newMethod)\n console.warn('This method is deprecated please use web3.'+ method.newMethod +'() instead.');\n\n return web3.manager.send({\n method: call,\n params: args,\n outputFormatter: method.outputFormatter,\n inputFormatter: method.inputFormatter,\n addDefaultblock: method.addDefaultblock\n }, callback);\n };\n\n if(objectMethods.length > 1) {\n if(!obj[objectMethods[0]])\n obj[objectMethods[0]] = {};\n\n obj[objectMethods[0]][objectMethods[1]] = callFunction;\n \n } else {\n\n obj[objectMethods[0]] = callFunction;\n }\n\n });\n};\n\n/// creates properties in a given object based on properties description on input\n/// setups api calls for these properties\nvar setupProperties = function (obj, properties) {\n properties.forEach(function (property) {\n var proto = {};\n proto.get = function () {\n\n // show deprecated warning\n if(property.newProperty)\n console.warn('This property is deprecated please use web3.'+ property.newProperty +' instead.');\n\n\n return web3.manager.send({\n method: property.getter,\n outputFormatter: property.outputFormatter\n });\n };\n\n if (property.setter) {\n proto.set = function (val) {\n\n // show deprecated warning\n if(property.newProperty)\n console.warn('This property is deprecated please use web3.'+ property.newProperty +' instead.');\n\n return web3.manager.send({\n method: property.setter,\n params: [val],\n inputFormatter: property.inputFormatter\n });\n };\n }\n\n proto.enumerable = !property.newProperty;\n Object.defineProperty(obj, property.name, proto);\n\n });\n};\n\n/*jshint maxparams:4 */\nvar startPolling = function (method, id, callback, uninstall) {\n web3.manager.startPolling({\n method: method, \n params: [id]\n }, id, callback, uninstall); \n};\n/*jshint maxparams:3 */\n\nvar stopPolling = function (id) {\n web3.manager.stopPolling(id);\n};\n\nvar ethWatch = {\n startPolling: startPolling.bind(null, 'eth_getFilterChanges'), \n stopPolling: stopPolling\n};\n\nvar shhWatch = {\n startPolling: startPolling.bind(null, 'shh_getFilterChanges'), \n stopPolling: stopPolling\n};\n\n/// setups web3 object, and it's in-browser executed methods\nvar web3 = {\n manager: requestManager(),\n providers: {},\n\n setProvider: function (provider) {\n web3.manager.setProvider(provider);\n },\n \n /// Should be called to reset state of web3 object\n /// Resets everything except manager\n reset: function () {\n web3.manager.reset(); \n },\n\n /// @returns hex string of the input\n toHex: utils.toHex,\n\n /// @returns ascii string representation of hex value prefixed with 0x\n toAscii: utils.toAscii,\n\n /// @returns hex representation (prefixed by 0x) of ascii string\n fromAscii: utils.fromAscii,\n\n /// @returns decimal representaton of hex value prefixed by 0x\n toDecimal: utils.toDecimal,\n\n /// @returns hex representation (prefixed by 0x) of decimal value\n fromDecimal: utils.fromDecimal,\n\n /// @returns a BigNumber object\n toBigNumber: utils.toBigNumber,\n\n toWei: utils.toWei,\n fromWei: utils.fromWei,\n isAddress: utils.isAddress,\n\n // provide network information\n net: {\n // peerCount: \n },\n\n\n /// eth object prototype\n eth: {\n // DEPRECATED\n contractFromAbi: function (abi) {\n console.warn('Initiating a contract like this is deprecated please use var MyContract = eth.contract(abi); new MyContract(address); instead.');\n\n return function(addr) {\n // Default to address of Config. TODO: rremove prior to genesis.\n addr = addr || '0xc6d9d2cd449a754c494264e1809c50e34d64562b';\n var ret = web3.eth.contract(addr, abi);\n ret.address = addr;\n return ret;\n };\n },\n\n /// @param filter may be a string, object or event\n /// @param eventParams is optional, this is an object with optional event eventParams params\n /// @param options is optional, this is an object with optional event options ('max'...)\n /*jshint maxparams:4 */\n filter: function (fil, eventParams, options) {\n\n // if its event, treat it differently\n if (fil._isEvent)\n return fil(eventParams, options);\n\n return filter(fil, ethWatch, formatters.outputLogFormatter);\n },\n // DEPRECATED\n watch: function (fil, eventParams, options) {\n console.warn('eth.watch() is deprecated please use eth.filter() instead.');\n return this.filter(fil, eventParams, options);\n }\n /*jshint maxparams:3 */\n },\n\n /// db object prototype\n db: {},\n\n /// shh object prototype\n shh: {\n /// @param filter may be a string, object or event\n filter: function (fil) {\n return filter(fil, shhWatch, formatters.outputPostFormatter);\n },\n // DEPRECATED\n watch: function (fil) {\n console.warn('shh.watch() is deprecated please use shh.filter() instead.');\n return this.filter(fil);\n }\n }\n};\n\n\n// ADD defaultblock\nObject.defineProperty(web3.eth, 'defaultBlock', {\n get: function () {\n return c.ETH_DEFAULTBLOCK;\n },\n set: function (val) {\n c.ETH_DEFAULTBLOCK = val;\n return c.ETH_DEFAULTBLOCK;\n }\n});\n\n\n/// setups all api methods\nsetupMethods(web3, web3Methods());\nsetupMethods(web3.net, net.methods);\nsetupProperties(web3.net, net.properties);\nsetupMethods(web3.eth, eth.methods);\nsetupProperties(web3.eth, eth.properties);\nsetupMethods(web3.db, db.methods());\nsetupMethods(web3.shh, shh.methods());\nsetupMethods(ethWatch, watches.eth());\nsetupMethods(shhWatch, watches.shh());\n\nmodule.exports = web3;\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file contract.js\n * @authors:\n * Marek Kotewicz \n * @date 2014\n */\n\nvar web3 = require('../web3'); \nvar abi = require('../solidity/abi');\nvar utils = require('../utils/utils');\nvar eventImpl = require('./event');\nvar signature = require('./signature');\n\nvar exportNatspecGlobals = function (vars) {\n // it's used byt natspec.js\n // TODO: figure out better way to solve this\n web3._currentContractAbi = vars.abi;\n web3._currentContractAddress = vars.address;\n web3._currentContractMethodName = vars.method;\n web3._currentContractMethodParams = vars.params;\n};\n\nvar addFunctionRelatedPropertiesToContract = function (contract) {\n \n contract.call = function (options) {\n contract._isTransaction = false;\n contract._options = options;\n return contract;\n };\n\n\n contract.sendTransaction = function (options) {\n contract._isTransaction = true;\n contract._options = options;\n return contract;\n };\n // DEPRECATED\n contract.transact = function (options) {\n\n console.warn('myContract.transact() is deprecated please use myContract.sendTransaction() instead.');\n\n return contract.sendTransaction(options);\n };\n\n contract._options = {};\n ['gas', 'gasPrice', 'value', 'from'].forEach(function(p) {\n contract[p] = function (v) {\n contract._options[p] = v;\n return contract;\n };\n });\n\n};\n\nvar addFunctionsToContract = function (contract, desc, address) {\n var inputParser = abi.inputParser(desc);\n var outputParser = abi.outputParser(desc);\n\n // create contract functions\n utils.filterFunctions(desc).forEach(function (method) {\n\n var displayName = utils.extractDisplayName(method.name);\n var typeName = utils.extractTypeName(method.name);\n\n var impl = function () {\n /*jshint maxcomplexity:7 */\n var params = Array.prototype.slice.call(arguments);\n var sign = signature.functionSignatureFromAscii(method.name);\n var parsed = inputParser[displayName][typeName].apply(null, params);\n\n var options = contract._options || {};\n options.to = address;\n options.data = sign + parsed;\n \n var isTransaction = contract._isTransaction === true || (contract._isTransaction !== false && !method.constant);\n var collapse = options.collapse !== false;\n \n // reset\n contract._options = {};\n contract._isTransaction = null;\n\n if (isTransaction) {\n \n exportNatspecGlobals({\n abi: desc,\n address: address,\n method: method.name,\n params: params\n });\n\n // transactions do not have any output, cause we do not know, when they will be processed\n web3.eth.sendTransaction(options);\n return;\n }\n \n var output = web3.eth.call(options);\n var ret = outputParser[displayName][typeName](output);\n if (collapse)\n {\n if (ret.length === 1)\n ret = ret[0];\n else if (ret.length === 0)\n ret = null;\n }\n return ret;\n };\n\n if (contract[displayName] === undefined) {\n contract[displayName] = impl;\n }\n\n contract[displayName][typeName] = impl;\n });\n};\n\nvar addEventRelatedPropertiesToContract = function (contract, desc, address) {\n contract.address = address;\n contract._onWatchEventResult = function (data) {\n var matchingEvent = event.getMatchingEvent(utils.filterEvents(desc));\n var parser = eventImpl.outputParser(matchingEvent);\n return parser(data);\n };\n \n Object.defineProperty(contract, 'topics', {\n get: function() {\n return utils.filterEvents(desc).map(function (e) {\n return signature.eventSignatureFromAscii(e.name);\n });\n }\n });\n\n};\n\nvar addEventsToContract = function (contract, desc, address) {\n // create contract events\n utils.filterEvents(desc).forEach(function (e) {\n\n var impl = function () {\n var params = Array.prototype.slice.call(arguments);\n var sign = signature.eventSignatureFromAscii(e.name);\n var event = eventImpl.inputParser(address, sign, e);\n var o = event.apply(null, params);\n var outputFormatter = function (data) {\n var parser = eventImpl.outputParser(e);\n return parser(data);\n };\n return web3.eth.filter(o, undefined, undefined, outputFormatter);\n };\n \n // this property should be used by eth.filter to check if object is an event\n impl._isEvent = true;\n\n var displayName = utils.extractDisplayName(e.name);\n var typeName = utils.extractTypeName(e.name);\n\n if (contract[displayName] === undefined) {\n contract[displayName] = impl;\n }\n\n contract[displayName][typeName] = impl;\n\n });\n};\n\n\n/**\n * This method should be called when we want to call / transact some solidity method from javascript\n * it returns an object which has same methods available as solidity contract description\n * usage example: \n *\n * var abi = [{\n * name: 'myMethod',\n * inputs: [{ name: 'a', type: 'string' }],\n * outputs: [{name: 'd', type: 'string' }]\n * }]; // contract abi\n *\n * var MyContract = web3.eth.contract(abi); // creation of contract prototype\n *\n * var contractInstance = new MyContract('0x0123123121');\n *\n * contractInstance.myMethod('this is test string param for call'); // myMethod call (implicit, default)\n * contractInstance.call().myMethod('this is test string param for call'); // myMethod call (explicit)\n * contractInstance.sendTransaction().myMethod('this is test string param for transact'); // myMethod sendTransaction\n *\n * @param abi - abi json description of the contract, which is being created\n * @returns contract object\n */\nvar contract = function (abi) {\n\n // return prototype\n if(abi instanceof Array && arguments.length === 1) {\n return Contract.bind(null, abi);\n\n // deprecated: auto initiate contract\n } else {\n\n console.warn('Initiating a contract like this is deprecated please use var MyContract = eth.contract(abi); new MyContract(address); instead.');\n\n return new Contract(arguments[1], arguments[0]);\n }\n\n};\n\nfunction Contract(abi, address) {\n\n // workaround for invalid assumption that method.name is the full anonymous prototype of the method.\n // it's not. it's just the name. the rest of the code assumes it's actually the anonymous\n // prototype, so we make it so as a workaround.\n // TODO: we may not want to modify input params, maybe use copy instead?\n abi.forEach(function (method) {\n if (method.name.indexOf('(') === -1) {\n var displayName = method.name;\n var typeName = method.inputs.map(function(i){return i.type; }).join();\n method.name = displayName + '(' + typeName + ')';\n }\n });\n\n var result = {};\n addFunctionRelatedPropertiesToContract(result);\n addFunctionsToContract(result, abi, address);\n addEventRelatedPropertiesToContract(result, abi, address);\n addEventsToContract(result, abi, address);\n\n return result;\n}\n\nmodule.exports = contract;\n\n", "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file db.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\n/// @returns an array of objects describing web3.db api methods\nvar methods = function () {\n return [\n { name: 'put', call: 'db_put' },\n { name: 'get', call: 'db_get' },\n { name: 'putString', call: 'db_putString' },\n { name: 'getString', call: 'db_getString' }\n ];\n};\n\nmodule.exports = {\n methods: methods\n};\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file eth.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\n/// @returns an array of objects describing web3.eth api methods\nvar methods = function () {\n var blockCall = function (args) {\n return typeof args[0] === \"string\" ? \"eth_blockByHash\" : \"eth_blockByNumber\";\n };\n\n var transactionCall = function (args) {\n return typeof args[0] === \"string\" ? 'eth_transactionByHash' : 'eth_transactionByNumber';\n };\n\n var uncleCall = function (args) {\n return typeof args[0] === \"string\" ? 'eth_uncleByHash' : 'eth_uncleByNumber';\n };\n\n var transactionCountCall = function (args) {\n return typeof args[0] === \"string\" ? 'eth_transactionCountByHash' : 'eth_transactionCountByNumber';\n };\n\n var uncleCountCall = function (args) {\n return typeof args[0] === \"string\" ? 'eth_uncleCountByHash' : 'eth_uncleCountByNumber';\n };\n\n return [\n { name: 'balanceAt', call: 'eth_balanceAt' },\n { name: 'stateAt', call: 'eth_stateAt' },\n { name: 'storageAt', call: 'eth_storageAt' },\n { name: 'countAt', call: 'eth_countAt'},\n { name: 'codeAt', call: 'eth_codeAt' },\n { name: 'transact', call: 'eth_transact' },\n { name: 'call', call: 'eth_call' },\n { name: 'block', call: blockCall },\n { name: 'transaction', call: transactionCall },\n { name: 'uncle', call: uncleCall },\n { name: 'compilers', call: 'eth_compilers' },\n { name: 'flush', call: 'eth_flush' },\n { name: 'lll', call: 'eth_lll' },\n { name: 'solidity', call: 'eth_solidity' },\n { name: 'serpent', call: 'eth_serpent' },\n { name: 'logs', call: 'eth_logs' },\n { name: 'transactionCount', call: transactionCountCall },\n { name: 'uncleCount', call: uncleCountCall }\n ];\n};\n\n/// @returns an array of objects describing web3.eth api properties\nvar properties = function () {\n return [\n { name: 'coinbase', getter: 'eth_coinbase', setter: 'eth_setCoinbase' },\n { name: 'listening', getter: 'eth_listening', setter: 'eth_setListening' },\n { name: 'mining', getter: 'eth_mining', setter: 'eth_setMining' },\n { name: 'gasPrice', getter: 'eth_gasPrice' },\n { name: 'accounts', getter: 'eth_accounts' },\n { name: 'peerCount', getter: 'eth_peerCount' },\n { name: 'defaultBlock', getter: 'eth_defaultBlock', setter: 'eth_setDefaultBlock' },\n { name: 'number', getter: 'eth_number'}\n ];\n};\n\nmodule.exports = {\n methods: methods,\n properties: properties\n};\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file event.js\n * @authors:\n * Marek Kotewicz \n * @date 2014\n */\n\nvar abi = require('./abi');\nvar utils = require('./utils');\nvar signature = require('./signature');\n\n/// filter inputs array && returns only indexed (or not) inputs\n/// @param inputs array\n/// @param bool if result should be an array of indexed params on not\n/// @returns array of (not?) indexed params\nvar filterInputs = function (inputs, indexed) {\n return inputs.filter(function (current) {\n return current.indexed === indexed;\n });\n};\n\nvar inputWithName = function (inputs, name) {\n var index = utils.findIndex(inputs, function (input) {\n return input.name === name;\n });\n \n if (index === -1) {\n console.error('indexed param with name ' + name + ' not found');\n return undefined;\n }\n return inputs[index];\n};\n\nvar indexedParamsToTopics = function (event, indexed) {\n // sort keys?\n return Object.keys(indexed).map(function (key) {\n var inputs = [inputWithName(filterInputs(event.inputs, true), key)];\n\n var value = indexed[key];\n if (value instanceof Array) {\n return value.map(function (v) {\n return abi.formatInput(inputs, [v]);\n }); \n }\n return abi.formatInput(inputs, [value]);\n });\n};\n\nvar inputParser = function (address, sign, event) {\n \n // valid options are 'earliest', 'latest', 'offset' and 'max', as defined for 'eth.watch'\n return function (indexed, options) {\n var o = options || {};\n o.address = address;\n o.topic = [];\n o.topic.push(sign);\n if (indexed) {\n o.topic = o.topic.concat(indexedParamsToTopics(event, indexed));\n }\n return o;\n };\n};\n\nvar getArgumentsObject = function (inputs, indexed, notIndexed) {\n var indexedCopy = indexed.slice();\n var notIndexedCopy = notIndexed.slice();\n return inputs.reduce(function (acc, current) {\n var value;\n if (current.indexed)\n value = indexedCopy.splice(0, 1)[0];\n else\n value = notIndexedCopy.splice(0, 1)[0];\n\n acc[current.name] = value;\n return acc;\n }, {}); \n};\n \nvar outputParser = function (event) {\n \n return function (output) {\n var result = {\n event: utils.extractDisplayName(event.name),\n number: output.number,\n hash: output.hash,\n args: {}\n };\n\n output.topics = output.topic; // fallback for go-ethereum\n if (!output.topic) {\n return result;\n }\n \n var indexedOutputs = filterInputs(event.inputs, true);\n var indexedData = \"0x\" + output.topic.slice(1, output.topic.length).map(function (topic) { return topic.slice(2); }).join(\"\");\n var indexedRes = abi.formatOutput(indexedOutputs, indexedData);\n\n var notIndexedOutputs = filterInputs(event.inputs, false);\n var notIndexedRes = abi.formatOutput(notIndexedOutputs, output.data);\n\n result.args = getArgumentsObject(event.inputs, indexedRes, notIndexedRes);\n\n return result;\n };\n};\n\nvar getMatchingEvent = function (events, payload) {\n for (var i = 0; i < events.length; i++) {\n var sign = signature.eventSignatureFromAscii(events[i].name); \n if (sign === payload.topic[0]) {\n return events[i];\n }\n }\n return undefined;\n};\n\n\nmodule.exports = {\n inputParser: inputParser,\n outputParser: outputParser,\n getMatchingEvent: getMatchingEvent\n};\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file filter.js\n * @authors:\n * Jeffrey Wilcke \n * Marek Kotewicz \n * Marian Oancea \n * Gav Wood \n * @date 2014\n */\n\n/// Should be called to check if filter implementation is valid\n/// @returns true if it is, otherwise false\nvar implementationIsValid = function (i) {\n return !!i && \n typeof i.newFilter === 'function' && \n typeof i.getMessages === 'function' && \n typeof i.uninstallFilter === 'function' &&\n typeof i.startPolling === 'function' &&\n typeof i.stopPolling === 'function';\n};\n\n/// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones\n/// @param should be string or object\n/// @returns options string or object\nvar getOptions = function (options) {\n if (typeof options === 'string') {\n return options;\n } \n\n options = options || {};\n\n if (options.topics) {\n console.warn('\"topics\" is deprecated, is \"topic\" instead');\n }\n\n // evaluate lazy properties\n return {\n to: options.to,\n topic: options.topic,\n earliest: options.earliest,\n latest: options.latest,\n max: options.max,\n skip: options.skip,\n address: options.address\n };\n};\n\n/// Should be used when we want to watch something\n/// it's using inner polling mechanism and is notified about changes\n/// @param options are filter options\n/// @param implementation, an abstract polling implementation\n/// @param formatter (optional), callback function which formats output before 'real' callback \nvar filter = function(options, implementation, formatter) {\n if (!implementationIsValid(implementation)) {\n console.error('filter implemenation is invalid');\n return;\n }\n\n options = getOptions(options);\n var callbacks = [];\n var filterId = implementation.newFilter(options);\n var onMessages = function (messages) {\n messages.forEach(function (message) {\n message = formatter ? formatter(message) : message;\n callbacks.forEach(function (callback) {\n callback(message);\n });\n });\n };\n\n implementation.startPolling(filterId, onMessages, implementation.uninstallFilter);\n\n var changed = function (callback) {\n callbacks.push(callback);\n };\n\n var messages = function () {\n return implementation.getMessages(filterId);\n };\n \n var uninstall = function () {\n implementation.stopPolling(filterId);\n implementation.uninstallFilter(filterId);\n callbacks = [];\n };\n\n return {\n changed: changed,\n arrived: changed,\n happened: changed,\n messages: messages,\n logs: messages,\n uninstall: uninstall\n };\n};\n\nmodule.exports = filter;\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file formatters.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\nif (\"build\" !== 'build') {/*\n var BigNumber = require('bignumber.js'); // jshint ignore:line\n*/}\n\nvar utils = require('./utils');\nvar c = require('./const');\n\n/// @param string string to be padded\n/// @param number of characters that result string should have\n/// @param sign, by default 0\n/// @returns right aligned string\nvar padLeft = function (string, chars, sign) {\n return new Array(chars - string.length + 1).join(sign ? sign : \"0\") + string;\n};\n\n/// Formats input value to byte representation of int\n/// If value is negative, return it's two's complement\n/// If the value is floating point, round it down\n/// @returns right-aligned byte representation of int\nvar formatInputInt = function (value) {\n /*jshint maxcomplexity:7 */\n var padding = c.ETH_PADDING * 2;\n if (value instanceof BigNumber || typeof value === 'number') {\n if (typeof value === 'number')\n value = new BigNumber(value);\n BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);\n value = value.round();\n\n if (value.lessThan(0)) \n value = new BigNumber(\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 16).plus(value).plus(1);\n value = value.toString(16);\n }\n else if (value.indexOf('0x') === 0)\n value = value.substr(2);\n else if (typeof value === 'string')\n value = formatInputInt(new BigNumber(value));\n else\n value = (+value).toString(16);\n return padLeft(value, padding);\n};\n\n/// Formats input value to byte representation of string\n/// @returns left-algined byte representation of string\nvar formatInputString = function (value) {\n return utils.fromAscii(value, c.ETH_PADDING).substr(2);\n};\n\n/// Formats input value to byte representation of bool\n/// @returns right-aligned byte representation bool\nvar formatInputBool = function (value) {\n return '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');\n};\n\n/// Formats input value to byte representation of real\n/// Values are multiplied by 2^m and encoded as integers\n/// @returns byte representation of real\nvar formatInputReal = function (value) {\n return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128))); \n};\n\n\n/// Check if input value is negative\n/// @param value is hex format\n/// @returns true if it is negative, otherwise false\nvar signedIsNegative = function (value) {\n return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1';\n};\n\n/// Formats input right-aligned input bytes to int\n/// @returns right-aligned input bytes formatted to int\nvar formatOutputInt = function (value) {\n value = value || \"0\";\n // check if it's negative number\n // it it is, return two's complement\n if (signedIsNegative(value)) {\n return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1);\n }\n return new BigNumber(value, 16);\n};\n\n/// Formats big right-aligned input bytes to uint\n/// @returns right-aligned input bytes formatted to uint\nvar formatOutputUInt = function (value) {\n value = value || \"0\";\n return new BigNumber(value, 16);\n};\n\n/// @returns input bytes formatted to real\nvar formatOutputReal = function (value) {\n return formatOutputInt(value).dividedBy(new BigNumber(2).pow(128)); \n};\n\n/// @returns input bytes formatted to ureal\nvar formatOutputUReal = function (value) {\n return formatOutputUInt(value).dividedBy(new BigNumber(2).pow(128)); \n};\n\n/// @returns right-aligned input bytes formatted to hex\nvar formatOutputHash = function (value) {\n return \"0x\" + value;\n};\n\n/// @returns right-aligned input bytes formatted to bool\nvar formatOutputBool = function (value) {\n return value === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;\n};\n\n/// @returns left-aligned input bytes formatted to ascii string\nvar formatOutputString = function (value) {\n return utils.toAscii(value);\n};\n\n/// @returns right-aligned input bytes formatted to address\nvar formatOutputAddress = function (value) {\n return \"0x\" + value.slice(value.length - 40, value.length);\n};\n\n\nmodule.exports = {\n formatInputInt: formatInputInt,\n formatInputString: formatInputString,\n formatInputBool: formatInputBool,\n formatInputReal: formatInputReal,\n formatOutputInt: formatOutputInt,\n formatOutputUInt: formatOutputUInt,\n formatOutputReal: formatOutputReal,\n formatOutputUReal: formatOutputUReal,\n formatOutputHash: formatOutputHash,\n formatOutputBool: formatOutputBool,\n formatOutputString: formatOutputString,\n formatOutputAddress: formatOutputAddress\n};\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file httpsync.js\n * @authors:\n * Marek Kotewicz \n * Marian Oancea \n * @date 2014\n */\n\nif (\"build\" !== 'build') {/*\n var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line\n*/}\n\nvar HttpSyncProvider = function (host) {\n this.handlers = [];\n this.host = host || 'http://127.0.0.1:8080';\n};\n\nHttpSyncProvider.prototype.send = function (payload) {\n //var data = formatJsonRpcObject(payload);\n\n var request = new XMLHttpRequest();\n request.open('POST', this.host, false);\n request.send(JSON.stringify(payload));\n\n var result = request.responseText;\n // check request.status\n if(request.status !== 200)\n return;\n return JSON.parse(result);\n};\n\nmodule.exports = HttpSyncProvider;\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file eth.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\n/**\n * Web3\n * \n * @module web3\n */\n\n/**\n * Eth methods and properties\n *\n * An example method object can look as follows:\n *\n * {\n * name: 'getBlock',\n * call: blockCall,\n * outputFormatter: formatters.outputBlockFormatter,\n * inputFormatter: [ // can be a formatter funciton or an array of functions. Where each item in the array will be used for one parameter\n * utils.toHex, // formats paramter 1\n * function(param){ if(!param) return false; } // formats paramter 2\n * ]\n * },\n *\n * @class [web3] eth\n * @constructor\n */\n\n\nvar formatters = require('./formatters');\nvar utils = require('../utils/utils');\n\n\nvar blockCall = function (args) {\n return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? \"eth_getBlockByHash\" : \"eth_getBlockByNumber\";\n};\n\nvar transactionFromBlockCall = function (args) {\n return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex';\n};\n\nvar uncleCall = function (args) {\n return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex';\n};\n\nvar getBlockTransactionCountCall = function (args) {\n return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber';\n};\n\nvar uncleCountCall = function (args) {\n return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber';\n};\n\n/// @returns an array of objects describing web3.eth api methods\nvar methods = [\n { name: 'getBalance', call: 'eth_getBalance', addDefaultblock: 2,\n outputFormatter: formatters.convertToBigNumber},\n { name: 'getStorage', call: 'eth_getStorage', addDefaultblock: 2},\n { name: 'getStorageAt', call: 'eth_getStorageAt', addDefaultblock: 3,\n inputFormatter: utils.toHex},\n { name: 'getData', call: 'eth_getData', addDefaultblock: 2},\n { name: 'getBlock', call: blockCall,\n outputFormatter: formatters.outputBlockFormatter,\n inputFormatter: [utils.toHex, function(param){ return (!param) ? false : true; }]},\n { name: 'getUncle', call: uncleCall,\n outputFormatter: formatters.outputBlockFormatter,\n inputFormatter: [utils.toHex, utils.toHex, function(param){ return (!param) ? false : true; }]},\n { name: 'getCompilers', call: 'eth_getCompilers' },\n { name: 'getBlockTransactionCount', call: getBlockTransactionCountCall,\n outputFormatter: utils.toDecimal,\n inputFormatter: utils.toHex },\n { name: 'getBlockUncleCount', call: uncleCountCall,\n outputFormatter: utils.toDecimal,\n inputFormatter: utils.toHex },\n { name: 'getTransaction', call: 'eth_getTransactionByHash',\n outputFormatter: formatters.outputTransactionFormatter },\n { name: 'getTransactionFromBlock', call: transactionFromBlockCall,\n outputFormatter: formatters.outputTransactionFormatter,\n inputFormatter: utils.toHex },\n { name: 'getTransactionCount', call: 'eth_getTransactionCount', addDefaultblock: 2,\n outputFormatter: utils.toDecimal},\n { name: 'sendTransaction', call: 'eth_sendTransaction',\n inputFormatter: formatters.inputTransactionFormatter },\n { name: 'call', call: 'eth_call', addDefaultblock: 2,\n inputFormatter: formatters.inputCallFormatter },\n { name: 'compile.solidity', call: 'eth_compileSolidity', inputFormatter: utils.toHex },\n { name: 'compile.lll', call: 'eth_compileLLL', inputFormatter: utils.toHex },\n { name: 'compile.serpent', call: 'eth_compileSerpent', inputFormatter: utils.toHex },\n { name: 'flush', call: 'eth_flush' },\n\n // deprecated methods\n { name: 'balanceAt', call: 'eth_balanceAt', newMethod: 'eth.getBalance' },\n { name: 'stateAt', call: 'eth_stateAt', newMethod: 'eth.getStorageAt' },\n { name: 'storageAt', call: 'eth_storageAt', newMethod: 'eth.getStorage' },\n { name: 'countAt', call: 'eth_countAt', newMethod: 'eth.getTransactionCount' },\n { name: 'codeAt', call: 'eth_codeAt', newMethod: 'eth.getData' },\n { name: 'transact', call: 'eth_transact', newMethod: 'eth.sendTransaction' },\n { name: 'block', call: blockCall, newMethod: 'eth.getBlock' },\n { name: 'transaction', call: transactionFromBlockCall, newMethod: 'eth.getTransaction' },\n { name: 'uncle', call: uncleCall, newMethod: 'eth.getUncle' },\n { name: 'compilers', call: 'eth_compilers', newMethod: 'eth.getCompilers' },\n { name: 'solidity', call: 'eth_solidity', newMethod: 'eth.compile.solidity' },\n { name: 'lll', call: 'eth_lll', newMethod: 'eth.compile.lll' },\n { name: 'serpent', call: 'eth_serpent', newMethod: 'eth.compile.serpent' },\n { name: 'transactionCount', call: getBlockTransactionCountCall, newMethod: 'eth.getBlockTransactionCount' },\n { name: 'uncleCount', call: uncleCountCall, newMethod: 'eth.getBlockUncleCount' },\n { name: 'logs', call: 'eth_logs' }\n];\n\n/// @returns an array of objects describing web3.eth api properties\nvar properties = [\n { name: 'coinbase', getter: 'eth_coinbase'},\n { name: 'mining', getter: 'eth_mining'},\n { name: 'gasPrice', getter: 'eth_gasPrice', outputFormatter: formatters.convertToBigNumber},\n { name: 'accounts', getter: 'eth_accounts' },\n { name: 'blockNumber', getter: 'eth_blockNumber', outputFormatter: utils.toDecimal},\n\n // deprecated properties\n { name: 'listening', getter: 'net_listening', setter: 'eth_setListening', newProperty: 'net.listening'},\n { name: 'peerCount', getter: 'net_peerCount', newProperty: 'net.peerCount'},\n { name: 'number', getter: 'eth_number', newProperty: 'eth.blockNumber'}\n];\n\n\nmodule.exports = {\n methods: methods,\n properties: properties\n};\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file event.js\n * @authors:\n * Marek Kotewicz \n * @date 2014\n */\n\nvar abi = require('../solidity/abi');\nvar utils = require('../utils/utils');\nvar signature = require('./signature');\n\n/// filter inputs array && returns only indexed (or not) inputs\n/// @param inputs array\n/// @param bool if result should be an array of indexed params on not\n/// @returns array of (not?) indexed params\nvar filterInputs = function (inputs, indexed) {\n return inputs.filter(function (current) {\n return current.indexed === indexed;\n });\n};\n\nvar inputWithName = function (inputs, name) {\n var index = utils.findIndex(inputs, function (input) {\n return input.name === name;\n });\n \n if (index === -1) {\n console.error('indexed param with name ' + name + ' not found');\n return undefined;\n }\n return inputs[index];\n};\n\nvar indexedParamsToTopics = function (event, indexed) {\n // sort keys?\n return Object.keys(indexed).map(function (key) {\n var inputs = [inputWithName(filterInputs(event.inputs, true), key)];\n\n var value = indexed[key];\n if (value instanceof Array) {\n return value.map(function (v) {\n return abi.formatInput(inputs, [v]);\n }); \n }\n return abi.formatInput(inputs, [value]);\n });\n};\n\nvar inputParser = function (address, sign, event) {\n \n // valid options are 'earliest', 'latest', 'offset' and 'max', as defined for 'eth.filter'\n return function (indexed, options) {\n var o = options || {};\n o.address = address;\n o.topics = [];\n o.topics.push(sign);\n if (indexed) {\n o.topics = o.topics.concat(indexedParamsToTopics(event, indexed));\n }\n return o;\n };\n};\n\nvar getArgumentsObject = function (inputs, indexed, notIndexed) {\n var indexedCopy = indexed.slice();\n var notIndexedCopy = notIndexed.slice();\n return inputs.reduce(function (acc, current) {\n var value;\n if (current.indexed)\n value = indexedCopy.splice(0, 1)[0];\n else\n value = notIndexedCopy.splice(0, 1)[0];\n\n acc[current.name] = value;\n return acc;\n }, {}); \n};\n \nvar outputParser = function (event) {\n \n return function (output) {\n var result = {\n event: utils.extractDisplayName(event.name),\n number: output.number,\n hash: output.hash,\n args: {}\n };\n\n output.topics = output.topic; // fallback for go-ethereum\n if (!output.topics) {\n return result;\n }\n \n var indexedOutputs = filterInputs(event.inputs, true);\n var indexedData = \"0x\" + output.topics.slice(1, output.topics.length).map(function (topics) { return topics.slice(2); }).join(\"\");\n var indexedRes = abi.formatOutput(indexedOutputs, indexedData);\n\n var notIndexedOutputs = filterInputs(event.inputs, false);\n var notIndexedRes = abi.formatOutput(notIndexedOutputs, output.data);\n\n result.args = getArgumentsObject(event.inputs, indexedRes, notIndexedRes);\n\n return result;\n };\n};\n\nvar getMatchingEvent = function (events, payload) {\n for (var i = 0; i < events.length; i++) {\n var sign = signature.eventSignatureFromAscii(events[i].name); \n if (sign === payload.topics[0]) {\n return events[i];\n }\n }\n return undefined;\n};\n\n\nmodule.exports = {\n inputParser: inputParser,\n outputParser: outputParser,\n getMatchingEvent: getMatchingEvent\n};\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file filter.js\n * @authors:\n * Jeffrey Wilcke \n * Marek Kotewicz \n * Marian Oancea \n * Gav Wood \n * @date 2014\n */\n\nvar utils = require('../utils/utils');\n\n/// Should be called to check if filter implementation is valid\n/// @returns true if it is, otherwise false\nvar implementationIsValid = function (i) {\n return !!i && \n typeof i.newFilter === 'function' && \n typeof i.getLogs === 'function' && \n typeof i.uninstallFilter === 'function' &&\n typeof i.startPolling === 'function' &&\n typeof i.stopPolling === 'function';\n};\n\n/// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones\n/// @param should be string or object\n/// @returns options string or object\nvar getOptions = function (options) {\n /*jshint maxcomplexity:9 */\n\n if (typeof options === 'string') {\n return options;\n } \n\n options = options || {};\n\n if (options.topic) {\n console.warn('\"topic\" is deprecated, is \"topics\" instead');\n options.topics = options.topic;\n }\n\n if (options.earliest) {\n console.warn('\"earliest\" is deprecated, is \"fromBlock\" instead');\n options.fromBlock = options.earliest;\n }\n\n if (options.latest) {\n console.warn('\"latest\" is deprecated, is \"toBlock\" instead');\n options.toBlock = options.latest;\n }\n\n if (options.skip) {\n console.warn('\"skip\" is deprecated, is \"offset\" instead');\n options.offset = options.skip;\n }\n\n if (options.max) {\n console.warn('\"max\" is deprecated, is \"limit\" instead');\n options.limit = options.max;\n }\n\n // make sure topics, get converted to hex\n if(options.topics instanceof Array) {\n options.topics = options.topics.map(function(topic){\n return utils.toHex(topic);\n });\n }\n\n\n // evaluate lazy properties\n return {\n fromBlock: utils.toHex(options.fromBlock),\n toBlock: utils.toHex(options.toBlock),\n limit: utils.toHex(options.limit),\n offset: utils.toHex(options.offset),\n to: options.to,\n address: options.address,\n topics: options.topics\n };\n};\n\n/// Should be used when we want to watch something\n/// it's using inner polling mechanism and is notified about changes\n/// @param options are filter options\n/// @param implementation, an abstract polling implementation\n/// @param formatter (optional), callback function which formats output before 'real' callback \nvar filter = function(options, implementation, formatter) {\n if (!implementationIsValid(implementation)) {\n console.error('filter implemenation is invalid');\n return;\n }\n\n options = getOptions(options);\n var callbacks = [];\n var filterId = implementation.newFilter(options);\n\n // call the callbacks\n var onMessages = function (messages) {\n messages.forEach(function (message) {\n message = formatter ? formatter(message) : message;\n callbacks.forEach(function (callback) {\n callback(message);\n });\n });\n };\n\n implementation.startPolling(filterId, onMessages, implementation.uninstallFilter);\n\n var watch = function(callback) {\n callbacks.push(callback);\n };\n\n var stopWatching = function() {\n implementation.stopPolling(filterId);\n implementation.uninstallFilter(filterId);\n callbacks = [];\n };\n\n var get = function () {\n var results = implementation.getLogs(filterId);\n\n return utils.isArray(results) ? results.map(function(message){\n return formatter ? formatter(message) : message;\n }) : results;\n };\n \n return {\n watch: watch,\n stopWatching: stopWatching,\n get: get,\n\n // DEPRECATED methods\n changed: function(){\n console.warn('watch().changed() is deprecated please use filter().watch() instead.');\n return watch.apply(this, arguments);\n },\n arrived: function(){\n console.warn('watch().arrived() is deprecated please use filter().watch() instead.');\n return watch.apply(this, arguments);\n },\n happened: function(){\n console.warn('watch().happened() is deprecated please use filter().watch() instead.');\n return watch.apply(this, arguments);\n },\n uninstall: function(){\n console.warn('watch().uninstall() is deprecated please use filter().stopWatching() instead.');\n return stopWatching.apply(this, arguments);\n },\n messages: function(){\n console.warn('watch().messages() is deprecated please use filter().get() instead.');\n return get.apply(this, arguments);\n },\n logs: function(){\n console.warn('watch().logs() is deprecated please use filter().get() instead.');\n return get.apply(this, arguments);\n }\n };\n};\n\nmodule.exports = filter;\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file formatters.js\n * @authors:\n * Marek Kotewicz \n * Fabian Vogelsteller \n * @date 2015\n */\n\nvar utils = require('../utils/utils');\n\n/**\n * Should the input to a big number\n *\n * @method convertToBigNumber\n * @param {String|Number|BigNumber}\n * @returns {BigNumber} object\n */\nvar convertToBigNumber = function (value) {\n return utils.toBigNumber(value);\n};\n\n/**\n * Formats the input of a transaction and converts all values to HEX\n *\n * @method inputTransactionFormatter\n * @param {Object} transaction options\n * @returns object\n*/\nvar inputTransactionFormatter = function (options){\n\n // make code -> data\n if (options.code) {\n options.data = options.code;\n delete options.code;\n }\n\n ['gasPrice', 'gas', 'value'].forEach(function(key){\n options[key] = utils.fromDecimal(options[key]);\n });\n\n return options;\n};\n\n/**\n * Formats the output of a transaction to its proper values\n * \n * @method outputTransactionFormatter\n * @param {Object} transaction\n * @returns {Object} transaction\n*/\nvar outputTransactionFormatter = function (tx){\n tx.gas = utils.toDecimal(tx.gas);\n tx.gasPrice = utils.toBigNumber(tx.gasPrice);\n tx.value = utils.toBigNumber(tx.value);\n return tx;\n};\n\n/**\n * Formats the input of a call and converts all values to HEX\n *\n * @method inputCallFormatter\n * @param {Object} transaction options\n * @returns object\n*/\nvar inputCallFormatter = function (options){\n\n // make code -> data\n if (options.code) {\n options.data = options.code;\n delete options.code;\n }\n\n return options;\n};\n\n\n/**\n * Formats the output of a block to its proper values\n *\n * @method outputBlockFormatter\n * @param {Object} block object \n * @returns {Object} block object\n*/\nvar outputBlockFormatter = function(block){\n\n // transform to number\n block.gasLimit = utils.toDecimal(block.gasLimit);\n block.gasUsed = utils.toDecimal(block.gasUsed);\n block.size = utils.toDecimal(block.size);\n block.timestamp = utils.toDecimal(block.timestamp);\n block.number = utils.toDecimal(block.number);\n\n block.minGasPrice = utils.toBigNumber(block.minGasPrice);\n block.difficulty = utils.toBigNumber(block.difficulty);\n block.totalDifficulty = utils.toBigNumber(block.totalDifficulty);\n\n if(block.transactions instanceof Array) {\n block.transactions.forEach(function(item){\n if(!utils.isString(item))\n return outputTransactionFormatter(item);\n });\n }\n\n return block;\n};\n\n/**\n * Formats the output of a log\n * \n * @method outputLogFormatter\n * @param {Object} log object\n * @returns {Object} log\n*/\nvar outputLogFormatter = function(log){\n log.blockNumber = utils.toDecimal(log.blockNumber);\n log.transactionIndex = utils.toDecimal(log.transactionIndex);\n log.logIndex = utils.toDecimal(log.logIndex);\n\n return log;\n};\n\n\n/**\n * Formats the input of a whisper post and converts all values to HEX\n *\n * @method inputPostFormatter\n * @param {Object} transaction object\n * @returns {Object}\n*/\nvar inputPostFormatter = function(post){\n\n post.payload = utils.toHex(post.payload);\n post.ttl = utils.fromDecimal(post.ttl);\n post.priority = utils.fromDecimal(post.priority);\n\n if(!(post.topics instanceof Array))\n post.topics = [post.topics];\n\n\n // format the following options\n post.topics = post.topics.map(function(topic){\n return utils.fromAscii(topic);\n });\n\n return post;\n};\n\n/**\n * Formats the output of a received post message\n *\n * @method outputPostFormatter\n * @param {Object}\n * @returns {Object}\n */\nvar outputPostFormatter = function(post){\n\n post.expiry = utils.toDecimal(post.expiry);\n post.sent = utils.toDecimal(post.sent);\n post.ttl = utils.toDecimal(post.ttl);\n post.workProved = utils.toDecimal(post.workProved);\n post.payloadRaw = post.payload;\n post.payload = utils.toAscii(post.payload);\n\n if(post.payload.indexOf('{') === 0 || post.payload.indexOf('[') === 0) {\n try {\n post.payload = JSON.parse(post.payload);\n } catch (e) { }\n }\n\n // format the following options\n post.topics = post.topics.map(function(topic){\n return utils.toAscii(topic);\n });\n\n return post;\n};\n\nmodule.exports = {\n convertToBigNumber: convertToBigNumber,\n inputTransactionFormatter: inputTransactionFormatter,\n outputTransactionFormatter: outputTransactionFormatter,\n inputCallFormatter: inputCallFormatter,\n outputBlockFormatter: outputBlockFormatter,\n outputLogFormatter: outputLogFormatter,\n inputPostFormatter: inputPostFormatter,\n outputPostFormatter: outputPostFormatter\n};\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file httpprovider.js\n * @authors:\n * Marek Kotewicz \n * Marian Oancea \n * @date 2014\n */\n\nif (\"build\" !== 'build') {/*\n var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line\n*/}\n\nvar HttpProvider = function (host) {\n this.name = 'HTTP';\n this.handlers = [];\n this.host = host || 'http://localhost:8080';\n};\n\nHttpProvider.prototype.send = function (payload, callback) {\n var request = new XMLHttpRequest();\n request.open('POST', this.host, false);\n\n // ASYNC\n if(typeof callback === 'function') {\n request.onreadystatechange = function() {\n if(request.readyState === 4) {\n var result = '';\n try {\n result = JSON.parse(request.responseText);\n } catch(error) {\n result = error;\n }\n callback(result, request.status);\n }\n };\n\n request.open('POST', this.host, true);\n request.send(JSON.stringify(payload));\n\n // SYNC\n } else {\n request.open('POST', this.host, false);\n request.send(JSON.stringify(payload));\n\n // check request.status\n if(request.status !== 200)\n return;\n return JSON.parse(request.responseText);\n \n }\n};\n\nmodule.exports = HttpProvider;\n\n", "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file jsonrpc.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\nvar messageId = 1;\n\n/// Should be called to valid json create payload object\n/// @param method of jsonrpc call, required\n/// @param params, an array of method params, optional\n/// @returns valid jsonrpc payload object\nvar toPayload = function (method, params) {\n if (!method)\n console.error('jsonrpc method should be specified!');\n\n return {\n jsonrpc: '2.0',\n method: method,\n params: params || [],\n id: messageId++\n }; \n};\n\n/// Should be called to check if jsonrpc response is valid\n/// @returns true if response is valid, otherwise false \nvar isValidResponse = function (response) {\n return !!response &&\n !response.error &&\n response.jsonrpc === '2.0' &&\n typeof response.id === 'number' &&\n response.result !== undefined; // only undefined is not valid json object\n};\n\n/// Should be called to create batch payload object\n/// @param messages, an array of objects with method (required) and params (optional) fields\nvar toBatchPayload = function (messages) {\n return messages.map(function (message) {\n return toPayload(message.method, message.params);\n }); \n};\n\nmodule.exports = {\n toPayload: toPayload,\n isValidResponse: isValidResponse,\n toBatchPayload: toBatchPayload\n};\n\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file eth.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\nvar utils = require('../utils/utils');\n\n/// @returns an array of objects describing web3.eth api methods\nvar methods = [\n // { name: 'getBalance', call: 'eth_balanceAt', outputFormatter: formatters.convertToBigNumber},\n];\n\n/// @returns an array of objects describing web3.eth api properties\nvar properties = [\n { name: 'listening', getter: 'net_listening'},\n { name: 'peerCount', getter: 'net_peerCount', outputFormatter: utils.toDecimal },\n];\n\n\nmodule.exports = {\n methods: methods,\n properties: properties\n};\n\n", "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file qtsync.js\n * @authors:\n * Marek Kotewicz \n * Marian Oancea \n * @date 2014\n */\n\nvar QtSyncProvider = function () {\n};\n\nQtSyncProvider.prototype.send = function (payload) {\n var result = navigator.qt.callMethod(JSON.stringify(payload));\n return JSON.parse(result);\n};\n\nmodule.exports = QtSyncProvider;\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file requestmanager.js\n * @authors:\n * Jeffrey Wilcke \n * Marek Kotewicz \n * Marian Oancea \n * Gav Wood \n * @date 2014\n */\n\nvar jsonrpc = require('./jsonrpc');\nvar c = require('./const');\n\n/**\n * It's responsible for passing messages to providers\n * It's also responsible for polling the ethereum node for incoming messages\n * Default poll timeout is 1 second\n */\nvar requestManager = function() {\n var polls = [];\n var timeout = null;\n var provider;\n\n var send = function (data) {\n var payload = jsonrpc.toPayload(data.method, data.params);\n \n if (!provider) {\n console.error('provider is not set');\n return null;\n }\n\n var result = provider.send(payload);\n\n if (!jsonrpc.isValidResponse(result)) {\n console.log(result);\n return null;\n }\n \n return result.result;\n };\n\n var setProvider = function (p) {\n provider = p;\n };\n\n /*jshint maxparams:4 */\n var startPolling = function (data, pollId, callback, uninstall) {\n polls.push({data: data, id: pollId, callback: callback, uninstall: uninstall});\n };\n /*jshint maxparams:3 */\n\n var stopPolling = function (pollId) {\n for (var i = polls.length; i--;) {\n var poll = polls[i];\n if (poll.id === pollId) {\n polls.splice(i, 1);\n }\n }\n };\n\n var reset = function () {\n polls.forEach(function (poll) {\n poll.uninstall(poll.id); \n });\n polls = [];\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n poll();\n };\n\n var poll = function () {\n polls.forEach(function (data) {\n var result = send(data.data);\n if (!(result instanceof Array) || result.length === 0) {\n return;\n }\n data.callback(result);\n });\n timeout = setTimeout(poll, c.ETH_POLLING_TIMEOUT);\n };\n \n poll();\n\n return {\n send: send,\n setProvider: setProvider,\n startPolling: startPolling,\n stopPolling: stopPolling,\n reset: reset\n };\n};\n\nmodule.exports = requestManager;\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file shh.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\n/// @returns an array of objects describing web3.shh api methods\nvar methods = function () {\n return [\n { name: 'post', call: 'shh_post' },\n { name: 'newIdentity', call: 'shh_newIdentity' },\n { name: 'haveIdentity', call: 'shh_haveIdentity' },\n { name: 'newGroup', call: 'shh_newGroup' },\n { name: 'addToGroup', call: 'shh_addToGroup' }\n ];\n};\n\nmodule.exports = {\n methods: methods\n};\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file signature.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\nvar web3 = require('./web3'); \nvar c = require('./const');\n\n/// @param function name for which we want to get signature\n/// @returns signature of function with given name\nvar functionSignatureFromAscii = function (name) {\n return web3.sha3(web3.fromAscii(name)).slice(0, 2 + c.ETH_SIGNATURE_LENGTH * 2);\n};\n\n/// @param event name for which we want to get signature\n/// @returns signature of event with given name\nvar eventSignatureFromAscii = function (name) {\n return web3.sha3(web3.fromAscii(name));\n};\n\nmodule.exports = {\n functionSignatureFromAscii: functionSignatureFromAscii,\n eventSignatureFromAscii: eventSignatureFromAscii\n};\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file types.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\nvar f = require('./formatters');\n\n/// @param expected type prefix (string)\n/// @returns function which checks if type has matching prefix. if yes, returns true, otherwise false\nvar prefixedType = function (prefix) {\n return function (type) {\n return type.indexOf(prefix) === 0;\n };\n};\n\n/// @param expected type name (string)\n/// @returns function which checks if type is matching expected one. if yes, returns true, otherwise false\nvar namedType = function (name) {\n return function (type) {\n return name === type;\n };\n};\n\n/// Setups input formatters for solidity types\n/// @returns an array of input formatters \nvar inputTypes = function () {\n \n return [\n { type: prefixedType('uint'), format: f.formatInputInt },\n { type: prefixedType('int'), format: f.formatInputInt },\n { type: prefixedType('hash'), format: f.formatInputInt },\n { type: prefixedType('string'), format: f.formatInputString }, \n { type: prefixedType('real'), format: f.formatInputReal },\n { type: prefixedType('ureal'), format: f.formatInputReal },\n { type: namedType('address'), format: f.formatInputInt },\n { type: namedType('bool'), format: f.formatInputBool }\n ];\n};\n\n/// Setups output formaters for solidity types\n/// @returns an array of output formatters\nvar outputTypes = function () {\n\n return [\n { type: prefixedType('uint'), format: f.formatOutputUInt },\n { type: prefixedType('int'), format: f.formatOutputInt },\n { type: prefixedType('hash'), format: f.formatOutputHash },\n { type: prefixedType('string'), format: f.formatOutputString },\n { type: prefixedType('real'), format: f.formatOutputReal },\n { type: prefixedType('ureal'), format: f.formatOutputUReal },\n { type: namedType('address'), format: f.formatOutputAddress },\n { type: namedType('bool'), format: f.formatOutputBool }\n ];\n};\n\nmodule.exports = {\n prefixedType: prefixedType,\n namedType: namedType,\n inputTypes: inputTypes,\n outputTypes: outputTypes\n};\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file utils.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\nvar c = require('./const');\n\n/// Finds first index of array element matching pattern\n/// @param array\n/// @param callback pattern\n/// @returns index of element\nvar findIndex = function (array, callback) {\n var end = false;\n var i = 0;\n for (; i < array.length && !end; i++) {\n end = callback(array[i]);\n }\n return end ? i - 1 : -1;\n};\n\n/// @returns ascii string representation of hex value prefixed with 0x\nvar toAscii = function(hex) {\n// Find termination\n var str = \"\";\n var i = 0, l = hex.length;\n if (hex.substring(0, 2) === '0x') {\n i = 2;\n }\n for (; i < l; i+=2) {\n var code = parseInt(hex.substr(i, 2), 16);\n if (code === 0) {\n break;\n }\n\n str += String.fromCharCode(code);\n }\n\n return str;\n};\n \nvar toHex = function(str) {\n var hex = \"\";\n for(var i = 0; i < str.length; i++) {\n var n = str.charCodeAt(i).toString(16);\n hex += n.length < 2 ? '0' + n : n;\n }\n\n return hex;\n};\n\n/// @returns hex representation (prefixed by 0x) of ascii string\nvar fromAscii = function(str, pad) {\n pad = pad === undefined ? 0 : pad;\n var hex = toHex(str);\n while (hex.length < pad*2)\n hex += \"00\";\n return \"0x\" + hex;\n};\n\n/// @returns display name for function/event eg. multiply(uint256) -> multiply\nvar extractDisplayName = function (name) {\n var length = name.indexOf('('); \n return length !== -1 ? name.substr(0, length) : name;\n};\n\n/// @returns overloaded part of function/event name\nvar extractTypeName = function (name) {\n /// TODO: make it invulnerable\n var length = name.indexOf('(');\n return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : \"\";\n};\n\n/// Filters all function from input abi\n/// @returns abi array with filtered objects of type 'function'\nvar filterFunctions = function (json) {\n return json.filter(function (current) {\n return current.type === 'function'; \n }); \n};\n\n/// Filters all events form input abi\n/// @returns abi array with filtered objects of type 'event'\nvar filterEvents = function (json) {\n return json.filter(function (current) {\n return current.type === 'event';\n });\n};\n\n/// used to transform value/string to eth string\n/// TODO: use BigNumber.js to parse int\n/// TODO: add tests for it!\nvar toEth = function (str) {\n /*jshint maxcomplexity:7 */\n var val = typeof str === \"string\" ? str.indexOf('0x') === 0 ? parseInt(str.substr(2), 16) : parseInt(str) : str;\n var unit = 0;\n var units = c.ETH_UNITS;\n while (val > 3000 && unit < units.length - 1)\n {\n val /= 1000;\n unit++;\n }\n var s = val.toString().length < val.toFixed(2).length ? val.toString() : val.toFixed(2);\n var replaceFunction = function($0, $1, $2) {\n return $1 + ',' + $2;\n };\n\n while (true) {\n var o = s;\n s = s.replace(/(\\d)(\\d\\d\\d[\\.\\,])/, replaceFunction);\n if (o === s)\n break;\n }\n return s + ' ' + units[unit];\n};\n\nmodule.exports = {\n findIndex: findIndex,\n toAscii: toAscii,\n fromAscii: fromAscii,\n extractDisplayName: extractDisplayName,\n extractTypeName: extractTypeName,\n filterFunctions: filterFunctions,\n filterEvents: filterEvents,\n toEth: toEth\n};\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file watches.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\n/// @returns an array of objects describing web3.eth.watch api methods\nvar eth = function () {\n var newFilter = function (args) {\n return typeof args[0] === 'string' ? 'eth_newFilterString' : 'eth_newFilter';\n };\n\n return [\n { name: 'newFilter', call: newFilter },\n { name: 'uninstallFilter', call: 'eth_uninstallFilter' },\n { name: 'getMessages', call: 'eth_filterLogs' }\n ];\n};\n\n/// @returns an array of objects describing web3.shh.watch api methods\nvar shh = function () {\n return [\n { name: 'newFilter', call: 'shh_newFilter' },\n { name: 'uninstallFilter', call: 'shh_uninstallFilter' },\n { name: 'getMessages', call: 'shh_getMessages' }\n ];\n};\n\nmodule.exports = {\n eth: eth,\n shh: shh\n};\n\n", - "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file web3.js\n * @authors:\n * Jeffrey Wilcke \n * Marek Kotewicz \n * Marian Oancea \n * Gav Wood \n * @date 2014\n */\n\nif (\"build\" !== 'build') {/*\n var BigNumber = require('bignumber.js');\n*/}\n\nvar eth = require('./eth');\nvar db = require('./db');\nvar shh = require('./shh');\nvar watches = require('./watches');\nvar filter = require('./filter');\nvar utils = require('./utils');\nvar requestManager = require('./requestmanager');\n\n/// @returns an array of objects describing web3 api methods\nvar web3Methods = function () {\n return [\n { name: 'sha3', call: 'web3_sha3' }\n ];\n};\n\n/// creates methods in a given object based on method description on input\n/// setups api calls for these methods\nvar setupMethods = function (obj, methods) {\n methods.forEach(function (method) {\n obj[method.name] = function () {\n var args = Array.prototype.slice.call(arguments);\n var call = typeof method.call === 'function' ? method.call(args) : method.call;\n return web3.manager.send({\n method: call,\n params: args\n });\n };\n });\n};\n\n/// creates properties in a given object based on properties description on input\n/// setups api calls for these properties\nvar setupProperties = function (obj, properties) {\n properties.forEach(function (property) {\n var proto = {};\n proto.get = function () {\n return web3.manager.send({\n method: property.getter\n });\n };\n\n if (property.setter) {\n proto.set = function (val) {\n return web3.manager.send({\n method: property.setter,\n params: [val]\n });\n };\n }\n Object.defineProperty(obj, property.name, proto);\n });\n};\n\n/*jshint maxparams:4 */\nvar startPolling = function (method, id, callback, uninstall) {\n web3.manager.startPolling({\n method: method, \n params: [id]\n }, id, callback, uninstall); \n};\n/*jshint maxparams:3 */\n\nvar stopPolling = function (id) {\n web3.manager.stopPolling(id);\n};\n\nvar ethWatch = {\n startPolling: startPolling.bind(null, 'eth_changed'), \n stopPolling: stopPolling\n};\n\nvar shhWatch = {\n startPolling: startPolling.bind(null, 'shh_changed'), \n stopPolling: stopPolling\n};\n\n/// setups web3 object, and it's in-browser executed methods\nvar web3 = {\n manager: requestManager(),\n providers: {},\n\n /// @returns ascii string representation of hex value prefixed with 0x\n toAscii: utils.toAscii,\n\n /// @returns hex representation (prefixed by 0x) of ascii string\n fromAscii: utils.fromAscii,\n\n /// @returns decimal representaton of hex value prefixed by 0x\n toDecimal: function (val) {\n // remove 0x and place 0, if it's required\n val = val.length > 2 ? val.substring(2) : \"0\";\n return (new BigNumber(val, 16).toString(10));\n },\n\n /// @returns hex representation (prefixed by 0x) of decimal value\n fromDecimal: function (val) {\n return \"0x\" + (new BigNumber(val).toString(16));\n },\n\n /// used to transform value/string to eth string\n toEth: utils.toEth,\n\n /// eth object prototype\n eth: {\n contractFromAbi: function (abi) {\n return function(addr) {\n // Default to address of Config. TODO: rremove prior to genesis.\n addr = addr || '0xc6d9d2cd449a754c494264e1809c50e34d64562b';\n var ret = web3.eth.contract(addr, abi);\n ret.address = addr;\n return ret;\n };\n },\n\n canary: function (abi) {\n return function(addr) {\n // Default to address of Config. TODO: rremove prior to genesis.\n addr = addr || '0xc6d9d2cd449a754c494264e1809c50e34d64562b';\n return addr;\n };\n },\n\n /// @param filter may be a string, object or event\n /// @param indexed is optional, this is an object with optional event indexed params\n /// @param options is optional, this is an object with optional event options ('max'...)\n /// TODO: fix it, 4 params? no way\n /*jshint maxparams:4 */\n watch: function (fil, indexed, options, formatter) {\n if (fil._isEvent) {\n return fil(indexed, options);\n }\n return filter(fil, ethWatch, formatter);\n }\n /*jshint maxparams:3 */\n },\n\n /// db object prototype\n db: {},\n\n /// shh object prototype\n shh: {\n /// @param filter may be a string, object or event\n watch: function (fil) {\n return filter(fil, shhWatch);\n }\n },\n setProvider: function (provider) {\n web3.manager.setProvider(provider);\n },\n \n /// Should be called to reset state of web3 object\n /// Resets everything except manager\n reset: function () {\n web3.manager.reset(); \n }\n};\n\n/// setups all api methods\nsetupMethods(web3, web3Methods());\nsetupMethods(web3.eth, eth.methods());\nsetupProperties(web3.eth, eth.properties());\nsetupMethods(web3.db, db.methods());\nsetupMethods(web3.shh, shh.methods());\nsetupMethods(ethWatch, watches.eth());\nsetupMethods(shhWatch, watches.shh());\n\nmodule.exports = web3;\n\n", - "var web3 = require('./lib/web3');\nweb3.providers.HttpSyncProvider = require('./lib/httpsync');\nweb3.providers.QtSyncProvider = require('./lib/qtsync');\nweb3.eth.contract = require('./lib/contract');\nweb3.abi = require('./lib/abi');\n\nmodule.exports = web3;\n" + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file requestmanager.js\n * @authors:\n * Jeffrey Wilcke \n * Marek Kotewicz \n * Marian Oancea \n * Gav Wood \n * @date 2014\n */\n\nvar jsonrpc = require('./jsonrpc');\nvar c = require('../utils/config');\n\n/**\n * It's responsible for passing messages to providers\n * It's also responsible for polling the ethereum node for incoming messages\n * Default poll timeout is 1 second\n */\nvar requestManager = function() {\n var polls = [];\n var timeout = null;\n var provider;\n\n var send = function (data, callback) {\n /*jshint maxcomplexity: 8 */\n\n // FORMAT BASED ON ONE FORMATTER function\n if(typeof data.inputFormatter === 'function') {\n data.params = Array.prototype.map.call(data.params, function(item, index){\n // format everything besides the defaultblock, which is already formated\n return (!data.addDefaultblock || index+1 < data.addDefaultblock) ? data.inputFormatter(item) : item;\n });\n\n // FORMAT BASED ON the input FORMATTER ARRAY\n } else if(data.inputFormatter instanceof Array) {\n data.params = Array.prototype.map.call(data.inputFormatter, function(formatter, index){\n // format everything besides the defaultblock, which is already formated\n return (!data.addDefaultblock || index+1 < data.addDefaultblock) ? formatter(data.params[index]) : data.params[index];\n });\n }\n\n\n var payload = jsonrpc.toPayload(data.method, data.params);\n \n if (!provider) {\n console.error('provider is not set');\n return null;\n }\n\n // HTTP ASYNC (only when callback is given, and it a HttpProvidor)\n if(typeof callback === 'function' && provider.name === 'HTTP'){\n provider.send(payload, function(result, status){\n\n if (!jsonrpc.isValidResponse(result)) {\n if(typeof result === 'object' && result.error && result.error.message) {\n console.error(result.error.message);\n callback(result.error);\n } else {\n callback(new Error({\n status: status,\n error: result,\n message: 'Bad Request'\n }));\n }\n return null;\n }\n\n // format the output\n callback(null, (typeof data.outputFormatter === 'function') ? data.outputFormatter(result.result) : result.result);\n });\n\n // SYNC\n } else {\n var result = provider.send(payload);\n\n if (!jsonrpc.isValidResponse(result)) {\n console.log(result);\n if(typeof result === 'object' && result.error && result.error.message)\n console.error(result.error.message);\n return null;\n }\n\n // format the output\n return (typeof data.outputFormatter === 'function') ? data.outputFormatter(result.result) : result.result;\n }\n \n };\n\n var setProvider = function (p) {\n provider = p;\n };\n\n /*jshint maxparams:4 */\n var startPolling = function (data, pollId, callback, uninstall) {\n polls.push({data: data, id: pollId, callback: callback, uninstall: uninstall});\n };\n /*jshint maxparams:3 */\n\n var stopPolling = function (pollId) {\n for (var i = polls.length; i--;) {\n var poll = polls[i];\n if (poll.id === pollId) {\n polls.splice(i, 1);\n }\n }\n };\n\n var reset = function () {\n polls.forEach(function (poll) {\n poll.uninstall(poll.id); \n });\n polls = [];\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n poll();\n };\n\n var poll = function () {\n polls.forEach(function (data) {\n // send async\n send(data.data, function(error, result){\n if (!(result instanceof Array) || result.length === 0) {\n return;\n }\n data.callback(result);\n });\n });\n timeout = setTimeout(poll, c.ETH_POLLING_TIMEOUT);\n };\n \n poll();\n\n return {\n send: send,\n setProvider: setProvider,\n startPolling: startPolling,\n stopPolling: stopPolling,\n reset: reset\n };\n};\n\nmodule.exports = requestManager;\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file shh.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\nvar formatters = require('./formatters');\n\n/// @returns an array of objects describing web3.shh api methods\nvar methods = function () {\n return [\n { name: 'post', call: 'shh_post', inputFormatter: formatters.inputPostFormatter },\n { name: 'newIdentity', call: 'shh_newIdentity' },\n { name: 'hasIdentity', call: 'shh_hasIdentity' },\n { name: 'newGroup', call: 'shh_newGroup' },\n { name: 'addToGroup', call: 'shh_addToGroup' },\n\n // deprecated\n { name: 'haveIdentity', call: 'shh_haveIdentity', newMethod: 'shh.hasIdentity' },\n ];\n};\n\nmodule.exports = {\n methods: methods\n};\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file signature.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\nvar web3 = require('../web3'); \nvar c = require('../utils/config');\n\n/// @param function name for which we want to get signature\n/// @returns signature of function with given name\nvar functionSignatureFromAscii = function (name) {\n return web3.sha3(web3.fromAscii(name)).slice(0, 2 + c.ETH_SIGNATURE_LENGTH * 2);\n};\n\n/// @param event name for which we want to get signature\n/// @returns signature of event with given name\nvar eventSignatureFromAscii = function (name) {\n return web3.sha3(web3.fromAscii(name));\n};\n\nmodule.exports = {\n functionSignatureFromAscii: functionSignatureFromAscii,\n eventSignatureFromAscii: eventSignatureFromAscii\n};\n\n", + "/*\n This file is part of ethereum.js.\n\n ethereum.js is free software: you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n ethereum.js is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with ethereum.js. If not, see .\n*/\n/** @file watches.js\n * @authors:\n * Marek Kotewicz \n * @date 2015\n */\n\n/// @returns an array of objects describing web3.eth.filter api methods\nvar eth = function () {\n var newFilter = function (args) {\n return typeof args[0] === 'string' ? 'eth_newBlockFilter' : 'eth_newFilter';\n };\n\n return [\n { name: 'newFilter', call: newFilter },\n { name: 'uninstallFilter', call: 'eth_uninstallFilter' },\n { name: 'getLogs', call: 'eth_getFilterLogs' }\n ];\n};\n\n/// @returns an array of objects describing web3.shh.watch api methods\nvar shh = function () {\n return [\n { name: 'newFilter', call: 'shh_newFilter' },\n { name: 'uninstallFilter', call: 'shh_uninstallFilter' },\n { name: 'getLogs', call: 'shh_getMessages' }\n ];\n};\n\nmodule.exports = {\n eth: eth,\n shh: shh\n};\n\n", + "var web3 = require('./lib/web3');\nweb3.providers.HttpProvider = require('./lib/web3/httpprovider');\nweb3.providers.QtSyncProvider = require('./lib/web3/qtsync');\nweb3.eth.contract = require('./lib/web3/contract');\nweb3.abi = require('./lib/solidity/abi');\n\nmodule.exports = web3;\n" ] } \ No newline at end of file diff --git a/libjsqrc/ethereumjs/dist/ethereum.min.js b/libjsqrc/ethereumjs/dist/ethereum.min.js index e65ae4f09..fc5a3691a 100644 --- a/libjsqrc/ethereumjs/dist/ethereum.min.js +++ b/libjsqrc/ethereumjs/dist/ethereum.min.js @@ -1 +1 @@ -require=function t(n,e,r){function o(i,u){if(!e[i]){if(!n[i]){var f="function"==typeof require&&require;if(!u&&f)return f(i,!0);if(a)return a(i,!0);var s=new Error("Cannot find module '"+i+"'");throw s.code="MODULE_NOT_FOUND",s}var c=e[i]={exports:{}};n[i][0].call(c.exports,function(t){var e=n[i][1][t];return o(e?e:t)},c,c.exports,t,n,e,r)}return e[i].exports}for(var a="function"==typeof require&&require,i=0;iv;v++)g.push(h(n.slice(0,f))),n=n.slice(f);e.push(g)}else r.prefixedType("string")(t[s].type)?(c=c.slice(f),e.push(h(n.slice(0,f))),n=n.slice(f)):(e.push(h(n.slice(0,f))),n=n.slice(f))}),e},h=function(t){var n={};return t.forEach(function(t){var r=e.extractDisplayName(t.name),o=e.extractTypeName(t.name),a=function(){var n=Array.prototype.slice.call(arguments);return c(t.inputs,n)};void 0===n[r]&&(n[r]=a),n[r][o]=a}),n},d=function(t){var n={};return t.forEach(function(t){var r=e.extractDisplayName(t.name),o=e.extractTypeName(t.name),a=function(n){return m(t.outputs,n)};void 0===n[r]&&(n[r]=a),n[r][o]=a}),n};n.exports={inputParser:h,outputParser:d,formatInput:c,formatOutput:m}},{"./const":2,"./formatters":8,"./types":15,"./utils":16}],2:[function(t,n){var e=["wei","Kwei","Mwei","Gwei","szabo","finney","ether","grand","Mether","Gether","Tether","Pether","Eether","Zether","Yether","Nether","Dether","Vether","Uether"];n.exports={ETH_PADDING:32,ETH_SIGNATURE_LENGTH:4,ETH_UNITS:e,ETH_BIGNUMBER_ROUNDING_MODE:{ROUNDING_MODE:BigNumber.ROUND_DOWN},ETH_POLLING_TIMEOUT:1e3}},{}],3:[function(t,n){var e=t("./web3"),r=t("./abi"),o=t("./utils"),a=t("./event"),i=t("./signature"),u=function(t){e._currentContractAbi=t.abi,e._currentContractAddress=t.address,e._currentContractMethodName=t.method,e._currentContractMethodParams=t.params},f=function(t){t.call=function(n){return t._isTransact=!1,t._options=n,t},t.transact=function(n){return t._isTransact=!0,t._options=n,t},t._options={},["gas","gasPrice","value","from"].forEach(function(n){t[n]=function(e){return t._options[n]=e,t}})},s=function(t,n,a){var f=r.inputParser(n),s=r.outputParser(n);o.filterFunctions(n).forEach(function(r){var c=o.extractDisplayName(r.name),l=o.extractTypeName(r.name),p=function(){var o=Array.prototype.slice.call(arguments),p=i.functionSignatureFromAscii(r.name),m=f[c][l].apply(null,o),h=t._options||{};h.to=a,h.data=p+m;var d=t._isTransact===!0||t._isTransact!==!1&&!r.constant,g=h.collapse!==!1;if(t._options={},t._isTransact=null,d)return u({abi:n,address:a,method:r.name,params:o}),void e.eth.transact(h);var v=e.eth.call(h),y=s[c][l](v);return g&&(1===y.length?y=y[0]:0===y.length&&(y=null)),y};void 0===t[c]&&(t[c]=p),t[c][l]=p})},c=function(t,n,e){t.address=e,t._onWatchEventResult=function(t){var e=event.getMatchingEvent(o.filterEvents(n)),r=a.outputParser(e);return r(t)},Object.defineProperty(t,"topic",{get:function(){return o.filterEvents(n).map(function(t){return i.eventSignatureFromAscii(t.name)})}})},l=function(t,n,r){o.filterEvents(n).forEach(function(n){var u=function(){var t=Array.prototype.slice.call(arguments),o=i.eventSignatureFromAscii(n.name),u=a.inputParser(r,o,n),f=u.apply(null,t),s=function(t){var e=a.outputParser(n);return e(t)};return e.eth.watch(f,void 0,void 0,s)};u._isEvent=!0;var f=o.extractDisplayName(n.name),s=o.extractTypeName(n.name);void 0===t[f]&&(t[f]=u),t[f][s]=u})},p=function(t,n){n.forEach(function(t){if(-1===t.name.indexOf("(")){var n=t.name,e=t.inputs.map(function(t){return t.type}).join();t.name=n+"("+e+")"}});var e={};return f(e),s(e,n,t),c(e,n,t),l(e,n,t),e};n.exports=p},{"./abi":1,"./event":6,"./signature":14,"./utils":16,"./web3":18}],4:[function(t,n){var e=function(){return[{name:"put",call:"db_put"},{name:"get",call:"db_get"},{name:"putString",call:"db_putString"},{name:"getString",call:"db_getString"}]};n.exports={methods:e}},{}],5:[function(t,n){var e=function(){var t=function(t){return"string"==typeof t[0]?"eth_blockByHash":"eth_blockByNumber"},n=function(t){return"string"==typeof t[0]?"eth_transactionByHash":"eth_transactionByNumber"},e=function(t){return"string"==typeof t[0]?"eth_uncleByHash":"eth_uncleByNumber"},r=function(t){return"string"==typeof t[0]?"eth_transactionCountByHash":"eth_transactionCountByNumber"},o=function(t){return"string"==typeof t[0]?"eth_uncleCountByHash":"eth_uncleCountByNumber"};return[{name:"balanceAt",call:"eth_balanceAt"},{name:"stateAt",call:"eth_stateAt"},{name:"storageAt",call:"eth_storageAt"},{name:"countAt",call:"eth_countAt"},{name:"codeAt",call:"eth_codeAt"},{name:"transact",call:"eth_transact"},{name:"call",call:"eth_call"},{name:"block",call:t},{name:"transaction",call:n},{name:"uncle",call:e},{name:"compilers",call:"eth_compilers"},{name:"flush",call:"eth_flush"},{name:"lll",call:"eth_lll"},{name:"solidity",call:"eth_solidity"},{name:"serpent",call:"eth_serpent"},{name:"logs",call:"eth_logs"},{name:"transactionCount",call:r},{name:"uncleCount",call:o}]},r=function(){return[{name:"coinbase",getter:"eth_coinbase",setter:"eth_setCoinbase"},{name:"listening",getter:"eth_listening",setter:"eth_setListening"},{name:"mining",getter:"eth_mining",setter:"eth_setMining"},{name:"gasPrice",getter:"eth_gasPrice"},{name:"accounts",getter:"eth_accounts"},{name:"peerCount",getter:"eth_peerCount"},{name:"defaultBlock",getter:"eth_defaultBlock",setter:"eth_setDefaultBlock"},{name:"number",getter:"eth_number"}]};n.exports={methods:e,properties:r}},{}],6:[function(t,n){var e=t("./abi"),r=t("./utils"),o=t("./signature"),a=function(t,n){return t.filter(function(t){return t.indexed===n})},i=function(t,n){var e=r.findIndex(t,function(t){return t.name===n});return-1===e?void console.error("indexed param with name "+n+" not found"):t[e]},u=function(t,n){return Object.keys(n).map(function(r){var o=[i(a(t.inputs,!0),r)],u=n[r];return u instanceof Array?u.map(function(t){return e.formatInput(o,[t])}):e.formatInput(o,[u])})},f=function(t,n,e){return function(r,o){var a=o||{};return a.address=t,a.topic=[],a.topic.push(n),r&&(a.topic=a.topic.concat(u(e,r))),a}},s=function(t,n,e){var r=n.slice(),o=e.slice();return t.reduce(function(t,n){var e;return e=n.indexed?r.splice(0,1)[0]:o.splice(0,1)[0],t[n.name]=e,t},{})},c=function(t){return function(n){var o={event:r.extractDisplayName(t.name),number:n.number,hash:n.hash,args:{}};if(n.topics=n.topic,!n.topic)return o;var i=a(t.inputs,!0),u="0x"+n.topic.slice(1,n.topic.length).map(function(t){return t.slice(2)}).join(""),f=e.formatOutput(i,u),c=a(t.inputs,!1),l=e.formatOutput(c,n.data);return o.args=s(t.inputs,f,l),o}},l=function(t,n){for(var e=0;ee;e+=2){var o=parseInt(t.substr(e,2),16);if(0===o)break;n+=String.fromCharCode(o)}return n},a=function(t){for(var n="",e=0;e3e3&&r2?t.substring(2):"0",new BigNumber(t,16).toString(10)},fromDecimal:function(t){return"0x"+new BigNumber(t).toString(16)},toEth:u.toEth,eth:{contractFromAbi:function(t){return function(n){n=n||"0xc6d9d2cd449a754c494264e1809c50e34d64562b";var e=g.eth.contract(n,t);return e.address=n,e}},canary:function(){return function(t){return t=t||"0xc6d9d2cd449a754c494264e1809c50e34d64562b"}},watch:function(t,n,e,r){return t._isEvent?t(n,e):i(t,h,r)}},db:{},shh:{watch:function(t){return i(t,d)}},setProvider:function(t){g.manager.setProvider(t)},reset:function(){g.manager.reset()}};c(g,s()),c(g.eth,e.methods()),l(g.eth,e.properties()),c(g.db,r.methods()),c(g.shh,o.methods()),c(h,a.eth()),c(d,a.shh()),n.exports=g},{"./db":4,"./eth":5,"./filter":7,"./requestmanager":12,"./shh":13,"./utils":16,"./watches":17}],web3:[function(t,n){var e=t("./lib/web3");e.providers.HttpSyncProvider=t("./lib/httpsync"),e.providers.QtSyncProvider=t("./lib/qtsync"),e.eth.contract=t("./lib/contract"),e.abi=t("./lib/abi"),n.exports=e},{"./lib/abi":1,"./lib/contract":3,"./lib/httpsync":9,"./lib/qtsync":11,"./lib/web3":18}]},{},["web3"]); \ No newline at end of file +require=function t(e,n,r){function o(i,u){if(!n[i]){if(!e[i]){var s="function"==typeof require&&require;if(!u&&s)return s(i,!0);if(a)return a(i,!0);var c=new Error("Cannot find module '"+i+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[i]={exports:{}};e[i][0].call(l.exports,function(t){var n=e[i][1][t];return o(n?n:t)},l,l.exports,t,e,n,r)}return n[i].exports}for(var a="function"==typeof require&&require,i=0;iy;y++)g.push(d(e.slice(0,s))),e=e.slice(s);n.push(g)}else o.prefixedType("string")(t[c].type)?(l=l.slice(s),n.push(d(e.slice(0,s))),e=e.slice(s)):(n.push(d(e.slice(0,s))),e=e.slice(s))}),n},d=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),o=n.extractTypeName(t.name),a=function(){var e=Array.prototype.slice.call(arguments);return l(t.inputs,e)};void 0===e[r]&&(e[r]=a),e[r][o]=a}),e},h=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),o=n.extractTypeName(t.name),a=function(e){return m(t.outputs,e)};void 0===e[r]&&(e[r]=a),e[r][o]=a}),e};e.exports={inputParser:d,outputParser:h,formatInput:l,formatOutput:m}},{"../utils/config":4,"../utils/utils":5,"./formatters":2,"./types":3}],2:[function(t,e){var n=t("../utils/utils"),r=t("../utils/config"),o=function(t,e,n){return new Array(e-t.length+1).join(n?n:"0")+t},a=function(t){var e=2*r.ETH_PADDING;return BigNumber.config(r.ETH_BIGNUMBER_ROUNDING_MODE),o(n.toTwosComplement(t).round().toString(16),e)},i=function(t){return n.fromAscii(t,r.ETH_PADDING).substr(2)},u=function(t){return"000000000000000000000000000000000000000000000000000000000000000"+(t?"1":"0")},s=function(t){return a(new BigNumber(t).times(new BigNumber(2).pow(128)))},c=function(t){return"1"===new BigNumber(t.substr(0,1),16).toString(2).substr(0,1)},l=function(t){return t=t||"0",c(t)?new BigNumber(t,16).minus(new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16)).minus(1):new BigNumber(t,16)},f=function(t){return t=t||"0",new BigNumber(t,16)},p=function(t){return l(t).dividedBy(new BigNumber(2).pow(128))},m=function(t){return f(t).dividedBy(new BigNumber(2).pow(128))},d=function(t){return"0x"+t},h=function(t){return"0000000000000000000000000000000000000000000000000000000000000001"===t?!0:!1},g=function(t){return n.toAscii(t)},y=function(t){return"0x"+t.slice(t.length-40,t.length)};e.exports={formatInputInt:a,formatInputString:i,formatInputBool:u,formatInputReal:s,formatOutputInt:l,formatOutputUInt:f,formatOutputReal:p,formatOutputUReal:m,formatOutputHash:d,formatOutputBool:h,formatOutputString:g,formatOutputAddress:y}},{"../utils/config":4,"../utils/utils":5}],3:[function(t,e){var n=t("./formatters"),r=function(t){return function(e){return 0===e.indexOf(t)}},o=function(t){return function(e){return t===e}},a=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:o("address"),format:n.formatInputInt},{type:o("bool"),format:n.formatInputBool}]},i=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:o("address"),format:n.formatOutputAddress},{type:o("bool"),format:n.formatOutputBool}]};e.exports={prefixedType:r,namedType:o,inputTypes:a,outputTypes:i}},{"./formatters":2}],4:[function(t,e){var n=["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:n,ETH_BIGNUMBER_ROUNDING_MODE:{ROUNDING_MODE:BigNumber.ROUND_DOWN},ETH_POLLING_TIMEOUT:1e3,ETH_DEFAULTBLOCK:"latest"}},{}],5:[function(t,e){var n={wei:"1",kwei:"1000",ada:"1000",mwei:"1000000",babbage:"1000000",gwei:"1000000000",shannon:"1000000000",szabo:"1000000000000",finney:"1000000000000000",ether:"1000000000000000000",kether:"1000000000000000000000",grand:"1000000000000000000000",einstein:"1000000000000000000000",mether:"1000000000000000000000000",gether:"1000000000000000000000000000",tether:"1000000000000000000000000000000"},r=function(t,e){for(var n=!1,r=0;rn;n+=2){var o=parseInt(t.substr(n,2),16);if(0===o)break;e+=String.fromCharCode(o)}return e},a=function(t){for(var e="",n=0;n1?(t[n[0]]||(t[n[0]]={}),t[n[0]][n[1]]=r):t[n[0]]=r})},d=function(t,e){e.forEach(function(e){var n={};n.get=function(){return e.newProperty&&console.warn("This property is deprecated please use web3."+e.newProperty+" instead."),v.manager.send({method:e.getter,outputFormatter:e.outputFormatter})},e.setter&&(n.set=function(t){return e.newProperty&&console.warn("This property is deprecated please use web3."+e.newProperty+" instead."),v.manager.send({method:e.setter,params:[t],inputFormatter:e.inputFormatter})}),n.enumerable=!e.newProperty,Object.defineProperty(t,e.name,n)})},h=function(t,e,n,r){v.manager.startPolling({method:t,params:[e]},e,n,r)},g=function(t){v.manager.stopPolling(t)},y={startPolling:h.bind(null,"eth_getFilterChanges"),stopPolling:g},b={startPolling:h.bind(null,"shh_getFilterChanges"),stopPolling:g},v={manager:l(),providers:{},setProvider:function(t){v.manager.setProvider(t)},reset:function(){v.manager.reset()},toHex:s.toHex,toAscii:s.toAscii,fromAscii:s.fromAscii,toDecimal:s.toDecimal,fromDecimal:s.fromDecimal,toBigNumber:s.toBigNumber,toWei:s.toWei,fromWei:s.fromWei,isAddress:s.isAddress,net:{},eth:{contractFromAbi:function(t){return console.warn("Initiating a contract like this is deprecated please use var MyContract = eth.contract(abi); new MyContract(address); instead."),function(e){e=e||"0xc6d9d2cd449a754c494264e1809c50e34d64562b";var n=v.eth.contract(e,t);return n.address=e,n}},filter:function(t,e,n){return t._isEvent?t(e,n):u(t,y,c.outputLogFormatter)},watch:function(t,e,n){return console.warn("eth.watch() is deprecated please use eth.filter() instead."),this.filter(t,e,n)}},db:{},shh:{filter:function(t){return u(t,b,c.outputPostFormatter)},watch:function(t){return console.warn("shh.watch() is deprecated please use shh.filter() instead."),this.filter(t)}}};Object.defineProperty(v.eth,"defaultBlock",{get:function(){return f.ETH_DEFAULTBLOCK},set:function(t){return f.ETH_DEFAULTBLOCK=t,f.ETH_DEFAULTBLOCK}}),m(v,p()),m(v.net,n.methods),d(v.net,n.properties),m(v.eth,r.methods),d(v.eth,r.properties),m(v.db,o.methods()),m(v.shh,a.methods()),m(y,i.eth()),m(b,i.shh()),e.exports=v},{"./solidity/formatters":2,"./utils/config":4,"./utils/utils":5,"./web3/db":8,"./web3/eth":9,"./web3/filter":11,"./web3/net":15,"./web3/requestmanager":17,"./web3/shh":18,"./web3/watches":20}],7:[function(t,e){function n(t,e){t.forEach(function(t){if(-1===t.name.indexOf("(")){var e=t.name,n=t.inputs.map(function(t){return t.type}).join();t.name=e+"("+n+")"}});var n={};return c(n),l(n,t,e),f(n,t,e),p(n,t,e),n}var r=t("../web3"),o=t("../solidity/abi"),a=t("../utils/utils"),i=t("./event"),u=t("./signature"),s=function(t){r._currentContractAbi=t.abi,r._currentContractAddress=t.address,r._currentContractMethodName=t.method,r._currentContractMethodParams=t.params},c=function(t){t.call=function(e){return t._isTransaction=!1,t._options=e,t},t.sendTransaction=function(e){return t._isTransaction=!0,t._options=e,t},t.transact=function(e){return console.warn("myContract.transact() is deprecated please use myContract.sendTransaction() instead."),t.sendTransaction(e)},t._options={},["gas","gasPrice","value","from"].forEach(function(e){t[e]=function(n){return t._options[e]=n,t}})},l=function(t,e,n){var i=o.inputParser(e),c=o.outputParser(e);a.filterFunctions(e).forEach(function(o){var l=a.extractDisplayName(o.name),f=a.extractTypeName(o.name),p=function(){var a=Array.prototype.slice.call(arguments),p=u.functionSignatureFromAscii(o.name),m=i[l][f].apply(null,a),d=t._options||{};d.to=n,d.data=p+m;var h=t._isTransaction===!0||t._isTransaction!==!1&&!o.constant,g=d.collapse!==!1;if(t._options={},t._isTransaction=null,h)return s({abi:e,address:n,method:o.name,params:a}),void r.eth.sendTransaction(d);var y=r.eth.call(d),b=c[l][f](y);return g&&(1===b.length?b=b[0]:0===b.length&&(b=null)),b};void 0===t[l]&&(t[l]=p),t[l][f]=p})},f=function(t,e,n){t.address=n,t._onWatchEventResult=function(t){var n=event.getMatchingEvent(a.filterEvents(e)),r=i.outputParser(n);return r(t)},Object.defineProperty(t,"topics",{get:function(){return a.filterEvents(e).map(function(t){return u.eventSignatureFromAscii(t.name)})}})},p=function(t,e,n){a.filterEvents(e).forEach(function(e){var o=function(){var t=Array.prototype.slice.call(arguments),o=u.eventSignatureFromAscii(e.name),a=i.inputParser(n,o,e),s=a.apply(null,t),c=function(t){var n=i.outputParser(e);return n(t)};return r.eth.filter(s,void 0,void 0,c)};o._isEvent=!0;var s=a.extractDisplayName(e.name),c=a.extractTypeName(e.name);void 0===t[s]&&(t[s]=o),t[s][c]=o})},m=function(t){return t instanceof Array&&1===arguments.length?n.bind(null,t):(console.warn("Initiating a contract like this is deprecated please use var MyContract = eth.contract(abi); new MyContract(address); instead."),new n(arguments[1],arguments[0]))};e.exports=m},{"../solidity/abi":1,"../utils/utils":5,"../web3":6,"./event":10,"./signature":19}],8:[function(t,e){var n=function(){return[{name:"put",call:"db_put"},{name:"get",call:"db_get"},{name:"putString",call:"db_putString"},{name:"getString",call:"db_getString"}]};e.exports={methods:n}},{}],9:[function(t,e){var n=t("./formatters"),r=t("../utils/utils"),o=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getBlockByHash":"eth_getBlockByNumber"},a=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getTransactionByBlockHashAndIndex":"eth_getTransactionByBlockNumberAndIndex"},i=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getUncleByBlockHashAndIndex":"eth_getUncleByBlockNumberAndIndex"},u=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getBlockTransactionCountByHash":"eth_getBlockTransactionCountByNumber"},s=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getUncleCountByBlockHash":"eth_getUncleCountByBlockNumber"},c=[{name:"getBalance",call:"eth_getBalance",addDefaultblock:2,outputFormatter:n.convertToBigNumber},{name:"getStorage",call:"eth_getStorage",addDefaultblock:2},{name:"getStorageAt",call:"eth_getStorageAt",addDefaultblock:3,inputFormatter:r.toHex},{name:"getData",call:"eth_getData",addDefaultblock:2},{name:"getBlock",call:o,outputFormatter:n.outputBlockFormatter,inputFormatter:[r.toHex,function(t){return t?!0:!1}]},{name:"getUncle",call:i,outputFormatter:n.outputBlockFormatter,inputFormatter:[r.toHex,r.toHex,function(t){return t?!0:!1}]},{name:"getCompilers",call:"eth_getCompilers"},{name:"getBlockTransactionCount",call:u,outputFormatter:r.toDecimal,inputFormatter:r.toHex},{name:"getBlockUncleCount",call:s,outputFormatter:r.toDecimal,inputFormatter:r.toHex},{name:"getTransaction",call:"eth_getTransactionByHash",outputFormatter:n.outputTransactionFormatter},{name:"getTransactionFromBlock",call:a,outputFormatter:n.outputTransactionFormatter,inputFormatter:r.toHex},{name:"getTransactionCount",call:"eth_getTransactionCount",addDefaultblock:2,outputFormatter:r.toDecimal},{name:"sendTransaction",call:"eth_sendTransaction",inputFormatter:n.inputTransactionFormatter},{name:"call",call:"eth_call",addDefaultblock:2,inputFormatter:n.inputCallFormatter},{name:"compile.solidity",call:"eth_compileSolidity",inputFormatter:r.toHex},{name:"compile.lll",call:"eth_compileLLL",inputFormatter:r.toHex},{name:"compile.serpent",call:"eth_compileSerpent",inputFormatter:r.toHex},{name:"flush",call:"eth_flush"},{name:"balanceAt",call:"eth_balanceAt",newMethod:"eth.getBalance"},{name:"stateAt",call:"eth_stateAt",newMethod:"eth.getStorageAt"},{name:"storageAt",call:"eth_storageAt",newMethod:"eth.getStorage"},{name:"countAt",call:"eth_countAt",newMethod:"eth.getTransactionCount"},{name:"codeAt",call:"eth_codeAt",newMethod:"eth.getData"},{name:"transact",call:"eth_transact",newMethod:"eth.sendTransaction"},{name:"block",call:o,newMethod:"eth.getBlock"},{name:"transaction",call:a,newMethod:"eth.getTransaction"},{name:"uncle",call:i,newMethod:"eth.getUncle"},{name:"compilers",call:"eth_compilers",newMethod:"eth.getCompilers"},{name:"solidity",call:"eth_solidity",newMethod:"eth.compile.solidity"},{name:"lll",call:"eth_lll",newMethod:"eth.compile.lll"},{name:"serpent",call:"eth_serpent",newMethod:"eth.compile.serpent"},{name:"transactionCount",call:u,newMethod:"eth.getBlockTransactionCount"},{name:"uncleCount",call:s,newMethod:"eth.getBlockUncleCount"},{name:"logs",call:"eth_logs"}],l=[{name:"coinbase",getter:"eth_coinbase"},{name:"mining",getter:"eth_mining"},{name:"gasPrice",getter:"eth_gasPrice",outputFormatter:n.convertToBigNumber},{name:"accounts",getter:"eth_accounts"},{name:"blockNumber",getter:"eth_blockNumber",outputFormatter:r.toDecimal},{name:"listening",getter:"net_listening",setter:"eth_setListening",newProperty:"net.listening"},{name:"peerCount",getter:"net_peerCount",newProperty:"net.peerCount"},{name:"number",getter:"eth_number",newProperty:"eth.blockNumber"}];e.exports={methods:c,properties:l}},{"../utils/utils":5,"./formatters":12}],10:[function(t,e){var n=t("../solidity/abi"),r=t("../utils/utils"),o=t("./signature"),a=function(t,e){return t.filter(function(t){return t.indexed===e})},i=function(t,e){var n=r.findIndex(t,function(t){return t.name===e});return-1===n?void console.error("indexed param with name "+e+" not found"):t[n]},u=function(t,e){return Object.keys(e).map(function(r){var o=[i(a(t.inputs,!0),r)],u=e[r];return u instanceof Array?u.map(function(t){return n.formatInput(o,[t])}):n.formatInput(o,[u])})},s=function(t,e,n){return function(r,o){var a=o||{};return a.address=t,a.topics=[],a.topics.push(e),r&&(a.topics=a.topics.concat(u(n,r))),a}},c=function(t,e,n){var r=e.slice(),o=n.slice();return t.reduce(function(t,e){var n;return n=e.indexed?r.splice(0,1)[0]:o.splice(0,1)[0],t[e.name]=n,t},{})},l=function(t){return function(e){var o={event:r.extractDisplayName(t.name),number:e.number,hash:e.hash,args:{}};if(e.topics=e.topic,!e.topics)return o;var i=a(t.inputs,!0),u="0x"+e.topics.slice(1,e.topics.length).map(function(t){return t.slice(2)}).join(""),s=n.formatOutput(i,u),l=a(t.inputs,!1),f=n.formatOutput(l,e.data);return o.args=c(t.inputs,s,f),o}},f=function(t,e){for(var n=0;n var web3 = require('web3'); - web3.setProvider(new web3.providers.HttpSyncProvider('http://localhost:8080')); + web3.setProvider(new web3.providers.HttpProvider()); function watchBalance() { var coinbase = web3.eth.coinbase; - var originalBalance = 0; - var balance = web3.eth.balanceAt(coinbase); - var originalBalance = web3.toDecimal(balance); - document.getElementById('original').innerText = 'original balance: ' + originalBalance + ' watching...'; + var originalBalance = web3.eth.getBalance(coinbase).toNumber(); + document.getElementById('coinbase').innerText = 'coinbase: ' + coinbase; + document.getElementById('original').innerText = ' original balance: ' + originalBalance + ' watching...'; - web3.eth.watch('pending').changed(function() { - balance = web3.eth.balanceAt(coinbase) - var currentBalance = web3.toDecimal(balance); + web3.eth.filter('pending').watch(function() { + var currentBalance = web3.eth.getBalance(coinbase).toNumber(); document.getElementById("current").innerText = 'current: ' + currentBalance; document.getElementById("diff").innerText = 'diff: ' + (currentBalance - originalBalance); }); @@ -31,6 +29,7 @@

coinbase balance

+
diff --git a/libjsqrc/ethereumjs/example/contract.html b/libjsqrc/ethereumjs/example/contract.html index a534f68d8..ce96d8d5c 100644 --- a/libjsqrc/ethereumjs/example/contract.html +++ b/libjsqrc/ethereumjs/example/contract.html @@ -7,7 +7,7 @@