UNPKG

multichain-crypto-wallet

Version:

A Multichain crypto wallet library that supports Ethereum, Bitcoin, Solana, Waves and other EVM compatible blockchains E.g. Binance Smart Chain, Polygon, Avalanche etc.

1,382 lines (1,368 loc) 131 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var bip39 = require('bip39'); var bitcoin = require('bitcoinjs-lib'); var ecc = require('tiny-secp256k1'); var bip32$1 = require('bip32'); var ecpair = require('ecpair'); require('base64-js'); var BigNumber = _interopDefault(require('bignumber.js')); var immutable = require('immutable'); var utxolib = require('@bitgo/utxo-lib'); var axios = _interopDefault(require('axios')); var url = require('url'); var ethers = require('ethers'); var solanaWeb3 = require('@solana/web3.js'); var splToken = require('@solana/spl-token'); var bs58 = require('bs58'); var ed25519HdKey = require('ed25519-hd-key'); var BufferLayout = require('buffer-layout'); var tsLibCrypto = require('@waves/ts-lib-crypto'); var wavesTransactions = require('@waves/waves-transactions'); var tronweb = require('tronweb'); function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _createForOfIteratorHelperLoose(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (t) return (t = t.call(r)).next.bind(t); if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var o = 0; return function () { return o >= r.length ? { done: !0 } : { done: !1, value: r[o++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; } function _regeneratorRuntime() { _regeneratorRuntime = function () { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function (t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function (t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(typeof e + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function (e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function () { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function (e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function (t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function (t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function (e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } var successResponse = function successResponse(args) { return args; }; /** * https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array/12646864#12646864 * Randomize array element order in-place. * Using Durstenfeld shuffle algorithm. */ var shuffleArray = function shuffleArray() { for (var _len = arguments.length, arrayIn = new Array(_len), _key = 0; _key < _len; _key++) { arrayIn[_key] = arguments[_key]; } var array = arrayIn.length === 1 && Array.isArray(arrayIn[0]) ? arrayIn[0] : arrayIn; for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var _ref2 = [array[j], array[i]]; array[i] = _ref2[0]; array[j] = _ref2[1]; } return array; }; /** * sortUTXOs compares two UTXOs by amount, then confirmations and then hash. * * @example * sortUTXOs({amount: 1, confirmations: 1}, {amount: 2, confirmations: 0}); * // -1, representing that the first parameter should be ordered first. * * @returns a negative value to represent that a should come before b or a * positive value to represent that b should come before a. */ var sortUTXOs = function sortUTXOs(a, b) { // Sort greater values first if (a.amount !== b.amount) { return b.amount - a.amount; } // Sort older UTXOs first if (a.confirmations !== b.confirmations) { return a.confirmations - b.confirmations; } return a.txHash <= b.txHash ? -1 : 1; }; /** * fixValue turns a readable value, e.g. `0.0001` BTC, to the value in the smallest * unit, e.g. `10000` sats. * * @example * fixValue(0.0001, 8) = 10000; * * @param value Value in the readable representation, e.g. `0.0001` BTC. * @param decimals The number of decimals to shift by, e.g. 8. */ var fixValue = function fixValue(value, decimals) { return new BigNumber(value).multipliedBy(new BigNumber(10).exponentiatedBy(decimals)).decimalPlaces(0).toNumber(); }; /** * fixUTXO calls {{fixValue}} on the value of the UTXO. */ var fixUTXO = function fixUTXO(utxo, decimals) { return _extends({}, utxo, { amount: fixValue(utxo.amount, decimals) }); }; /** * fixUTXOs maps over an array of UTXOs and calls {{fixValue}}. */ var fixUTXOs = function fixUTXOs(utxos, decimals) { return utxos.map(function (utxo) { return fixUTXO(utxo, decimals); }); }; var SECONDS = 1000; var DEFAULT_TIMEOUT = 30 * SECONDS; var BlockchainNetwork; (function (BlockchainNetwork) { BlockchainNetwork["Bitcoin"] = "btc"; BlockchainNetwork["BitcoinCash"] = "bch"; BlockchainNetwork["BitcoinTestnet"] = "btc-testnet"; BlockchainNetwork["BitcoinCashTestnet"] = "bch-testnet"; })(BlockchainNetwork || (BlockchainNetwork = {})); var fetchLatestBlock = /*#__PURE__*/function () { var _ref = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(network) { var statsUrl, statsResponse; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: statsUrl = "https://api.blockchain.info/haskoin-store/" + network + "/block/best?notx=true"; _context.next = 3; return axios.get(statsUrl); case 3: statsResponse = _context.sent.data; return _context.abrupt("return", statsResponse.height); case 5: case "end": return _context.stop(); } }, _callee); })); return function fetchLatestBlock(_x) { return _ref.apply(this, arguments); }; }(); var fetchUTXO = function fetchUTXO(network) { return /*#__PURE__*/function () { var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(txHash, vOut) { var url, response, confirmations; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: url = "https://api.blockchain.info/haskoin-store/" + network + "/transaction/" + txHash; _context2.next = 3; return axios.get("" + url, { timeout: DEFAULT_TIMEOUT }); case 3: response = _context2.sent.data; if (!(!response.block || !response.block.height)) { _context2.next = 8; break; } _context2.t0 = 0; _context2.next = 16; break; case 8: _context2.t1 = Math; _context2.next = 11; return fetchLatestBlock(network); case 11: _context2.t2 = _context2.sent; _context2.t3 = response.block.height; _context2.t4 = _context2.t2 - _context2.t3; _context2.t5 = _context2.t4 + 1; _context2.t0 = _context2.t1.max.call(_context2.t1, _context2.t5, 0); case 16: confirmations = _context2.t0; return _context2.abrupt("return", { txHash: txHash, block: response.block && response.block.height ? response.block.height : 0, amount: response.outputs[vOut].value, confirmations: confirmations }); case 18: case "end": return _context2.stop(); } }, _callee2); })); return function (_x2, _x3) { return _ref2.apply(this, arguments); }; }(); }; var fetchUTXOs = function fetchUTXOs(network) { return /*#__PURE__*/function () { var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(address, confirmations, limit, offset) { return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: if (limit === void 0) { limit = 25; } if (offset === void 0) { offset = 0; } return _context3.abrupt("return", fetchTXs(network)(address, confirmations, limit, offset, true)); case 3: case "end": return _context3.stop(); } }, _callee3); })); return function (_x4, _x5, _x6, _x7) { return _ref3.apply(this, arguments); }; }(); }; var fetchTXs = function fetchTXs(network) { return /*#__PURE__*/function () { var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(address, confirmations, limit, offset, onlyUnspent) { var url, response, latestBlock, received, _iterator, _step, tx, txConfirmations, i, vout; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: if (confirmations === void 0) { confirmations = 0; } if (limit === void 0) { limit = 25; } if (offset === void 0) { offset = 0; } if (onlyUnspent === void 0) { onlyUnspent = false; } url = "https://api.blockchain.info/haskoin-store/" + network + "/address/" + address + "/transactions/full?limit=" + limit + "&offset=" + offset; _context4.next = 7; return axios.get(url, { timeout: DEFAULT_TIMEOUT }); case 7: response = _context4.sent.data; received = []; _iterator = _createForOfIteratorHelperLoose(response); case 10: if ((_step = _iterator()).done) { _context4.next = 22; break; } tx = _step.value; _context4.t0 = latestBlock; if (_context4.t0) { _context4.next = 17; break; } _context4.next = 16; return fetchLatestBlock(network); case 16: _context4.t0 = _context4.sent; case 17: latestBlock = _context4.t0; txConfirmations = tx.block && tx.block.height ? Math.max(latestBlock - tx.block.height + 1, 0) : 0; for (i = 0; i < tx.outputs.length; i++) { vout = tx.outputs[i]; if (vout.address === address && ( // If the onlyUnspent flag is true, check that the tx is unspent. !onlyUnspent || vout.spent === false)) { received.push({ txHash: tx.txid, amount: vout.value, vOut: i, confirmations: txConfirmations }); } } case 20: _context4.next = 10; break; case 22: return _context4.abrupt("return", received.filter(function (utxo) { return confirmations === 0 || utxo.confirmations >= confirmations; }).sort(sortUTXOs)); case 23: case "end": return _context4.stop(); } }, _callee4); })); return function (_x8, _x9, _x10, _x11, _x12) { return _ref4.apply(this, arguments); }; }(); }; var broadcastTransaction = function broadcastTransaction(network) { return /*#__PURE__*/function () { var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(txHex) { var url$1, params, response; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: if (!(network !== BlockchainNetwork.Bitcoin)) { _context5.next = 2; break; } throw new Error("Broadcasting " + network + " transactions not supported by endpoint."); case 2: url$1 = "https://blockchain.info/pushtx"; params = new url.URLSearchParams(); params.append('tx', txHex); _context5.next = 7; return axios.post(url$1, params, { timeout: DEFAULT_TIMEOUT }); case 7: response = _context5.sent; if (!response.data.error) { _context5.next = 10; break; } throw new Error(response.data.error); case 10: return _context5.abrupt("return", response.data); case 11: case "end": return _context5.stop(); } }, _callee5); })); return function (_x13) { return _ref5.apply(this, arguments); }; }(); }; var Blockchain = { networks: BlockchainNetwork, fetchUTXO: fetchUTXO, fetchUTXOs: fetchUTXOs, broadcastTransaction: broadcastTransaction, fetchTXs: fetchTXs }; var getAPIUrl = function getAPIUrl(testnet) { return "https://blockstream.info/" + (testnet ? 'testnet/' : '') + "api"; }; var fetchUTXO$1 = function fetchUTXO(testnet) { return /*#__PURE__*/function () { var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(txHash, vOut) { var apiUrl, utxo, heightResponse, confirmations; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: apiUrl = getAPIUrl(testnet); _context.next = 3; return axios.get(apiUrl + "/tx/" + txHash, { timeout: DEFAULT_TIMEOUT }); case 3: utxo = _context.sent.data; _context.next = 6; return axios.get(apiUrl + "/blocks/tip/height", { timeout: DEFAULT_TIMEOUT }); case 6: heightResponse = _context.sent.data; confirmations = utxo.status.confirmed ? Math.max(1 + parseInt(heightResponse, 10) - utxo.status.block_height, 0) : 0; return _context.abrupt("return", { txHash: txHash, block: utxo.status.confirmed ? utxo.status.block_height : 0, amount: utxo.vout[vOut].value, confirmations: confirmations }); case 9: case "end": return _context.stop(); } }, _callee); })); return function (_x, _x2) { return _ref.apply(this, arguments); }; }(); }; var fetchUTXOs$1 = function fetchUTXOs(testnet) { return /*#__PURE__*/function () { var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(address, confirmations) { var apiUrl, response, heightResponse; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: apiUrl = getAPIUrl(testnet); _context2.next = 3; return axios.get(apiUrl + "/address/" + address + "/utxo", { timeout: DEFAULT_TIMEOUT }); case 3: response = _context2.sent; _context2.next = 6; return axios.get(apiUrl + "/blocks/tip/height", { timeout: DEFAULT_TIMEOUT }); case 6: heightResponse = _context2.sent; return _context2.abrupt("return", response.data.map(function (utxo) { return { txHash: utxo.txid, amount: utxo.value, vOut: utxo.vout, confirmations: utxo.status.confirmed ? 1 + parseInt(heightResponse.data, 10) - utxo.status.block_height : 0 }; }).filter(function (utxo) { return confirmations === 0 || utxo.confirmations >= confirmations; }).sort(sortUTXOs)); case 8: case "end": return _context2.stop(); } }, _callee2); })); return function (_x3, _x4) { return _ref2.apply(this, arguments); }; }(); }; var fetchTXs$1 = function fetchTXs(testnet) { return /*#__PURE__*/function () { var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(address, confirmations) { var apiUrl, response, heightResponse, received, _iterator, _step, tx, i, vout; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: if (confirmations === void 0) { confirmations = 0; } apiUrl = getAPIUrl(testnet); _context3.next = 4; return axios.get(apiUrl + "/address/" + address + "/txs", { timeout: DEFAULT_TIMEOUT }); case 4: response = _context3.sent; _context3.next = 7; return axios.get(apiUrl + "/blocks/tip/height", { timeout: DEFAULT_TIMEOUT }); case 7: heightResponse = _context3.sent; received = []; for (_iterator = _createForOfIteratorHelperLoose(response.data); !(_step = _iterator()).done;) { tx = _step.value; for (i = 0; i < tx.vout.length; i++) { vout = tx.vout[i]; if (vout.scriptpubkey_address === address) { received.push({ txHash: tx.txid, amount: vout.value, vOut: i, confirmations: tx.status.confirmed ? 1 + parseInt(heightResponse.data, 10) - tx.status.block_height : 0 }); } } } return _context3.abrupt("return", received.filter(function (utxo) { return confirmations === 0 || utxo.confirmations >= confirmations; }).sort(sortUTXOs)); case 11: case "end": return _context3.stop(); } }, _callee3); })); return function (_x5, _x6) { return _ref3.apply(this, arguments); }; }(); }; var broadcastTransaction$1 = function broadcastTransaction(testnet) { return /*#__PURE__*/function () { var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(txHex) { var apiUrl, response; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: apiUrl = getAPIUrl(testnet); _context4.next = 3; return axios.post(apiUrl + "/tx", txHex, { timeout: DEFAULT_TIMEOUT }); case 3: response = _context4.sent; return _context4.abrupt("return", response.data); case 5: case "end": return _context4.stop(); } }, _callee4); })); return function (_x7) { return _ref4.apply(this, arguments); }; }(); }; var Blockstream = { fetchUTXO: fetchUTXO$1, fetchUTXOs: fetchUTXOs$1, broadcastTransaction: broadcastTransaction$1, fetchTXs: fetchTXs$1 }; var fetchUTXO$2 = function fetchUTXO(network) { return /*#__PURE__*/function () { var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(txHash, vOut) { var url, response, tx; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: url = "https://sochain.com/api/v2/get_tx/" + network + "/" + txHash; _context.next = 3; return axios.get(url, { timeout: DEFAULT_TIMEOUT }); case 3: response = _context.sent; tx = response.data.data; return _context.abrupt("return", fixUTXO({ txHash: tx.txid, amount: parseInt(tx.outputs[vOut].value, 10), // scriptPubKey: tx.script_hex, vOut: vOut, confirmations: tx.confirmations }, 8)); case 6: case "end": return _context.stop(); } }, _callee); })); return function (_x, _x2) { return _ref.apply(this, arguments); }; }(); }; var fetchUTXOs$2 = function fetchUTXOs(network) { return /*#__PURE__*/function () { var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(address, confirmations) { var url, response; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: url = "https://sochain.com/api/v2/get_tx_unspent/" + network + "/" + address + "/" + confirmations; _context2.next = 3; return axios.get(url, { timeout: DEFAULT_TIMEOUT }); case 3: response = _context2.sent; return _context2.abrupt("return", fixUTXOs(response.data.data.txs.map(function (utxo) { return { txHash: utxo.txid, amount: utxo.value, // scriptPubKey: utxo.script_hex, vOut: utxo.output_no, confirmations: utxo.confirmations }; }), 8).filter(function (utxo) { return confirmations === 0 || utxo.confirmations >= confirmations; }).sort(sortUTXOs)); case 5: case "end": return _context2.stop(); } }, _callee2); })); return function (_x3, _x4) { return _ref2.apply(this, arguments); }; }(); }; var fetchTXs$2 = function fetchTXs(network) { return /*#__PURE__*/function () { var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(address, confirmations) { var url, response; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: if (confirmations === void 0) { confirmations = 0; } url = "https://sochain.com/api/v2/get_tx_received/" + network + "/" + address + "/" + confirmations; _context3.next = 4; return axios.get(url, { timeout: DEFAULT_TIMEOUT }); case 4: response = _context3.sent; return _context3.abrupt("return", fixUTXOs(response.data.data.txs.map(function (utxo) { return { txHash: utxo.txid, amount: utxo.value, // scriptPubKey: utxo.script_hex, vOut: utxo.output_no, confirmations: utxo.confirmations }; }), 8).filter(function (utxo) { return confirmations === 0 || utxo.confirmations >= confirmations; }).sort(sortUTXOs)); case 6: case "end": return _context3.stop(); } }, _callee3); })); return function (_x5, _x6) { return _ref3.apply(this, arguments); }; }(); }; var broadcastTransaction$2 = function broadcastTransaction(network) { return /*#__PURE__*/function () { var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(txHex) { var response; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return axios.post("https://sochain.com/api/v2/send_tx/" + network, { tx_hex: txHex }, { timeout: DEFAULT_TIMEOUT }); case 2: response = _context4.sent; return _context4.abrupt("return", response.data.data.txid); case 4: case "end": return _context4.stop(); } }, _callee4); })); return function (_x7) { return _ref4.apply(this, arguments); }; }(); }; var Sochain = { fetchUTXOs: fetchUTXOs$2, broadcastTransaction: broadcastTransaction$2, fetchUTXO: fetchUTXO$2, fetchTXs: fetchTXs$2 }; var fetchUTXO$3 = function fetchUTXO(network) { return /*#__PURE__*/function () { var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(txHash, vOut) { var url, response, tx, latestBlock, statsUrl, statsResponse, confirmations; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: url = "https://api.blockchair.com/" + network + "/dashboards/transaction/" + txHash; _context.next = 3; return axios.get("" + url, { timeout: DEFAULT_TIMEOUT }); case 3: response = _context.sent.data; if (response.data[txHash]) { _context.next = 6; break; } throw new Error("Transaction not found."); case 6: tx = response.data[txHash]; latestBlock = response.context.state; if (!(latestBlock === 0)) { _context.next = 14; break; } statsUrl = "https://api.blockchair.com/" + network + "/stats"; _context.next = 12; return axios.get(statsUrl); case 12: statsResponse = _context.sent.data; latestBlock = statsResponse.data.blocks - 1; case 14: confirmations = tx.transaction.block_id === -1 ? 0 : Math.max(latestBlock - tx.transaction.block_id + 1, 0); return _context.abrupt("return", { txHash: txHash, block: tx.transaction.block_id === -1 ? 0 : tx.transaction.block_id, amount: tx.outputs[vOut].value, confirmations: confirmations }); case 16: case "end": return _context.stop(); } }, _callee); })); return function (_x, _x2) { return _ref.apply(this, arguments); }; }(); }; var fetchUTXOs$3 = function fetchUTXOs(network) { return /*#__PURE__*/function () { var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(address, confirmations) { var url, response, latestBlock, statsUrl, statsResponse; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: url = "https://api.blockchair.com/" + network + "/dashboards/address/" + address + "?limit=0,100"; _context2.next = 3; return axios.get(url, { timeout: DEFAULT_TIMEOUT }); case 3: response = _context2.sent.data; latestBlock = response.context.state; if (!(latestBlock === 0)) { _context2.next = 11; break; } statsUrl = "https://api.blockchair.com/" + network + "/stats"; _context2.next = 9; return axios.get(statsUrl); case 9: statsResponse = _context2.sent.data; latestBlock = statsResponse.data.blocks - 1; case 11: return _context2.abrupt("return", response.data[address].utxo.map(function (utxo) { return { txHash: utxo.transaction_hash, amount: utxo.value, vOut: utxo.index, confirmations: utxo.block_id === -1 ? 0 : latestBlock - utxo.block_id + 1 }; }).filter(function (utxo) { return confirmations === 0 || utxo.confirmations >= confirmations; }).sort(sortUTXOs)); case 12: case "end": return _context2.stop(); } }, _callee2); })); return function (_x3, _x4) { return _ref2.apply(this, arguments); }; }(); }; var fetchTXs$3 = function fetchTXs(network) { return /*#__PURE__*/function () { var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(address, confirmations, limit) { var url, response, latestBlock, statsUrl, statsResponse, txHashes, txDetails, i, txUrl, txResponse, received, _iterator, _step, txHash, tx, txConfirmations, _i, vout; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: if (confirmations === void 0) { confirmations = 0; } if (limit === void 0) { limit = 25; } url = "https://api.blockchair.com/" + network + "/dashboards/address/" + address + "?limit=" + limit + ",0"; _context3.next = 5; return axios.get(url, { timeout: DEFAULT_TIMEOUT }); case 5: response = _context3.sent.data; latestBlock = response.context.state; if (!(latestBlock === 0)) { _context3.next = 13; break; } statsUrl = "https://api.blockchair.com/" + network + "/stats"; _context3.next = 11; return axios.get(statsUrl); case 11: statsResponse = _context3.sent.data; latestBlock = statsResponse.data.blocks - 1; case 13: txHashes = response.data[address].transactions; txDetails = {}; // Fetch in sets of 10 i = 0; case 16: if (!(i < Math.ceil(txHashes.length / 10))) { _context3.next = 25; break; } txUrl = "https://api.blockchair.com/" + network + "/dashboards/transactions/" + txHashes.slice(i * 10, (i + 1) * 10).join(','); _context3.next = 20; return axios.get(txUrl, { timeout: DEFAULT_TIMEOUT }); case 20: txResponse = _context3.sent.data; txDetails = _extends({}, txDetails, txResponse.data); case 22: i++; _context3.next = 16; break; case 25: received = []; for (_iterator = _createForOfIteratorHelperLoose(txHashes); !(_step = _iterator()).done;) { txHash = _step.value; tx = txDetails[txHash]; txConfirmations = tx.transaction.block_id === -1 ? 0 : Math.max(latestBlock - tx.transaction.block_id + 1, 0); for (_i = 0; _i < tx.outputs.length; _i++) { vout = tx.outputs[_i]; if (vout.recipient === address) { received.push({ txHash: tx.transaction.hash, amount: vout.value, vOut: _i, confirmations: txConfirmations }); } } } return _context3.abrupt("return", received.filter(function (utxo) { return confirmations === 0 || utxo.confirmations >= confirmations; }).sort(sortUTXOs)); case 28: case "end": return _context3.stop(); } }, _callee3); })); return function (_x5, _x6, _x7) { return _ref3.apply(this, arguments); }; }(); }; var broadcastTransaction$3 = function broadcastTransaction(network) { return /*#__PURE__*/function () { var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(txHex) { var url, response; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: url = "https://api.blockchair.com/" + network + "/push/transaction"; _context4.next = 3; return axios.post(url, { data: txHex }, { timeout: DEFAULT_TIMEOUT }); case 3: response = _context4.sent; if (!response.data.error) { _context4.next = 6; break; } throw new Error(response.data.error); case 6: return _context4.abrupt("return", response.data.data.transaction_hash); case 7: case "end": return _context4.stop(); } }, _callee4); })); return function (_x8) { return _ref4.apply(this, arguments); }; }(); }; var Networks; (function (Networks) { Networks["BITCOIN"] = "bitcoin"; Networks["BITCOIN_CASH"] = "bitcoin-cash"; Networks["LITECOIN"] = "litecoin"; Networks["BITCOIN_SV"] = "bitcoin-sv"; Networks["DOGECOIN"] = "dogecoin"; Networks["DASH"] = "dash"; Networks["GROESTLCOIN"] = "groestlcoin"; Networks["BITCOIN_TESTNET"] = "bitcoin/testnet"; })(Networks || (Networks = {})); var Blockchair = { networks: Networks, fetchUTXO: fetchUTXO$3, fetchUTXOs: fetchUTXOs$3, broadcastTransaction: broadcastTransaction$3, fetchTXs: fetchTXs$3 }; var getURL = function getURL(network, testnet) { return "https://multichain-web-proxy.herokuapp.com/electrumx-" + network + "-" + (testnet ? 'testnet' : 'mainnet'); }; var fetchUTXOs$4 = function fetchUTXOs(network, testnet) { return /*#__PURE__*/function () { var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(address, confirmations, scriptHash) { var url, latestBlock, response; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: if (scriptHash) { _context.next = 2; break; } throw new Error('Must provide script hash.' + address); case 2: url = getURL(network, testnet); _context.next = 5; return axios.post(url, { jsonrpc: '1.0', id: '67', method: 'blockchain.scripthash.listunspent', params: [scriptHash] }); case 5: latestBlock = _context.sent.data.result.height; _context.next = 8; return axios.post(url, { jsonrpc: '1.0', id: '67', method: 'blockchain.scripthash.listunspent', params: [scriptHash] }); case 8: response = _context.sent; return _context.abrupt("return", response.data.result.map(function (utxo) { return { txHash: utxo.tx_hash, amount: utxo.value, vOut: utxo.tx_pos, confirmations: utxo.height ? 1 + latestBlock - utxo.height : 0 }; }).filter(function (utxo) { return confirmations === 0 || utxo.confirmations >= confirmations; }).sort(sortUTXOs)); case 10: case "end": return _context.stop(); } }, _callee); })); return function (_x, _x2, _x3) { return _ref.apply(this, arguments); }; }(); }; var ElectrumX = { fetchUTXOs: fetchUTXOs$4 }; var MULTICHAIN_URLS = { BTC: 'https://multichain-web-proxy.herokuapp.com/multichain-bitcoin', BTCTEST: 'https://multichain-web-proxy.herokuapp.com/multichain-bitcoin-testnet', ZEC: 'https://multichain-web-proxy.herokuapp.com/multichain-zcash', ZECTEST: 'https://multichain-web-proxy.herokuapp.com/multichain-zcash-testnet', BCH: 'https://multichain-web-proxy.herokuapp.com/multichain-bitcoincash', BCHTEST: 'https://multichain-web-proxy.herokuapp.com/multichain-bitcoincash-testnet' }; var broadcastTransaction$4 = function broadcastTransaction(url) { return /*#__PURE__*/function () { var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(txHex) { var response; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: _context.next = 2; return axios.post(url, { jsonrpc: '1.0', id: '67', method: 'sendrawtransaction', params: [txHex] }, { timeout: DEFAULT_TIMEOUT }); case 2: response = _context.sent; return _context.abrupt("return", response.data.result); case 4: case "end": return _context.stop(); } }, _callee); })); return function (_x) { return _ref.apply(this, arguments); }; }(); }; var JSONRPC = { broadcastTransaction: broadcastTransaction$4 }; var _apiFallbacks = { fetchUTXO: function fetchUTXO(testnet, txHash, vOut) { return [].concat(shuffleArray(function () { return Blockstream.fetchUTXO(testnet)(txHash, vOut); }, function () { return Blockchair.fetchUTXO(testnet ? Blockchair.networks.BITCOIN_TESTNET : Blockchair.networks.BITCOIN)(txHash, vOut); }), [function () { return Blockchain.fetchUTXO(testnet ? BlockchainNetwork.BitcoinTestnet : BlockchainNetwork.Bitcoin)(txHash, vOut); }]); }, fetchUTXOs: function fetchUTXOs(testnet, address, confirmations, scriptHash) { return [].concat(shuffleArray(function () { return Blockstream.fetchUTXOs(testnet)(address, confirmations); }, function () { return Blockchair.fetchUTXOs(testnet ? Blockchair.networks.BITCOIN_TESTNET : Blockchair.networks.BITCOIN)(address, confirmations); }), [function () { return Sochain.fetchUTXOs(testnet ? 'BTCTEST' : 'BTC')(address, confirmations); }, function () { return Blockchain.fetchUTXOs(testnet ? BlockchainNetwork.BitcoinTestnet : BlockchainNetwork.Bitcoin)(address, confirmations); }, function () { return ElectrumX.fetchUTXOs('bitcoin', testnet)(address, confirmations, scriptHash); }]); }, fetchTXs: function fetchTXs(testnet, address, confirmations) { if (confirmations === void 0) { confirmations = 0; } return [].concat(shuffleArray(function () { return Blockstream.fetchTXs(testnet)(address); }, function () { return Blockchair.fetchTXs(testnet ? Blockchair.networks.BITCOIN_TESTNET : Block