mainnet-js 1.1.34 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/index.html +1 -1
  2. package/dist/{mainnet-1.1.34.js → mainnet-2.0.0.js} +25 -337
  3. package/dist/module/db/SqlProvider.d.ts +2 -2
  4. package/dist/module/db/SqlProvider.d.ts.map +1 -1
  5. package/dist/module/db/SqlProvider.js +6 -24
  6. package/dist/module/db/SqlProvider.js.map +1 -1
  7. package/dist/module/index.d.ts +0 -3
  8. package/dist/module/index.d.ts.map +1 -1
  9. package/dist/module/index.js +3 -6
  10. package/dist/module/index.js.map +1 -1
  11. package/dist/module/transaction/Wif.d.ts +4 -8
  12. package/dist/module/transaction/Wif.d.ts.map +1 -1
  13. package/dist/module/transaction/Wif.js +6 -10
  14. package/dist/module/transaction/Wif.js.map +1 -1
  15. package/dist/module/util/deriveCashaddr.d.ts +1 -0
  16. package/dist/module/util/deriveCashaddr.d.ts.map +1 -1
  17. package/dist/module/util/deriveCashaddr.js +8 -1
  18. package/dist/module/util/deriveCashaddr.js.map +1 -1
  19. package/dist/module/wallet/Base.d.ts +1 -1
  20. package/dist/module/wallet/Base.js +1 -1
  21. package/dist/module/wallet/Util.d.ts +2 -2
  22. package/dist/module/wallet/Util.js +2 -2
  23. package/dist/module/wallet/Wif.d.ts +0 -28
  24. package/dist/module/wallet/Wif.d.ts.map +1 -1
  25. package/dist/module/wallet/Wif.js +2 -109
  26. package/dist/module/wallet/Wif.js.map +1 -1
  27. package/dist/module/wallet/createWallet.d.ts +0 -12
  28. package/dist/module/wallet/createWallet.d.ts.map +1 -1
  29. package/dist/module/wallet/createWallet.js +0 -43
  30. package/dist/module/wallet/createWallet.js.map +1 -1
  31. package/dist/module/wallet/interface.d.ts +0 -2
  32. package/dist/module/wallet/interface.d.ts.map +1 -1
  33. package/dist/module/webhook/Webhook.d.ts +1 -6
  34. package/dist/module/webhook/Webhook.d.ts.map +1 -1
  35. package/dist/module/webhook/Webhook.js +0 -4
  36. package/dist/module/webhook/Webhook.js.map +1 -1
  37. package/dist/module/webhook/index.d.ts +0 -1
  38. package/dist/module/webhook/index.d.ts.map +1 -1
  39. package/dist/module/webhook/index.js +0 -1
  40. package/dist/module/webhook/index.js.map +1 -1
  41. package/dist/module/webhook/interface.d.ts +0 -1
  42. package/dist/module/webhook/interface.d.ts.map +1 -1
  43. package/dist/tsconfig.tsbuildinfo +1 -1
  44. package/package.json +5 -10
  45. package/src/db/SqlProvider.test.ts +2 -18
  46. package/src/db/SqlProvider.ts +5 -26
  47. package/src/index.ts +3 -7
  48. package/src/transaction/Wif.ts +2 -19
  49. package/src/util/deriveCashaddr.test.ts +8 -0
  50. package/src/util/deriveCashaddr.ts +9 -0
  51. package/src/wallet/Base.ts +1 -1
  52. package/src/wallet/Util.ts +2 -2
  53. package/src/wallet/Wif.test.ts +0 -23
  54. package/src/wallet/Wif.ts +2 -148
  55. package/src/wallet/createWallet.ts +0 -53
  56. package/src/wallet/interface.ts +0 -2
  57. package/src/webhook/Webhook.ts +4 -10
  58. package/src/webhook/index.ts +0 -1
  59. package/src/webhook/interface.ts +0 -1
  60. package/webpack.config.cjs +7 -7
  61. package/dist/module/slp/GsppProvider.d.ts +0 -55
  62. package/dist/module/slp/GsppProvider.d.ts.map +0 -1
  63. package/dist/module/slp/GsppProvider.js +0 -204
  64. package/dist/module/slp/GsppProvider.js.map +0 -1
  65. package/dist/module/slp/SlpDbProvider.d.ts +0 -52
  66. package/dist/module/slp/SlpDbProvider.d.ts.map +0 -1
  67. package/dist/module/slp/SlpDbProvider.js +0 -175
  68. package/dist/module/slp/SlpDbProvider.js.map +0 -1
  69. package/dist/module/slp/SlpDbTemplates.d.ts +0 -313
  70. package/dist/module/slp/SlpDbTemplates.d.ts.map +0 -1
  71. package/dist/module/slp/SlpDbTemplates.js +0 -375
  72. package/dist/module/slp/SlpDbTemplates.js.map +0 -1
  73. package/dist/module/slp/SlpLibAuth.d.ts +0 -210
  74. package/dist/module/slp/SlpLibAuth.d.ts.map +0 -1
  75. package/dist/module/slp/SlpLibAuth.js +0 -451
  76. package/dist/module/slp/SlpLibAuth.js.map +0 -1
  77. package/dist/module/slp/SlpProvider.d.ts +0 -24
  78. package/dist/module/slp/SlpProvider.d.ts.map +0 -1
  79. package/dist/module/slp/SlpProvider.js +0 -29
  80. package/dist/module/slp/SlpProvider.js.map +0 -1
  81. package/dist/module/slp/index.d.ts +0 -6
  82. package/dist/module/slp/index.d.ts.map +0 -1
  83. package/dist/module/slp/index.js +0 -5
  84. package/dist/module/slp/index.js.map +0 -1
  85. package/dist/module/slp/interface.d.ts +0 -114
  86. package/dist/module/slp/interface.d.ts.map +0 -1
  87. package/dist/module/slp/interface.js +0 -7
  88. package/dist/module/slp/interface.js.map +0 -1
  89. package/dist/module/util/bchaddr.d.ts +0 -2
  90. package/dist/module/util/bchaddr.d.ts.map +0 -1
  91. package/dist/module/util/bchaddr.js +0 -16
  92. package/dist/module/util/bchaddr.js.map +0 -1
  93. package/dist/module/wallet/Slp.d.ts +0 -431
  94. package/dist/module/wallet/Slp.d.ts.map +0 -1
  95. package/dist/module/wallet/Slp.js +0 -770
  96. package/dist/module/wallet/Slp.js.map +0 -1
  97. package/dist/module/webhook/WebhookSlp.d.ts +0 -15
  98. package/dist/module/webhook/WebhookSlp.d.ts.map +0 -1
  99. package/dist/module/webhook/WebhookSlp.js +0 -100
  100. package/dist/module/webhook/WebhookSlp.js.map +0 -1
  101. package/src/slp/GsppProvider.test.ts +0 -40
  102. package/src/slp/GsppProvider.ts +0 -329
  103. package/src/slp/SlpDbProvider.test.ts +0 -27
  104. package/src/slp/SlpDbProvider.ts +0 -291
  105. package/src/slp/SlpDbTemplates.ts +0 -400
  106. package/src/slp/SlpLibAuth.test.ts +0 -162
  107. package/src/slp/SlpLibAuth.ts +0 -532
  108. package/src/slp/SlpProvider.ts +0 -100
  109. package/src/slp/index.ts +0 -6
  110. package/src/slp/interface.ts +0 -128
  111. package/src/util/bchaddr.test.ts +0 -27
  112. package/src/util/bchaddr.ts +0 -27
  113. package/src/wallet/Slp.test.headless.js +0 -120
  114. package/src/wallet/Slp.test.ts +0 -1000
  115. package/src/wallet/Slp.ts +0 -1014
  116. package/src/webhook/WebhookSlp.test.ts +0 -288
  117. package/src/webhook/WebhookSlp.ts +0 -123
@@ -288,16 +288,6 @@ eval("\n\nvar bind = __webpack_require__(/*! ./helpers/bind */ \"../../node_modu
288
288
 
289
289
  /***/ }),
290
290
 
291
- /***/ "../../node_modules/base-x/src/index.js":
292
- /*!**********************************************!*\
293
- !*** ../../node_modules/base-x/src/index.js ***!
294
- \**********************************************/
295
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
296
-
297
- eval("\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n// @ts-ignore\nvar _Buffer = (__webpack_require__(/*! safe-buffer */ \"../../node_modules/safe-buffer/index.js\").Buffer)\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256)\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i)\n var xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n var BASE = ALPHABET.length\n var LEADER = ALPHABET.charAt(0)\n var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) }\n if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0\n var length = 0\n var pbegin = 0\n var pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n var b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return _Buffer.alloc(0) }\n var psz = 0\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0\n var length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size)\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)]\n // Invalid character\n if (carry === 255) { return }\n var i = 0\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n var vch = _Buffer.allocUnsafe(zeroes + (size - it4))\n vch.fill(0x00, 0, zeroes)\n var j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n var buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nmodule.exports = base\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/base-x/src/index.js?");
298
-
299
- /***/ }),
300
-
301
291
  /***/ "../../node_modules/base64-js/index.js":
302
292
  /*!*********************************************!*\
303
293
  !*** ../../node_modules/base64-js/index.js ***!
@@ -308,36 +298,6 @@ eval("\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nex
308
298
 
309
299
  /***/ }),
310
300
 
311
- /***/ "../../node_modules/bchaddrjs-slp/src/bchaddr.js":
312
- /*!*******************************************************!*\
313
- !*** ../../node_modules/bchaddrjs-slp/src/bchaddr.js ***!
314
- \*******************************************************/
315
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
316
-
317
- eval("/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\")[\"Buffer\"];\n/***\n * @license\n * https://github.com/bitcoincashjs/bchaddr\n * Copyright (c) 2018 Emilio Almansi\n * Distributed under the MIT software license, see the accompanying\n * file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n */\n\nvar bs58check = __webpack_require__(/*! bs58check */ \"../../node_modules/bs58check/index.js\")\nvar cashaddr = __webpack_require__(/*! cashaddrjs-slp */ \"../../node_modules/cashaddrjs-slp/src/cashaddr.js\")\n\n/**\n * General purpose Bitcoin Cash address detection and translation.<br />\n * Supports all major Bitcoin Cash address formats.<br />\n * Currently:\n * <ul>\n * <li> Legacy format </li>\n * <li> Bitpay format </li>\n * <li> Cashaddr format </li>\n * </ul>\n * @module bchaddr\n */\n\n/**\n * @static\n * Supported Bitcoin Cash address formats.\n */\nvar Format = {}\nFormat.Legacy = 'legacy'\nFormat.Bitpay = 'bitpay'\nFormat.Cashaddr = 'cashaddr'\nFormat.Slpaddr = 'slpaddr'\n\n/**\n * @static\n * Supported networks.\n */\nvar Network = {}\nNetwork.Mainnet = 'mainnet'\nNetwork.Testnet = 'testnet'\n\n/**\n * @static\n * Supported address types.\n */\nvar Type = {}\nType.P2PKH = 'p2pkh'\nType.P2SH = 'p2sh'\n\n/**\n * Returns a boolean indicating whether the given input is a valid Bitcoin Cash address.\n * @static\n * @param {*} input - Any input to check for validity.\n * @returns {boolean}\n */\nfunction isValidAddress (input) {\n try {\n decodeAddress(input)\n return true\n } catch (error) {\n return false\n }\n}\n\n/**\n * Detects what is the given address' format.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @return {string}\n * @throws {InvalidAddressError}\n */\nfunction detectAddressFormat (address) {\n return decodeAddress(address).format\n}\n\n/**\n * Detects what is the given address' network.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @return {string}\n * @throws {InvalidAddressError}\n */\nfunction detectAddressNetwork (address) {\n return decodeAddress(address).network\n}\n\n/**\n * Detects what is the given address' type.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @return {string}\n * @throws {InvalidAddressError}\n */\nfunction detectAddressType (address) {\n return decodeAddress(address).type\n}\n\n/**\n * Translates the given address into legacy format.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @return {string}\n * @throws {InvalidAddressError}\n */\nfunction toLegacyAddress (address) {\n var decoded = decodeAddress(address)\n if (decoded.format === Format.Legacy) {\n return address\n }\n return encodeAsLegacy(decoded)\n}\n\n/**\n * Translates the given address into bitpay format.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @return {string}\n * @throws {InvalidAddressError}\n */\nfunction toBitpayAddress (address) {\n var decoded = decodeAddress(address)\n if (decoded.format === Format.Bitpay) {\n return address\n }\n return encodeAsBitpay(decoded)\n}\n\n/**\n * Translates the given address into cashaddr format.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @return {string}\n * @throws {InvalidAddressError}\n */\nfunction toCashAddress (address) {\n var decoded = decodeAddress(address)\n return encodeAsCashaddr(decoded)\n}\n\n/**\n * Translates the given address into cashaddr format.\n * @static\n * @param {string} address - A valid address in any format.\n * @return {string}\n * @throws {InvalidAddressError}\n */\nfunction toSlpAddress (address) {\n var decoded = decodeAddress(address)\n return encodeAsSlpaddr(decoded)\n}\n\n/**\n * Translates the given address into mainnet format.\n * @static\n * @param {string} address - A valid address in any format.\n * @return {string}\n * @throws {InvalidAddressError}\n */\nfunction toMainnetAddress (address) {\n var decoded = decodeAddress(address)\n return encodeAsMainnetaddr(decoded)\n}\n\n/**\n * Translates the given address into testnet format.\n * @static\n * @param {string} address - A valid address in any format.\n * @return {string}\n * @throws {InvalidAddressError}\n */\nfunction toTestnetAddress (address) {\n var decoded = decodeAddress(address)\n return encodeAsTestnetaddr(decoded)\n}\n\n/**\n * Translates the given address into regtest format.\n * @static\n * @param {string} address - A valid address in any format.\n * @return {string}\n * @throws {InvalidAddressError}\n */\nfunction toRegtestAddress (address) {\n var decoded = decodeAddress(address)\n return encodeAsRegtestaddr(decoded)\n}\n\n/**\n * Translates the given address into regtest format.\n * @static\n * @param {string} address - A valid address in any format.\n * @return {string}\n * @throws {InvalidAddressError}\n */\nfunction toSlpRegtestAddress (address) {\n var decoded = decodeAddress(address)\n return encodeAsSlpRegtestaddr(decoded)\n}\n\n/**\n * Version byte table for base58 formats.\n * @private\n */\nvar VERSION_BYTE = {}\nVERSION_BYTE[Format.Legacy] = {}\nVERSION_BYTE[Format.Legacy][Network.Mainnet] = {}\nVERSION_BYTE[Format.Legacy][Network.Mainnet][Type.P2PKH] = 0\nVERSION_BYTE[Format.Legacy][Network.Mainnet][Type.P2SH] = 5\nVERSION_BYTE[Format.Legacy][Network.Testnet] = {}\nVERSION_BYTE[Format.Legacy][Network.Testnet][Type.P2PKH] = 111\nVERSION_BYTE[Format.Legacy][Network.Testnet][Type.P2SH] = 196\nVERSION_BYTE[Format.Bitpay] = {}\nVERSION_BYTE[Format.Bitpay][Network.Mainnet] = {}\nVERSION_BYTE[Format.Bitpay][Network.Mainnet][Type.P2PKH] = 28\nVERSION_BYTE[Format.Bitpay][Network.Mainnet][Type.P2SH] = 40\nVERSION_BYTE[Format.Bitpay][Network.Testnet] = {}\nVERSION_BYTE[Format.Bitpay][Network.Testnet][Type.P2PKH] = 111\nVERSION_BYTE[Format.Bitpay][Network.Testnet][Type.P2SH] = 196\n\n/**\n * Decodes the given address into its constituting hash, format, network and type.\n * @private\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @return {object}\n * @throws {InvalidAddressError}\n */\nfunction decodeAddress (address) {\n try {\n return decodeBase58Address(address)\n } catch (error) {\n }\n try {\n return decodeCashAddress(address)\n } catch (error) {\n }\n try {\n return decodeSlpAddress(address)\n } catch (error) {\n }\n throw new InvalidAddressError()\n}\n\n/**\n * Length of a valid base58check encoding payload: 1 byte for\n * the version byte plus 20 bytes for a RIPEMD-160 hash.\n * @private\n */\nvar BASE_58_CHECK_PAYLOAD_LENGTH = 21\n\n/**\n * Attempts to decode the given address assuming it is a base58 address.\n * @private\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @return {object}\n * @throws {InvalidAddressError}\n */\nfunction decodeBase58Address (address) {\n try {\n var payload = bs58check.decode(address)\n if (payload.length !== BASE_58_CHECK_PAYLOAD_LENGTH) {\n throw new InvalidAddressError()\n }\n var versionByte = payload[0]\n var hash = Array.prototype.slice.call(payload, 1)\n switch (versionByte) {\n case VERSION_BYTE[Format.Legacy][Network.Mainnet][Type.P2PKH]:\n return {\n hash: hash,\n format: Format.Legacy,\n network: Network.Mainnet,\n type: Type.P2PKH\n }\n case VERSION_BYTE[Format.Legacy][Network.Mainnet][Type.P2SH]:\n return {\n hash: hash,\n format: Format.Legacy,\n network: Network.Mainnet,\n type: Type.P2SH\n }\n case VERSION_BYTE[Format.Legacy][Network.Testnet][Type.P2PKH]:\n return {\n hash: hash,\n format: Format.Legacy,\n network: Network.Testnet,\n type: Type.P2PKH\n }\n case VERSION_BYTE[Format.Legacy][Network.Testnet][Type.P2SH]:\n return {\n hash: hash,\n format: Format.Legacy,\n network: Network.Testnet,\n type: Type.P2SH\n }\n case VERSION_BYTE[Format.Bitpay][Network.Mainnet][Type.P2PKH]:\n return {\n hash: hash,\n format: Format.Bitpay,\n network: Network.Mainnet,\n type: Type.P2PKH\n }\n case VERSION_BYTE[Format.Bitpay][Network.Mainnet][Type.P2SH]:\n return {\n hash: hash,\n format: Format.Bitpay,\n network: Network.Mainnet,\n type: Type.P2SH\n }\n }\n } catch (error) {\n }\n throw new InvalidAddressError()\n}\n\n/**\n * Attempts to decode the given address assuming it is a cashaddr address.\n * @private\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @return {object}\n * @throws {InvalidAddressError}\n */\nfunction decodeCashAddress (address) {\n if (address.indexOf(':') !== -1) {\n try {\n return decodeCashAddressWithPrefix(address)\n } catch (error) {\n }\n } else {\n var prefixes = ['bitcoincash', 'bchtest', 'regtest', 'bchreg']\n for (var i = 0; i < prefixes.length; ++i) {\n try {\n var prefix = prefixes[i]\n return decodeCashAddressWithPrefix(prefix + ':' + address)\n } catch (error) {\n }\n }\n }\n throw new InvalidAddressError()\n}\n\n/**\n * Attempts to decode the given address assuming it is a cashaddr address with explicit prefix.\n * @private\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @return {object}\n * @throws {InvalidAddressError}\n */\nfunction decodeCashAddressWithPrefix (address) {\n try {\n var decoded = cashaddr.decode(address)\n var hash = Array.prototype.slice.call(decoded.hash, 0)\n var type = decoded.type === 'P2PKH' ? Type.P2PKH : Type.P2SH\n switch (decoded.prefix) {\n case 'bitcoincash':\n return {\n hash: hash,\n format: Format.Cashaddr,\n network: Network.Mainnet,\n type: type\n }\n case 'bchtest':\n case 'regtest':\n case 'bchreg':\n return {\n hash: hash,\n format: Format.Cashaddr,\n network: Network.Testnet,\n type: type\n }\n }\n } catch (error) {\n }\n throw new InvalidAddressError()\n}\n\n/**\n * Attempts to decode the given address assuming it is a slpaddr address.\n * @private\n * @param {string} address - A valid SLP address in any format.\n * @return {object}\n * @throws {InvalidAddressError}\n */\nfunction decodeSlpAddress (address) {\n if (address.indexOf(':') !== -1) {\n try {\n return decodeSlpAddressWithPrefix(address)\n } catch (error) {\n }\n } else {\n var prefixes = ['simpleledger', 'slptest', 'slpreg']\n for (var i = 0; i < prefixes.length; ++i) {\n try {\n var prefix = prefixes[i]\n return decodeSlpAddressWithPrefix(prefix + ':' + address)\n } catch (error) {\n }\n }\n }\n throw new InvalidAddressError()\n}\n\n/**\n * Attempts to decode the given address assuming it is a slpaddr address with explicit prefix.\n * @private\n * @param {string} address - A valid SLP address in any format.\n * @return {object}\n * @throws {InvalidAddressError}\n */\nfunction decodeSlpAddressWithPrefix (address) {\n try {\n var decoded = cashaddr.decode(address)\n var hash = Array.prototype.slice.call(decoded.hash, 0)\n var type = decoded.type === 'P2PKH' ? Type.P2PKH : Type.P2SH\n switch (decoded.prefix) {\n case 'simpleledger':\n return {\n hash: hash,\n format: Format.Slpaddr,\n network: Network.Mainnet,\n type: type\n }\n case 'slptest':\n case 'slpreg':\n return {\n hash: hash,\n format: Format.Slpaddr,\n network: Network.Testnet,\n type: type\n }\n }\n } catch (error) {\n }\n throw new InvalidAddressError()\n}\n\n/**\n * Encodes the given decoded address into legacy format.\n * @private\n * @param {object} decoded\n * @returns {string}\n */\nfunction encodeAsLegacy (decoded) {\n var versionByte = VERSION_BYTE[Format.Legacy][decoded.network][decoded.type]\n var buffer = Buffer.alloc(1 + decoded.hash.length)\n buffer[0] = versionByte\n buffer.set(decoded.hash, 1)\n return bs58check.encode(buffer)\n}\n\n/**\n * Encodes the given decoded address into bitpay format.\n * @private\n * @param {object} decoded\n * @returns {string}\n */\nfunction encodeAsBitpay (decoded) {\n var versionByte = VERSION_BYTE[Format.Bitpay][decoded.network][decoded.type]\n var buffer = Buffer.alloc(1 + decoded.hash.length)\n buffer[0] = versionByte\n buffer.set(decoded.hash, 1)\n return bs58check.encode(buffer)\n}\n\n/**\n * Encodes the given decoded address into cashaddr format.\n * @private\n * @param {object} decoded\n * @returns {string}\n */\nfunction encodeAsCashaddr (decoded) {\n var prefix = decoded.network === Network.Mainnet ? 'bitcoincash' : 'bchtest'\n var type = decoded.type === Type.P2PKH ? 'P2PKH' : 'P2SH'\n var hash = Uint8Array.from(decoded.hash)\n return cashaddr.encode(prefix, type, hash)\n}\n\n/**\n * Encodes the given decoded address into slpaddr format.\n * @private\n * @param {object} decoded\n * @returns {string}\n */\nfunction encodeAsSlpaddr (decoded) {\n var prefix = decoded.network === Network.Mainnet ? 'simpleledger' : 'slptest'\n var type = decoded.type === Type.P2PKH ? 'P2PKH' : 'P2SH'\n var hash = Uint8Array.from(decoded.hash)\n return cashaddr.encode(prefix, type, hash)\n}\n\n/**\n * Encodes the given decoded address into mainnet format.\n * @private\n * @param {object} decoded\n * @returns {string}\n */\nfunction encodeAsMainnetaddr (decoded) {\n var prefix = 'bitcoincash'\n var type = decoded.type === Type.P2PKH ? 'P2PKH' : 'P2SH'\n var hash = Uint8Array.from(decoded.hash)\n if (decoded.format === Format.Slpaddr) {\n prefix = 'simpleledger'\n }\n return cashaddr.encode(prefix, type, hash)\n}\n\n/**\n * Encodes the given decoded address into testnet format.\n * @private\n * @param {object} decoded\n * @returns {string}\n */\nfunction encodeAsTestnetaddr (decoded) {\n var prefix = 'bchtest'\n var type = decoded.type === Type.P2PKH ? 'P2PKH' : 'P2SH'\n var hash = Uint8Array.from(decoded.hash)\n if (decoded.format === Format.Slpaddr) {\n prefix = 'slptest'\n }\n return cashaddr.encode(prefix, type, hash)\n}\n\n/**\n * Encodes the given decoded address into regtest format.\n * @private\n * @param {object} decoded\n * @returns {string}\n */\nfunction encodeAsRegtestaddr (decoded) {\n var prefix = 'bchreg'\n var type = decoded.type === Type.P2PKH ? 'P2PKH' : 'P2SH'\n var hash = Uint8Array.from(decoded.hash)\n if (decoded.format === Format.Slpaddr) {\n prefix = 'slpreg'\n }\n return cashaddr.encode(prefix, type, hash)\n}\n\n/**\n * Encodes the given decoded address into regtest format.\n * @private\n * @param {object} decoded\n * @returns {string}\n */\nfunction encodeAsSlpRegtestaddr (decoded) {\n var prefix = 'slpreg'\n var type = decoded.type === Type.P2PKH ? 'P2PKH' : 'P2SH'\n var hash = Uint8Array.from(decoded.hash)\n return cashaddr.encode(prefix, type, hash)\n}\n\n/**\n * Returns a boolean indicating whether the address is in legacy format.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @returns {boolean}\n * @throws {InvalidAddressError}\n */\nfunction isLegacyAddress (address) {\n return detectAddressFormat(address) === Format.Legacy\n}\n\n/**\n * Returns a boolean indicating whether the address is in bitpay format.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @returns {boolean}\n * @throws {InvalidAddressError}\n */\nfunction isBitpayAddress (address) {\n return detectAddressFormat(address) === Format.Bitpay\n}\n\n/**\n * Returns a boolean indicating whether the address is in cashaddr format.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @returns {boolean}\n * @throws {InvalidAddressError}\n */\nfunction isCashAddress (address) {\n return detectAddressFormat(address) === Format.Cashaddr\n}\n\n/**\n * Returns a boolean indicating whether the address is in cashaddr format.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @returns {boolean}\n * @throws {InvalidAddressError}\n */\nfunction isSlpAddress (address) {\n return detectAddressFormat(address) === Format.Slpaddr\n}\n\n/**\n * Returns a boolean indicating whether the address is a mainnet address.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @returns {boolean}\n * @throws {InvalidAddressError}\n */\nfunction isMainnetAddress (address) {\n return detectAddressNetwork(address) === Network.Mainnet\n}\n\n/**\n * Returns a boolean indicating whether the address is a testnet address.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @returns {boolean}\n * @throws {InvalidAddressError}\n */\nfunction isTestnetAddress (address) {\n return detectAddressNetwork(address) === Network.Testnet\n}\n\n/**\n * Returns a boolean indicating whether the address is a p2pkh address.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @returns {boolean}\n * @throws {InvalidAddressError}\n */\nfunction isP2PKHAddress (address) {\n return detectAddressType(address) === Type.P2PKH\n}\n\n/**\n * Returns a boolean indicating whether the address is a p2sh address.\n * @static\n * @param {string} address - A valid Bitcoin Cash address in any format.\n * @returns {boolean}\n * @throws {InvalidAddressError}\n */\nfunction isP2SHAddress (address) {\n return detectAddressType(address) === Type.P2SH\n}\n\n/**\n * Error thrown when the address given as input is not a valid Bitcoin Cash address.\n * @constructor\n * InvalidAddressError\n */\nfunction InvalidAddressError () {\n var error = new Error()\n this.name = error.name = 'InvalidAddressError'\n this.message = error.message = 'Received an invalid Bitcoin Cash address as input.'\n this.stack = error.stack\n}\n\nInvalidAddressError.prototype = Object.create(Error.prototype)\n\nmodule.exports = {\n Format: Format,\n Network: Network,\n Type: Type,\n isValidAddress: isValidAddress,\n detectAddressFormat: detectAddressFormat,\n detectAddressNetwork: detectAddressNetwork,\n detectAddressType: detectAddressType,\n decodeAddress: decodeAddress,\n toLegacyAddress: toLegacyAddress,\n toBitpayAddress: toBitpayAddress,\n encodeAsCashaddr: encodeAsCashaddr,\n toCashAddress: toCashAddress,\n encodeAsSlpaddr: encodeAsSlpaddr,\n toSlpAddress: toSlpAddress,\n toMainnetAddress: toMainnetAddress,\n toTestnetAddress: toTestnetAddress,\n encodeAsMainnetaddr: encodeAsMainnetaddr,\n encodeAsTestnetaddr: encodeAsTestnetaddr,\n encodeAsRegtestaddr: encodeAsRegtestaddr,\n toRegtestAddress: toRegtestAddress,\n encodeAsSlpRegtestaddr: encodeAsSlpRegtestaddr,\n toSlpRegtestAddress: toSlpRegtestAddress,\n encodeAsLegacy: encodeAsLegacy,\n isLegacyAddress: isLegacyAddress,\n encodeAsBitpay: encodeAsBitpay,\n isBitpayAddress: isBitpayAddress,\n isCashAddress: isCashAddress,\n isSlpAddress: isSlpAddress,\n isMainnetAddress: isMainnetAddress,\n isTestnetAddress: isTestnetAddress,\n isP2PKHAddress: isP2PKHAddress,\n isP2SHAddress: isP2SHAddress,\n InvalidAddressError: InvalidAddressError\n}\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/bchaddrjs-slp/src/bchaddr.js?");
318
-
319
- /***/ }),
320
-
321
- /***/ "../../node_modules/big-integer/BigInteger.js":
322
- /*!****************************************************!*\
323
- !*** ../../node_modules/big-integer/BigInteger.js ***!
324
- \****************************************************/
325
- /***/ ((module, exports, __webpack_require__) => {
326
-
327
- eval("/* module decorator */ module = __webpack_require__.nmd(module);\nvar __WEBPACK_AMD_DEFINE_RESULT__;var bigInt = (function (undefined) {\r\n \"use strict\";\r\n\r\n var BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_INT = 9007199254740992,\r\n MAX_INT_ARR = smallToArray(MAX_INT),\r\n DEFAULT_ALPHABET = \"0123456789abcdefghijklmnopqrstuvwxyz\";\r\n\r\n var supportsNativeBigInt = typeof BigInt === \"function\";\r\n\r\n function Integer(v, radix, alphabet, caseSensitive) {\r\n if (typeof v === \"undefined\") return Integer[0];\r\n if (typeof radix !== \"undefined\") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);\r\n return parseValue(v);\r\n }\r\n\r\n function BigInteger(value, sign) {\r\n this.value = value;\r\n this.sign = sign;\r\n this.isSmall = false;\r\n }\r\n BigInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function SmallInteger(value) {\r\n this.value = value;\r\n this.sign = value < 0;\r\n this.isSmall = true;\r\n }\r\n SmallInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function NativeBigInt(value) {\r\n this.value = value;\r\n }\r\n NativeBigInt.prototype = Object.create(Integer.prototype);\r\n\r\n function isPrecise(n) {\r\n return -MAX_INT < n && n < MAX_INT;\r\n }\r\n\r\n function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes\r\n if (n < 1e7)\r\n return [n];\r\n if (n < 1e14)\r\n return [n % 1e7, Math.floor(n / 1e7)];\r\n return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];\r\n }\r\n\r\n function arrayToSmall(arr) { // If BASE changes this function may need to change\r\n trim(arr);\r\n var length = arr.length;\r\n if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {\r\n switch (length) {\r\n case 0: return 0;\r\n case 1: return arr[0];\r\n case 2: return arr[0] + arr[1] * BASE;\r\n default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;\r\n }\r\n }\r\n return arr;\r\n }\r\n\r\n function trim(v) {\r\n var i = v.length;\r\n while (v[--i] === 0);\r\n v.length = i + 1;\r\n }\r\n\r\n function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger\r\n var x = new Array(length);\r\n var i = -1;\r\n while (++i < length) {\r\n x[i] = 0;\r\n }\r\n return x;\r\n }\r\n\r\n function truncate(n) {\r\n if (n > 0) return Math.floor(n);\r\n return Math.ceil(n);\r\n }\r\n\r\n function add(a, b) { // assumes a and b are arrays with a.length >= b.length\r\n var l_a = a.length,\r\n l_b = b.length,\r\n r = new Array(l_a),\r\n carry = 0,\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l_b; i++) {\r\n sum = a[i] + b[i] + carry;\r\n carry = sum >= base ? 1 : 0;\r\n r[i] = sum - carry * base;\r\n }\r\n while (i < l_a) {\r\n sum = a[i] + carry;\r\n carry = sum === base ? 1 : 0;\r\n r[i++] = sum - carry * base;\r\n }\r\n if (carry > 0) r.push(carry);\r\n return r;\r\n }\r\n\r\n function addAny(a, b) {\r\n if (a.length >= b.length) return add(a, b);\r\n return add(b, a);\r\n }\r\n\r\n function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l; i++) {\r\n sum = a[i] - base + carry;\r\n carry = Math.floor(sum / base);\r\n r[i] = sum - carry * base;\r\n carry += 1;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall) {\r\n return new BigInteger(addSmall(a, Math.abs(b)), this.sign);\r\n }\r\n return new BigInteger(addAny(a, b), this.sign);\r\n };\r\n BigInteger.prototype.plus = BigInteger.prototype.add;\r\n\r\n SmallInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n if (isPrecise(a + b)) return new SmallInteger(a + b);\r\n b = smallToArray(Math.abs(b));\r\n }\r\n return new BigInteger(addSmall(b, Math.abs(a)), a < 0);\r\n };\r\n SmallInteger.prototype.plus = SmallInteger.prototype.add;\r\n\r\n NativeBigInt.prototype.add = function (v) {\r\n return new NativeBigInt(this.value + parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.plus = NativeBigInt.prototype.add;\r\n\r\n function subtract(a, b) { // assumes a and b are arrays with a >= b\r\n var a_l = a.length,\r\n b_l = b.length,\r\n r = new Array(a_l),\r\n borrow = 0,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < b_l; i++) {\r\n difference = a[i] - borrow - b[i];\r\n if (difference < 0) {\r\n difference += base;\r\n borrow = 1;\r\n } else borrow = 0;\r\n r[i] = difference;\r\n }\r\n for (i = b_l; i < a_l; i++) {\r\n difference = a[i] - borrow;\r\n if (difference < 0) difference += base;\r\n else {\r\n r[i++] = difference;\r\n break;\r\n }\r\n r[i] = difference;\r\n }\r\n for (; i < a_l; i++) {\r\n r[i] = a[i];\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function subtractAny(a, b, sign) {\r\n var value;\r\n if (compareAbs(a, b) >= 0) {\r\n value = subtract(a, b);\r\n } else {\r\n value = subtract(b, a);\r\n sign = !sign;\r\n }\r\n value = arrayToSmall(value);\r\n if (typeof value === \"number\") {\r\n if (sign) value = -value;\r\n return new SmallInteger(value);\r\n }\r\n return new BigInteger(value, sign);\r\n }\r\n\r\n function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n carry = -b,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < l; i++) {\r\n difference = a[i] + carry;\r\n carry = Math.floor(difference / base);\r\n difference %= base;\r\n r[i] = difference < 0 ? difference + base : difference;\r\n }\r\n r = arrayToSmall(r);\r\n if (typeof r === \"number\") {\r\n if (sign) r = -r;\r\n return new SmallInteger(r);\r\n } return new BigInteger(r, sign);\r\n }\r\n\r\n BigInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall)\r\n return subtractSmall(a, Math.abs(b), this.sign);\r\n return subtractAny(a, b, this.sign);\r\n };\r\n BigInteger.prototype.minus = BigInteger.prototype.subtract;\r\n\r\n SmallInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n return new SmallInteger(a - b);\r\n }\r\n return subtractSmall(b, Math.abs(a), a >= 0);\r\n };\r\n SmallInteger.prototype.minus = SmallInteger.prototype.subtract;\r\n\r\n NativeBigInt.prototype.subtract = function (v) {\r\n return new NativeBigInt(this.value - parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;\r\n\r\n BigInteger.prototype.negate = function () {\r\n return new BigInteger(this.value, !this.sign);\r\n };\r\n SmallInteger.prototype.negate = function () {\r\n var sign = this.sign;\r\n var small = new SmallInteger(-this.value);\r\n small.sign = !sign;\r\n return small;\r\n };\r\n NativeBigInt.prototype.negate = function () {\r\n return new NativeBigInt(-this.value);\r\n }\r\n\r\n BigInteger.prototype.abs = function () {\r\n return new BigInteger(this.value, false);\r\n };\r\n SmallInteger.prototype.abs = function () {\r\n return new SmallInteger(Math.abs(this.value));\r\n };\r\n NativeBigInt.prototype.abs = function () {\r\n return new NativeBigInt(this.value >= 0 ? this.value : -this.value);\r\n }\r\n\r\n\r\n function multiplyLong(a, b) {\r\n var a_l = a.length,\r\n b_l = b.length,\r\n l = a_l + b_l,\r\n r = createArray(l),\r\n base = BASE,\r\n product, carry, i, a_i, b_j;\r\n for (i = 0; i < a_l; ++i) {\r\n a_i = a[i];\r\n for (var j = 0; j < b_l; ++j) {\r\n b_j = b[j];\r\n product = a_i * b_j + r[i + j];\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n r[i + j + 1] += carry;\r\n }\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n carry = 0,\r\n product, i;\r\n for (i = 0; i < l; i++) {\r\n product = a[i] * b + carry;\r\n carry = Math.floor(product / base);\r\n r[i] = product - carry * base;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n function shiftLeft(x, n) {\r\n var r = [];\r\n while (n-- > 0) r.push(0);\r\n return r.concat(x);\r\n }\r\n\r\n function multiplyKaratsuba(x, y) {\r\n var n = Math.max(x.length, y.length);\r\n\r\n if (n <= 30) return multiplyLong(x, y);\r\n n = Math.ceil(n / 2);\r\n\r\n var b = x.slice(n),\r\n a = x.slice(0, n),\r\n d = y.slice(n),\r\n c = y.slice(0, n);\r\n\r\n var ac = multiplyKaratsuba(a, c),\r\n bd = multiplyKaratsuba(b, d),\r\n abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));\r\n\r\n var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));\r\n trim(product);\r\n return product;\r\n }\r\n\r\n // The following function is derived from a surface fit of a graph plotting the performance difference\r\n // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.\r\n function useKaratsuba(l1, l2) {\r\n return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;\r\n }\r\n\r\n BigInteger.prototype.multiply = function (v) {\r\n var n = parseValue(v),\r\n a = this.value, b = n.value,\r\n sign = this.sign !== n.sign,\r\n abs;\r\n if (n.isSmall) {\r\n if (b === 0) return Integer[0];\r\n if (b === 1) return this;\r\n if (b === -1) return this.negate();\r\n abs = Math.abs(b);\r\n if (abs < BASE) {\r\n return new BigInteger(multiplySmall(a, abs), sign);\r\n }\r\n b = smallToArray(abs);\r\n }\r\n if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes\r\n return new BigInteger(multiplyKaratsuba(a, b), sign);\r\n return new BigInteger(multiplyLong(a, b), sign);\r\n };\r\n\r\n BigInteger.prototype.times = BigInteger.prototype.multiply;\r\n\r\n function multiplySmallAndArray(a, b, sign) { // a >= 0\r\n if (a < BASE) {\r\n return new BigInteger(multiplySmall(b, a), sign);\r\n }\r\n return new BigInteger(multiplyLong(b, smallToArray(a)), sign);\r\n }\r\n SmallInteger.prototype._multiplyBySmall = function (a) {\r\n if (isPrecise(a.value * this.value)) {\r\n return new SmallInteger(a.value * this.value);\r\n }\r\n return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);\r\n };\r\n BigInteger.prototype._multiplyBySmall = function (a) {\r\n if (a.value === 0) return Integer[0];\r\n if (a.value === 1) return this;\r\n if (a.value === -1) return this.negate();\r\n return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);\r\n };\r\n SmallInteger.prototype.multiply = function (v) {\r\n return parseValue(v)._multiplyBySmall(this);\r\n };\r\n SmallInteger.prototype.times = SmallInteger.prototype.multiply;\r\n\r\n NativeBigInt.prototype.multiply = function (v) {\r\n return new NativeBigInt(this.value * parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;\r\n\r\n function square(a) {\r\n //console.assert(2 * BASE * BASE < MAX_INT);\r\n var l = a.length,\r\n r = createArray(l + l),\r\n base = BASE,\r\n product, carry, i, a_i, a_j;\r\n for (i = 0; i < l; i++) {\r\n a_i = a[i];\r\n carry = 0 - a_i * a_i;\r\n for (var j = i; j < l; j++) {\r\n a_j = a[j];\r\n product = 2 * (a_i * a_j) + r[i + j] + carry;\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n }\r\n r[i + l] = carry;\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.square = function () {\r\n return new BigInteger(square(this.value), false);\r\n };\r\n\r\n SmallInteger.prototype.square = function () {\r\n var value = this.value * this.value;\r\n if (isPrecise(value)) return new SmallInteger(value);\r\n return new BigInteger(square(smallToArray(Math.abs(this.value))), false);\r\n };\r\n\r\n NativeBigInt.prototype.square = function (v) {\r\n return new NativeBigInt(this.value * this.value);\r\n }\r\n\r\n function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n base = BASE,\r\n result = createArray(b.length),\r\n divisorMostSignificantDigit = b[b_l - 1],\r\n // normalization\r\n lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),\r\n remainder = multiplySmall(a, lambda),\r\n divisor = multiplySmall(b, lambda),\r\n quotientDigit, shift, carry, borrow, i, l, q;\r\n if (remainder.length <= a_l) remainder.push(0);\r\n divisor.push(0);\r\n divisorMostSignificantDigit = divisor[b_l - 1];\r\n for (shift = a_l - b_l; shift >= 0; shift--) {\r\n quotientDigit = base - 1;\r\n if (remainder[shift + b_l] !== divisorMostSignificantDigit) {\r\n quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);\r\n }\r\n // quotientDigit <= base - 1\r\n carry = 0;\r\n borrow = 0;\r\n l = divisor.length;\r\n for (i = 0; i < l; i++) {\r\n carry += quotientDigit * divisor[i];\r\n q = Math.floor(carry / base);\r\n borrow += remainder[shift + i] - (carry - q * base);\r\n carry = q;\r\n if (borrow < 0) {\r\n remainder[shift + i] = borrow + base;\r\n borrow = -1;\r\n } else {\r\n remainder[shift + i] = borrow;\r\n borrow = 0;\r\n }\r\n }\r\n while (borrow !== 0) {\r\n quotientDigit -= 1;\r\n carry = 0;\r\n for (i = 0; i < l; i++) {\r\n carry += remainder[shift + i] - base + divisor[i];\r\n if (carry < 0) {\r\n remainder[shift + i] = carry + base;\r\n carry = 0;\r\n } else {\r\n remainder[shift + i] = carry;\r\n carry = 1;\r\n }\r\n }\r\n borrow += carry;\r\n }\r\n result[shift] = quotientDigit;\r\n }\r\n // denormalization\r\n remainder = divModSmall(remainder, lambda)[0];\r\n return [arrayToSmall(result), arrayToSmall(remainder)];\r\n }\r\n\r\n function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/\r\n // Performs faster than divMod1 on larger input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n result = [],\r\n part = [],\r\n base = BASE,\r\n guess, xlen, highx, highy, check;\r\n while (a_l) {\r\n part.unshift(a[--a_l]);\r\n trim(part);\r\n if (compareAbs(part, b) < 0) {\r\n result.push(0);\r\n continue;\r\n }\r\n xlen = part.length;\r\n highx = part[xlen - 1] * base + part[xlen - 2];\r\n highy = b[b_l - 1] * base + b[b_l - 2];\r\n if (xlen > b_l) {\r\n highx = (highx + 1) * base;\r\n }\r\n guess = Math.ceil(highx / highy);\r\n do {\r\n check = multiplySmall(b, guess);\r\n if (compareAbs(check, part) <= 0) break;\r\n guess--;\r\n } while (guess);\r\n result.push(guess);\r\n part = subtract(part, check);\r\n }\r\n result.reverse();\r\n return [arrayToSmall(result), arrayToSmall(part)];\r\n }\r\n\r\n function divModSmall(value, lambda) {\r\n var length = value.length,\r\n quotient = createArray(length),\r\n base = BASE,\r\n i, q, remainder, divisor;\r\n remainder = 0;\r\n for (i = length - 1; i >= 0; --i) {\r\n divisor = remainder * base + value[i];\r\n q = truncate(divisor / lambda);\r\n remainder = divisor - q * lambda;\r\n quotient[i] = q | 0;\r\n }\r\n return [quotient, remainder | 0];\r\n }\r\n\r\n function divModAny(self, v) {\r\n var value, n = parseValue(v);\r\n if (supportsNativeBigInt) {\r\n return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];\r\n }\r\n var a = self.value, b = n.value;\r\n var quotient;\r\n if (b === 0) throw new Error(\"Cannot divide by zero\");\r\n if (self.isSmall) {\r\n if (n.isSmall) {\r\n return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];\r\n }\r\n return [Integer[0], self];\r\n }\r\n if (n.isSmall) {\r\n if (b === 1) return [self, Integer[0]];\r\n if (b == -1) return [self.negate(), Integer[0]];\r\n var abs = Math.abs(b);\r\n if (abs < BASE) {\r\n value = divModSmall(a, abs);\r\n quotient = arrayToSmall(value[0]);\r\n var remainder = value[1];\r\n if (self.sign) remainder = -remainder;\r\n if (typeof quotient === \"number\") {\r\n if (self.sign !== n.sign) quotient = -quotient;\r\n return [new SmallInteger(quotient), new SmallInteger(remainder)];\r\n }\r\n return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];\r\n }\r\n b = smallToArray(abs);\r\n }\r\n var comparison = compareAbs(a, b);\r\n if (comparison === -1) return [Integer[0], self];\r\n if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];\r\n\r\n // divMod1 is faster on smaller input sizes\r\n if (a.length + b.length <= 200)\r\n value = divMod1(a, b);\r\n else value = divMod2(a, b);\r\n\r\n quotient = value[0];\r\n var qSign = self.sign !== n.sign,\r\n mod = value[1],\r\n mSign = self.sign;\r\n if (typeof quotient === \"number\") {\r\n if (qSign) quotient = -quotient;\r\n quotient = new SmallInteger(quotient);\r\n } else quotient = new BigInteger(quotient, qSign);\r\n if (typeof mod === \"number\") {\r\n if (mSign) mod = -mod;\r\n mod = new SmallInteger(mod);\r\n } else mod = new BigInteger(mod, mSign);\r\n return [quotient, mod];\r\n }\r\n\r\n BigInteger.prototype.divmod = function (v) {\r\n var result = divModAny(this, v);\r\n return {\r\n quotient: result[0],\r\n remainder: result[1]\r\n };\r\n };\r\n NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;\r\n\r\n\r\n BigInteger.prototype.divide = function (v) {\r\n return divModAny(this, v)[0];\r\n };\r\n NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {\r\n return new NativeBigInt(this.value / parseValue(v).value);\r\n };\r\n SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;\r\n\r\n BigInteger.prototype.mod = function (v) {\r\n return divModAny(this, v)[1];\r\n };\r\n NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {\r\n return new NativeBigInt(this.value % parseValue(v).value);\r\n };\r\n SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;\r\n\r\n BigInteger.prototype.pow = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value,\r\n value, x, y;\r\n if (b === 0) return Integer[1];\r\n if (a === 0) return Integer[0];\r\n if (a === 1) return Integer[1];\r\n if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.sign) {\r\n return Integer[0];\r\n }\r\n if (!n.isSmall) throw new Error(\"The exponent \" + n.toString() + \" is too large.\");\r\n if (this.isSmall) {\r\n if (isPrecise(value = Math.pow(a, b)))\r\n return new SmallInteger(truncate(value));\r\n }\r\n x = this;\r\n y = Integer[1];\r\n while (true) {\r\n if (b & 1 === 1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === 0) break;\r\n b /= 2;\r\n x = x.square();\r\n }\r\n return y;\r\n };\r\n SmallInteger.prototype.pow = BigInteger.prototype.pow;\r\n\r\n NativeBigInt.prototype.pow = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value, b = n.value;\r\n var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);\r\n if (b === _0) return Integer[1];\r\n if (a === _0) return Integer[0];\r\n if (a === _1) return Integer[1];\r\n if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.isNegative()) return new NativeBigInt(_0);\r\n var x = this;\r\n var y = Integer[1];\r\n while (true) {\r\n if ((b & _1) === _1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === _0) break;\r\n b /= _2;\r\n x = x.square();\r\n }\r\n return y;\r\n }\r\n\r\n BigInteger.prototype.modPow = function (exp, mod) {\r\n exp = parseValue(exp);\r\n mod = parseValue(mod);\r\n if (mod.isZero()) throw new Error(\"Cannot take modPow with modulus 0\");\r\n var r = Integer[1],\r\n base = this.mod(mod);\r\n if (exp.isNegative()) {\r\n exp = exp.multiply(Integer[-1]);\r\n base = base.modInv(mod);\r\n }\r\n while (exp.isPositive()) {\r\n if (base.isZero()) return Integer[0];\r\n if (exp.isOdd()) r = r.multiply(base).mod(mod);\r\n exp = exp.divide(2);\r\n base = base.square().mod(mod);\r\n }\r\n return r;\r\n };\r\n NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;\r\n\r\n function compareAbs(a, b) {\r\n if (a.length !== b.length) {\r\n return a.length > b.length ? 1 : -1;\r\n }\r\n for (var i = a.length - 1; i >= 0; i--) {\r\n if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;\r\n }\r\n return 0;\r\n }\r\n\r\n BigInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) return 1;\r\n return compareAbs(a, b);\r\n };\r\n SmallInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = Math.abs(this.value),\r\n b = n.value;\r\n if (n.isSmall) {\r\n b = Math.abs(b);\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n return -1;\r\n };\r\n NativeBigInt.prototype.compareAbs = function (v) {\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n a = a >= 0 ? a : -a;\r\n b = b >= 0 ? b : -b;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n\r\n BigInteger.prototype.compare = function (v) {\r\n // See discussion about comparison with Infinity:\r\n // https://github.com/peterolson/BigInteger.js/issues/61\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (this.sign !== n.sign) {\r\n return n.sign ? 1 : -1;\r\n }\r\n if (n.isSmall) {\r\n return this.sign ? -1 : 1;\r\n }\r\n return compareAbs(a, b) * (this.sign ? -1 : 1);\r\n };\r\n BigInteger.prototype.compareTo = BigInteger.prototype.compare;\r\n\r\n SmallInteger.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) {\r\n return a == b ? 0 : a > b ? 1 : -1;\r\n }\r\n if (a < 0 !== n.sign) {\r\n return a < 0 ? -1 : 1;\r\n }\r\n return a < 0 ? 1 : -1;\r\n };\r\n SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;\r\n\r\n NativeBigInt.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;\r\n\r\n BigInteger.prototype.equals = function (v) {\r\n return this.compare(v) === 0;\r\n };\r\n NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;\r\n\r\n BigInteger.prototype.notEquals = function (v) {\r\n return this.compare(v) !== 0;\r\n };\r\n NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;\r\n\r\n BigInteger.prototype.greater = function (v) {\r\n return this.compare(v) > 0;\r\n };\r\n NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;\r\n\r\n BigInteger.prototype.lesser = function (v) {\r\n return this.compare(v) < 0;\r\n };\r\n NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;\r\n\r\n BigInteger.prototype.greaterOrEquals = function (v) {\r\n return this.compare(v) >= 0;\r\n };\r\n NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;\r\n\r\n BigInteger.prototype.lesserOrEquals = function (v) {\r\n return this.compare(v) <= 0;\r\n };\r\n NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;\r\n\r\n BigInteger.prototype.isEven = function () {\r\n return (this.value[0] & 1) === 0;\r\n };\r\n SmallInteger.prototype.isEven = function () {\r\n return (this.value & 1) === 0;\r\n };\r\n NativeBigInt.prototype.isEven = function () {\r\n return (this.value & BigInt(1)) === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isOdd = function () {\r\n return (this.value[0] & 1) === 1;\r\n };\r\n SmallInteger.prototype.isOdd = function () {\r\n return (this.value & 1) === 1;\r\n };\r\n NativeBigInt.prototype.isOdd = function () {\r\n return (this.value & BigInt(1)) === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isPositive = function () {\r\n return !this.sign;\r\n };\r\n SmallInteger.prototype.isPositive = function () {\r\n return this.value > 0;\r\n };\r\n NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;\r\n\r\n BigInteger.prototype.isNegative = function () {\r\n return this.sign;\r\n };\r\n SmallInteger.prototype.isNegative = function () {\r\n return this.value < 0;\r\n };\r\n NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;\r\n\r\n BigInteger.prototype.isUnit = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isUnit = function () {\r\n return Math.abs(this.value) === 1;\r\n };\r\n NativeBigInt.prototype.isUnit = function () {\r\n return this.abs().value === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isZero = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isZero = function () {\r\n return this.value === 0;\r\n };\r\n NativeBigInt.prototype.isZero = function () {\r\n return this.value === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isDivisibleBy = function (v) {\r\n var n = parseValue(v);\r\n if (n.isZero()) return false;\r\n if (n.isUnit()) return true;\r\n if (n.compareAbs(2) === 0) return this.isEven();\r\n return this.mod(n).isZero();\r\n };\r\n NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;\r\n\r\n function isBasicPrime(v) {\r\n var n = v.abs();\r\n if (n.isUnit()) return false;\r\n if (n.equals(2) || n.equals(3) || n.equals(5)) return true;\r\n if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;\r\n if (n.lesser(49)) return true;\r\n // we don't know if it's prime: let the other functions figure it out\r\n }\r\n\r\n function millerRabinTest(n, a) {\r\n var nPrev = n.prev(),\r\n b = nPrev,\r\n r = 0,\r\n d, t, i, x;\r\n while (b.isEven()) b = b.divide(2), r++;\r\n next: for (i = 0; i < a.length; i++) {\r\n if (n.lesser(a[i])) continue;\r\n x = bigInt(a[i]).modPow(b, n);\r\n if (x.isUnit() || x.equals(nPrev)) continue;\r\n for (d = r - 1; d != 0; d--) {\r\n x = x.square().mod(n);\r\n if (x.isUnit()) return false;\r\n if (x.equals(nPrev)) continue next;\r\n }\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n // Set \"strict\" to true to force GRH-supported lower bound of 2*log(N)^2\r\n BigInteger.prototype.isPrime = function (strict) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var bits = n.bitLength();\r\n if (bits <= 64)\r\n return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);\r\n var logN = Math.log(2) * bits.toJSNumber();\r\n var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt(i + 2));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;\r\n\r\n BigInteger.prototype.isProbablePrime = function (iterations, rng) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var t = iterations === undefined ? 5 : iterations;\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt.randBetween(2, n.minus(2), rng));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;\r\n\r\n BigInteger.prototype.modInv = function (n) {\r\n var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;\r\n while (!newR.isZero()) {\r\n q = r.divide(newR);\r\n lastT = t;\r\n lastR = r;\r\n t = newT;\r\n r = newR;\r\n newT = lastT.subtract(q.multiply(newT));\r\n newR = lastR.subtract(q.multiply(newR));\r\n }\r\n if (!r.isUnit()) throw new Error(this.toString() + \" and \" + n.toString() + \" are not co-prime\");\r\n if (t.compare(0) === -1) {\r\n t = t.add(n);\r\n }\r\n if (this.isNegative()) {\r\n return t.negate();\r\n }\r\n return t;\r\n };\r\n\r\n NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;\r\n\r\n BigInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return subtractSmall(value, 1, this.sign);\r\n }\r\n return new BigInteger(addSmall(value, 1), this.sign);\r\n };\r\n SmallInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (value + 1 < MAX_INT) return new SmallInteger(value + 1);\r\n return new BigInteger(MAX_INT_ARR, false);\r\n };\r\n NativeBigInt.prototype.next = function () {\r\n return new NativeBigInt(this.value + BigInt(1));\r\n }\r\n\r\n BigInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return new BigInteger(addSmall(value, 1), true);\r\n }\r\n return subtractSmall(value, 1, this.sign);\r\n };\r\n SmallInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);\r\n return new BigInteger(MAX_INT_ARR, true);\r\n };\r\n NativeBigInt.prototype.prev = function () {\r\n return new NativeBigInt(this.value - BigInt(1));\r\n }\r\n\r\n var powersOfTwo = [1];\r\n while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);\r\n var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];\r\n\r\n function shift_isSmall(n) {\r\n return Math.abs(n) <= BASE;\r\n }\r\n\r\n BigInteger.prototype.shiftLeft = function (v) {\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + \" is too large for shifting.\");\r\n }\r\n if (n < 0) return this.shiftRight(-n);\r\n var result = this;\r\n if (result.isZero()) return result;\r\n while (n >= powers2Length) {\r\n result = result.multiply(highestPower2);\r\n n -= powers2Length - 1;\r\n }\r\n return result.multiply(powersOfTwo[n]);\r\n };\r\n NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;\r\n\r\n BigInteger.prototype.shiftRight = function (v) {\r\n var remQuo;\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + \" is too large for shifting.\");\r\n }\r\n if (n < 0) return this.shiftLeft(-n);\r\n var result = this;\r\n while (n >= powers2Length) {\r\n if (result.isZero() || (result.isNegative() && result.isUnit())) return result;\r\n remQuo = divModAny(result, highestPower2);\r\n result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n n -= powers2Length - 1;\r\n }\r\n remQuo = divModAny(result, powersOfTwo[n]);\r\n return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n };\r\n NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;\r\n\r\n function bitwise(x, y, fn) {\r\n y = parseValue(y);\r\n var xSign = x.isNegative(), ySign = y.isNegative();\r\n var xRem = xSign ? x.not() : x,\r\n yRem = ySign ? y.not() : y;\r\n var xDigit = 0, yDigit = 0;\r\n var xDivMod = null, yDivMod = null;\r\n var result = [];\r\n while (!xRem.isZero() || !yRem.isZero()) {\r\n xDivMod = divModAny(xRem, highestPower2);\r\n xDigit = xDivMod[1].toJSNumber();\r\n if (xSign) {\r\n xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers\r\n }\r\n\r\n yDivMod = divModAny(yRem, highestPower2);\r\n yDigit = yDivMod[1].toJSNumber();\r\n if (ySign) {\r\n yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers\r\n }\r\n\r\n xRem = xDivMod[0];\r\n yRem = yDivMod[0];\r\n result.push(fn(xDigit, yDigit));\r\n }\r\n var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);\r\n for (var i = result.length - 1; i >= 0; i -= 1) {\r\n sum = sum.multiply(highestPower2).add(bigInt(result[i]));\r\n }\r\n return sum;\r\n }\r\n\r\n BigInteger.prototype.not = function () {\r\n return this.negate().prev();\r\n };\r\n NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;\r\n\r\n BigInteger.prototype.and = function (n) {\r\n return bitwise(this, n, function (a, b) { return a & b; });\r\n };\r\n NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;\r\n\r\n BigInteger.prototype.or = function (n) {\r\n return bitwise(this, n, function (a, b) { return a | b; });\r\n };\r\n NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;\r\n\r\n BigInteger.prototype.xor = function (n) {\r\n return bitwise(this, n, function (a, b) { return a ^ b; });\r\n };\r\n NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;\r\n\r\n var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;\r\n function roughLOB(n) { // get lowestOneBit (rough)\r\n // SmallInteger: return Min(lowestOneBit(n), 1 << 30)\r\n // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]\r\n var v = n.value,\r\n x = typeof v === \"number\" ? v | LOBMASK_I :\r\n typeof v === \"bigint\" ? v | BigInt(LOBMASK_I) :\r\n v[0] + v[1] * BASE | LOBMASK_BI;\r\n return x & -x;\r\n }\r\n\r\n function integerLogarithm(value, base) {\r\n if (base.compareTo(value) <= 0) {\r\n var tmp = integerLogarithm(value, base.square(base));\r\n var p = tmp.p;\r\n var e = tmp.e;\r\n var t = p.multiply(base);\r\n return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };\r\n }\r\n return { p: bigInt(1), e: 0 };\r\n }\r\n\r\n BigInteger.prototype.bitLength = function () {\r\n var n = this;\r\n if (n.compareTo(bigInt(0)) < 0) {\r\n n = n.negate().subtract(bigInt(1));\r\n }\r\n if (n.compareTo(bigInt(0)) === 0) {\r\n return bigInt(0);\r\n }\r\n return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));\r\n }\r\n NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;\r\n\r\n function max(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.greater(b) ? a : b;\r\n }\r\n function min(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.lesser(b) ? a : b;\r\n }\r\n function gcd(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n if (a.equals(b)) return a;\r\n if (a.isZero()) return b;\r\n if (b.isZero()) return a;\r\n var c = Integer[1], d, t;\r\n while (a.isEven() && b.isEven()) {\r\n d = min(roughLOB(a), roughLOB(b));\r\n a = a.divide(d);\r\n b = b.divide(d);\r\n c = c.multiply(d);\r\n }\r\n while (a.isEven()) {\r\n a = a.divide(roughLOB(a));\r\n }\r\n do {\r\n while (b.isEven()) {\r\n b = b.divide(roughLOB(b));\r\n }\r\n if (a.greater(b)) {\r\n t = b; b = a; a = t;\r\n }\r\n b = b.subtract(a);\r\n } while (!b.isZero());\r\n return c.isUnit() ? a : a.multiply(c);\r\n }\r\n function lcm(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n return a.divide(gcd(a, b)).multiply(b);\r\n }\r\n function randBetween(a, b, rng) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n var usedRNG = rng || Math.random;\r\n var low = min(a, b), high = max(a, b);\r\n var range = high.subtract(low).add(1);\r\n if (range.isSmall) return low.add(Math.floor(usedRNG() * range));\r\n var digits = toBase(range, BASE).value;\r\n var result = [], restricted = true;\r\n for (var i = 0; i < digits.length; i++) {\r\n var top = restricted ? digits[i] : BASE;\r\n var digit = truncate(usedRNG() * top);\r\n result.push(digit);\r\n if (digit < top) restricted = false;\r\n }\r\n return low.add(Integer.fromArray(result, BASE, false));\r\n }\r\n\r\n var parseBase = function (text, base, alphabet, caseSensitive) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n text = String(text);\r\n if (!caseSensitive) {\r\n text = text.toLowerCase();\r\n alphabet = alphabet.toLowerCase();\r\n }\r\n var length = text.length;\r\n var i;\r\n var absBase = Math.abs(base);\r\n var alphabetValues = {};\r\n for (i = 0; i < alphabet.length; i++) {\r\n alphabetValues[alphabet[i]] = i;\r\n }\r\n for (i = 0; i < length; i++) {\r\n var c = text[i];\r\n if (c === \"-\") continue;\r\n if (c in alphabetValues) {\r\n if (alphabetValues[c] >= absBase) {\r\n if (c === \"1\" && absBase === 1) continue;\r\n throw new Error(c + \" is not a valid digit in base \" + base + \".\");\r\n }\r\n }\r\n }\r\n base = parseValue(base);\r\n var digits = [];\r\n var isNegative = text[0] === \"-\";\r\n for (i = isNegative ? 1 : 0; i < text.length; i++) {\r\n var c = text[i];\r\n if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));\r\n else if (c === \"<\") {\r\n var start = i;\r\n do { i++; } while (text[i] !== \">\" && i < text.length);\r\n digits.push(parseValue(text.slice(start + 1, i)));\r\n }\r\n else throw new Error(c + \" is not a valid character\");\r\n }\r\n return parseBaseFromArray(digits, base, isNegative);\r\n };\r\n\r\n function parseBaseFromArray(digits, base, isNegative) {\r\n var val = Integer[0], pow = Integer[1], i;\r\n for (i = digits.length - 1; i >= 0; i--) {\r\n val = val.add(digits[i].times(pow));\r\n pow = pow.times(base);\r\n }\r\n return isNegative ? val.negate() : val;\r\n }\r\n\r\n function stringify(digit, alphabet) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n if (digit < alphabet.length) {\r\n return alphabet[digit];\r\n }\r\n return \"<\" + digit + \">\";\r\n }\r\n\r\n function toBase(n, base) {\r\n base = bigInt(base);\r\n if (base.isZero()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n throw new Error(\"Cannot convert nonzero numbers to base 0.\");\r\n }\r\n if (base.equals(-1)) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n if (n.isNegative())\r\n return {\r\n value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))\r\n .map(Array.prototype.valueOf, [1, 0])\r\n ),\r\n isNegative: false\r\n };\r\n\r\n var arr = Array.apply(null, Array(n.toJSNumber() - 1))\r\n .map(Array.prototype.valueOf, [0, 1]);\r\n arr.unshift([1]);\r\n return {\r\n value: [].concat.apply([], arr),\r\n isNegative: false\r\n };\r\n }\r\n\r\n var neg = false;\r\n if (n.isNegative() && base.isPositive()) {\r\n neg = true;\r\n n = n.abs();\r\n }\r\n if (base.isUnit()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n\r\n return {\r\n value: Array.apply(null, Array(n.toJSNumber()))\r\n .map(Number.prototype.valueOf, 1),\r\n isNegative: neg\r\n };\r\n }\r\n var out = [];\r\n var left = n, divmod;\r\n while (left.isNegative() || left.compareAbs(base) >= 0) {\r\n divmod = left.divmod(base);\r\n left = divmod.quotient;\r\n var digit = divmod.remainder;\r\n if (digit.isNegative()) {\r\n digit = base.minus(digit).abs();\r\n left = left.next();\r\n }\r\n out.push(digit.toJSNumber());\r\n }\r\n out.push(left.toJSNumber());\r\n return { value: out.reverse(), isNegative: neg };\r\n }\r\n\r\n function toBaseString(n, base, alphabet) {\r\n var arr = toBase(n, base);\r\n return (arr.isNegative ? \"-\" : \"\") + arr.value.map(function (x) {\r\n return stringify(x, alphabet);\r\n }).join('');\r\n }\r\n\r\n BigInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n SmallInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n NativeBigInt.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n BigInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix !== 10) return toBaseString(this, radix, alphabet);\r\n var v = this.value, l = v.length, str = String(v[--l]), zeros = \"0000000\", digit;\r\n while (--l >= 0) {\r\n digit = String(v[l]);\r\n str += zeros.slice(digit.length) + digit;\r\n }\r\n var sign = this.sign ? \"-\" : \"\";\r\n return sign + str;\r\n };\r\n\r\n SmallInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix != 10) return toBaseString(this, radix, alphabet);\r\n return String(this.value);\r\n };\r\n\r\n NativeBigInt.prototype.toString = SmallInteger.prototype.toString;\r\n\r\n NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }\r\n\r\n BigInteger.prototype.valueOf = function () {\r\n return parseInt(this.toString(), 10);\r\n };\r\n BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;\r\n\r\n SmallInteger.prototype.valueOf = function () {\r\n return this.value;\r\n };\r\n SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;\r\n NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {\r\n return parseInt(this.toString(), 10);\r\n }\r\n\r\n function parseStringValue(v) {\r\n if (isPrecise(+v)) {\r\n var x = +v;\r\n if (x === truncate(x))\r\n return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);\r\n throw new Error(\"Invalid integer: \" + v);\r\n }\r\n var sign = v[0] === \"-\";\r\n if (sign) v = v.slice(1);\r\n var split = v.split(/e/i);\r\n if (split.length > 2) throw new Error(\"Invalid integer: \" + split.join(\"e\"));\r\n if (split.length === 2) {\r\n var exp = split[1];\r\n if (exp[0] === \"+\") exp = exp.slice(1);\r\n exp = +exp;\r\n if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error(\"Invalid integer: \" + exp + \" is not a valid exponent.\");\r\n var text = split[0];\r\n var decimalPlace = text.indexOf(\".\");\r\n if (decimalPlace >= 0) {\r\n exp -= text.length - decimalPlace - 1;\r\n text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);\r\n }\r\n if (exp < 0) throw new Error(\"Cannot include negative exponent part for integers\");\r\n text += (new Array(exp + 1)).join(\"0\");\r\n v = text;\r\n }\r\n var isValid = /^([0-9][0-9]*)$/.test(v);\r\n if (!isValid) throw new Error(\"Invalid integer: \" + v);\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(sign ? \"-\" + v : v));\r\n }\r\n var r = [], max = v.length, l = LOG_BASE, min = max - l;\r\n while (max > 0) {\r\n r.push(+v.slice(min, max));\r\n min -= l;\r\n if (min < 0) min = 0;\r\n max -= l;\r\n }\r\n trim(r);\r\n return new BigInteger(r, sign);\r\n }\r\n\r\n function parseNumberValue(v) {\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(v));\r\n }\r\n if (isPrecise(v)) {\r\n if (v !== truncate(v)) throw new Error(v + \" is not an integer.\");\r\n return new SmallInteger(v);\r\n }\r\n return parseStringValue(v.toString());\r\n }\r\n\r\n function parseValue(v) {\r\n if (typeof v === \"number\") {\r\n return parseNumberValue(v);\r\n }\r\n if (typeof v === \"string\") {\r\n return parseStringValue(v);\r\n }\r\n if (typeof v === \"bigint\") {\r\n return new NativeBigInt(v);\r\n }\r\n return v;\r\n }\r\n // Pre-define numbers in range [-999,999]\r\n for (var i = 0; i < 1000; i++) {\r\n Integer[i] = parseValue(i);\r\n if (i > 0) Integer[-i] = parseValue(-i);\r\n }\r\n // Backwards compatibility\r\n Integer.one = Integer[1];\r\n Integer.zero = Integer[0];\r\n Integer.minusOne = Integer[-1];\r\n Integer.max = max;\r\n Integer.min = min;\r\n Integer.gcd = gcd;\r\n Integer.lcm = lcm;\r\n Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };\r\n Integer.randBetween = randBetween;\r\n\r\n Integer.fromArray = function (digits, base, isNegative) {\r\n return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);\r\n };\r\n\r\n return Integer;\r\n})();\r\n\r\n// Node.js check\r\nif ( true && module.hasOwnProperty(\"exports\")) {\r\n module.exports = bigInt;\r\n}\r\n\r\n//amd check\r\nif (true) {\r\n !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {\r\n return bigInt;\r\n }).call(exports, __webpack_require__, exports, module),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\r\n}\r\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/big-integer/BigInteger.js?");
328
-
329
- /***/ }),
330
-
331
- /***/ "../../node_modules/bignumber.js/bignumber.js":
332
- /*!****************************************************!*\
333
- !*** ../../node_modules/bignumber.js/bignumber.js ***!
334
- \****************************************************/
335
- /***/ (function(module, exports, __webpack_require__) {
336
-
337
- eval("var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalObject) {\r\n 'use strict';\r\n\r\n/*\r\n * bignumber.js v9.0.1\r\n * A JavaScript library for arbitrary-precision arithmetic.\r\n * https://github.com/MikeMcl/bignumber.js\r\n * Copyright (c) 2020 Michael Mclaughlin <M8ch88l@gmail.com>\r\n * MIT Licensed.\r\n *\r\n * BigNumber.prototype methods | BigNumber methods\r\n * |\r\n * absoluteValue abs | clone\r\n * comparedTo | config set\r\n * decimalPlaces dp | DECIMAL_PLACES\r\n * dividedBy div | ROUNDING_MODE\r\n * dividedToIntegerBy idiv | EXPONENTIAL_AT\r\n * exponentiatedBy pow | RANGE\r\n * integerValue | CRYPTO\r\n * isEqualTo eq | MODULO_MODE\r\n * isFinite | POW_PRECISION\r\n * isGreaterThan gt | FORMAT\r\n * isGreaterThanOrEqualTo gte | ALPHABET\r\n * isInteger | isBigNumber\r\n * isLessThan lt | maximum max\r\n * isLessThanOrEqualTo lte | minimum min\r\n * isNaN | random\r\n * isNegative | sum\r\n * isPositive |\r\n * isZero |\r\n * minus |\r\n * modulo mod |\r\n * multipliedBy times |\r\n * negated |\r\n * plus |\r\n * precision sd |\r\n * shiftedBy |\r\n * squareRoot sqrt |\r\n * toExponential |\r\n * toFixed |\r\n * toFormat |\r\n * toFraction |\r\n * toJSON |\r\n * toNumber |\r\n * toPrecision |\r\n * toString |\r\n * valueOf |\r\n *\r\n */\r\n\r\n\r\n var BigNumber,\r\n isNumeric = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i,\r\n mathceil = Math.ceil,\r\n mathfloor = Math.floor,\r\n\r\n bignumberError = '[BigNumber Error] ',\r\n tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',\r\n\r\n BASE = 1e14,\r\n LOG_BASE = 14,\r\n MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1\r\n // MAX_INT32 = 0x7fffffff, // 2^31 - 1\r\n POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],\r\n SQRT_BASE = 1e7,\r\n\r\n // EDITABLE\r\n // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and\r\n // the arguments to toExponential, toFixed, toFormat, and toPrecision.\r\n MAX = 1E9; // 0 to MAX_INT32\r\n\r\n\r\n /*\r\n * Create and return a BigNumber constructor.\r\n */\r\n function clone(configObject) {\r\n var div, convertBase, parseNumeric,\r\n P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },\r\n ONE = new BigNumber(1),\r\n\r\n\r\n //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------\r\n\r\n\r\n // The default values below must be integers within the inclusive ranges stated.\r\n // The values can also be changed at run-time using BigNumber.set.\r\n\r\n // The maximum number of decimal places for operations involving division.\r\n DECIMAL_PLACES = 20, // 0 to MAX\r\n\r\n // The rounding mode used when rounding to the above decimal places, and when using\r\n // toExponential, toFixed, toFormat and toPrecision, and round (default value).\r\n // UP 0 Away from zero.\r\n // DOWN 1 Towards zero.\r\n // CEIL 2 Towards +Infinity.\r\n // FLOOR 3 Towards -Infinity.\r\n // HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n ROUNDING_MODE = 4, // 0 to 8\r\n\r\n // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]\r\n\r\n // The exponent value at and beneath which toString returns exponential notation.\r\n // Number type: -7\r\n TO_EXP_NEG = -7, // 0 to -MAX\r\n\r\n // The exponent value at and above which toString returns exponential notation.\r\n // Number type: 21\r\n TO_EXP_POS = 21, // 0 to MAX\r\n\r\n // RANGE : [MIN_EXP, MAX_EXP]\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // Number type: -324 (5e-324)\r\n MIN_EXP = -1e7, // -1 to -MAX\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // Number type: 308 (1.7976931348623157e+308)\r\n // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.\r\n MAX_EXP = 1e7, // 1 to MAX\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n CRYPTO = false, // true or false\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend.\r\n // This modulo mode is commonly known as 'truncated division' and is\r\n // equivalent to (a % n) in JavaScript.\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).\r\n // The remainder is always positive.\r\n //\r\n // The truncated division, floored division, Euclidian division and IEEE 754 remainder\r\n // modes are commonly used for the modulus operation.\r\n // Although the other rounding modes can also be used, they may not give useful results.\r\n MODULO_MODE = 1, // 0 to 9\r\n\r\n // The maximum number of significant digits of the result of the exponentiatedBy operation.\r\n // If POW_PRECISION is 0, there will be unlimited significant digits.\r\n POW_PRECISION = 0, // 0 to MAX\r\n\r\n // The format specification used by the BigNumber.prototype.toFormat method.\r\n FORMAT = {\r\n prefix: '',\r\n groupSize: 3,\r\n secondaryGroupSize: 0,\r\n groupSeparator: ',',\r\n decimalSeparator: '.',\r\n fractionGroupSize: 0,\r\n fractionGroupSeparator: '\\xA0', // non-breaking space\r\n suffix: ''\r\n },\r\n\r\n // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',\r\n // '-', '.', whitespace, or repeated character.\r\n // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'\r\n ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';\r\n\r\n\r\n //------------------------------------------------------------------------------------------\r\n\r\n\r\n // CONSTRUCTOR\r\n\r\n\r\n /*\r\n * The BigNumber constructor and exported function.\r\n * Create and return a new instance of a BigNumber object.\r\n *\r\n * v {number|string|BigNumber} A numeric value.\r\n * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.\r\n */\r\n function BigNumber(v, b) {\r\n var alphabet, c, caseChanged, e, i, isNum, len, str,\r\n x = this;\r\n\r\n // Enable constructor call without `new`.\r\n if (!(x instanceof BigNumber)) return new BigNumber(v, b);\r\n\r\n if (b == null) {\r\n\r\n if (v && v._isBigNumber === true) {\r\n x.s = v.s;\r\n\r\n if (!v.c || v.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else if (v.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = v.e;\r\n x.c = v.c.slice();\r\n }\r\n\r\n return;\r\n }\r\n\r\n if ((isNum = typeof v == 'number') && v * 0 == 0) {\r\n\r\n // Use `1 / n` to handle minus zero also.\r\n x.s = 1 / v < 0 ? (v = -v, -1) : 1;\r\n\r\n // Fast path for integers, where n < 2147483648 (2**31).\r\n if (v === ~~v) {\r\n for (e = 0, i = v; i >= 10; i /= 10, e++);\r\n\r\n if (e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else {\r\n x.e = e;\r\n x.c = [v];\r\n }\r\n\r\n return;\r\n }\r\n\r\n str = String(v);\r\n } else {\r\n\r\n if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);\r\n\r\n x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n\r\n // Allow exponential notation to be used with base 10 argument, while\r\n // also rounding to DECIMAL_PLACES as with other bases.\r\n if (b == 10) {\r\n x = new BigNumber(v);\r\n return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);\r\n }\r\n\r\n str = String(v);\r\n\r\n if (isNum = typeof v == 'number') {\r\n\r\n // Avoid potential interpretation of Infinity and NaN as base 44+ values.\r\n if (v * 0 != 0) return parseNumeric(x, str, isNum, b);\r\n\r\n x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (BigNumber.DEBUG && str.replace(/^0\\.0*|\\./, '').length > 15) {\r\n throw Error\r\n (tooManyDigits + v);\r\n }\r\n } else {\r\n x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n alphabet = ALPHABET.slice(0, b);\r\n e = i = 0;\r\n\r\n // Check that str is a valid base b number.\r\n // Don't use RegExp, so alphabet can contain special characters.\r\n for (len = str.length; i < len; i++) {\r\n if (alphabet.indexOf(c = str.charAt(i)) < 0) {\r\n if (c == '.') {\r\n\r\n // If '.' is not the first character and it has not be found before.\r\n if (i > e) {\r\n e = len;\r\n continue;\r\n }\r\n } else if (!caseChanged) {\r\n\r\n // Allow e.g. hexadecimal 'FF' as well as 'ff'.\r\n if (str == str.toUpperCase() && (str = str.toLowerCase()) ||\r\n str == str.toLowerCase() && (str = str.toUpperCase())) {\r\n caseChanged = true;\r\n i = -1;\r\n e = 0;\r\n continue;\r\n }\r\n }\r\n\r\n return parseNumeric(x, String(v), isNum, b);\r\n }\r\n }\r\n\r\n // Prevent later check for length on converted number.\r\n isNum = false;\r\n str = convertBase(str, b, 10, x.s);\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n else e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(--len) === 48;);\r\n\r\n if (str = str.slice(i, ++len)) {\r\n len -= i;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (isNum && BigNumber.DEBUG &&\r\n len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {\r\n throw Error\r\n (tooManyDigits + (x.s * v));\r\n }\r\n\r\n // Overflow?\r\n if ((e = e - i - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n x.c = x.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = e;\r\n x.c = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first element of the coefficient array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE; // i < 1\r\n\r\n if (i < len) {\r\n if (i) x.c.push(+str.slice(0, i));\r\n\r\n for (len -= LOG_BASE; i < len;) {\r\n x.c.push(+str.slice(i, i += LOG_BASE));\r\n }\r\n\r\n i = LOG_BASE - (str = str.slice(i)).length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--; str += '0');\r\n x.c.push(+str);\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n\r\n // CONSTRUCTOR PROPERTIES\r\n\r\n\r\n BigNumber.clone = clone;\r\n\r\n BigNumber.ROUND_UP = 0;\r\n BigNumber.ROUND_DOWN = 1;\r\n BigNumber.ROUND_CEIL = 2;\r\n BigNumber.ROUND_FLOOR = 3;\r\n BigNumber.ROUND_HALF_UP = 4;\r\n BigNumber.ROUND_HALF_DOWN = 5;\r\n BigNumber.ROUND_HALF_EVEN = 6;\r\n BigNumber.ROUND_HALF_CEIL = 7;\r\n BigNumber.ROUND_HALF_FLOOR = 8;\r\n BigNumber.EUCLID = 9;\r\n\r\n\r\n /*\r\n * Configure infrequently-changing library-wide settings.\r\n *\r\n * Accept an object with the following optional properties (if the value of a property is\r\n * a number, it must be an integer within the inclusive range stated):\r\n *\r\n * DECIMAL_PLACES {number} 0 to MAX\r\n * ROUNDING_MODE {number} 0 to 8\r\n * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]\r\n * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]\r\n * CRYPTO {boolean} true or false\r\n * MODULO_MODE {number} 0 to 9\r\n * POW_PRECISION {number} 0 to MAX\r\n * ALPHABET {string} A string of two or more unique characters which does\r\n * not contain '.'.\r\n * FORMAT {object} An object with some of the following properties:\r\n * prefix {string}\r\n * groupSize {number}\r\n * secondaryGroupSize {number}\r\n * groupSeparator {string}\r\n * decimalSeparator {string}\r\n * fractionGroupSize {number}\r\n * fractionGroupSeparator {string}\r\n * suffix {string}\r\n *\r\n * (The values assigned to the above FORMAT object properties are not checked for validity.)\r\n *\r\n * E.g.\r\n * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })\r\n *\r\n * Ignore properties/parameters set to null or undefined, except for ALPHABET.\r\n *\r\n * Return an object with the properties current values.\r\n */\r\n BigNumber.config = BigNumber.set = function (obj) {\r\n var p, v;\r\n\r\n if (obj != null) {\r\n\r\n if (typeof obj == 'object') {\r\n\r\n // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n DECIMAL_PLACES = v;\r\n }\r\n\r\n // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.\r\n // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 8, p);\r\n ROUNDING_MODE = v;\r\n }\r\n\r\n // EXPONENTIAL_AT {number|number[]}\r\n // Integer, -MAX to MAX inclusive or\r\n // [integer -MAX to 0 inclusive, 0 to MAX inclusive].\r\n // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, 0, p);\r\n intCheck(v[1], 0, MAX, p);\r\n TO_EXP_NEG = v[0];\r\n TO_EXP_POS = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);\r\n }\r\n }\r\n\r\n // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or\r\n // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].\r\n // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'\r\n if (obj.hasOwnProperty(p = 'RANGE')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, -1, p);\r\n intCheck(v[1], 1, MAX, p);\r\n MIN_EXP = v[0];\r\n MAX_EXP = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n if (v) {\r\n MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' cannot be zero: ' + v);\r\n }\r\n }\r\n }\r\n\r\n // CRYPTO {boolean} true or false.\r\n // '[BigNumber Error] CRYPTO not true or false: {v}'\r\n // '[BigNumber Error] crypto unavailable'\r\n if (obj.hasOwnProperty(p = 'CRYPTO')) {\r\n v = obj[p];\r\n if (v === !!v) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n CRYPTO = v;\r\n } else {\r\n CRYPTO = !v;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n } else {\r\n CRYPTO = v;\r\n }\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' not true or false: ' + v);\r\n }\r\n }\r\n\r\n // MODULO_MODE {number} Integer, 0 to 9 inclusive.\r\n // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'MODULO_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 9, p);\r\n MODULO_MODE = v;\r\n }\r\n\r\n // POW_PRECISION {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'POW_PRECISION')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n POW_PRECISION = v;\r\n }\r\n\r\n // FORMAT {object}\r\n // '[BigNumber Error] FORMAT not an object: {v}'\r\n if (obj.hasOwnProperty(p = 'FORMAT')) {\r\n v = obj[p];\r\n if (typeof v == 'object') FORMAT = v;\r\n else throw Error\r\n (bignumberError + p + ' not an object: ' + v);\r\n }\r\n\r\n // ALPHABET {string}\r\n // '[BigNumber Error] ALPHABET invalid: {v}'\r\n if (obj.hasOwnProperty(p = 'ALPHABET')) {\r\n v = obj[p];\r\n\r\n // Disallow if less than two characters,\r\n // or if it contains '+', '-', '.', whitespace, or a repeated character.\r\n if (typeof v == 'string' && !/^.?$|[+\\-.\\s]|(.).*\\1/.test(v)) {\r\n ALPHABET = v;\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' invalid: ' + v);\r\n }\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Object expected: {v}'\r\n throw Error\r\n (bignumberError + 'Object expected: ' + obj);\r\n }\r\n }\r\n\r\n return {\r\n DECIMAL_PLACES: DECIMAL_PLACES,\r\n ROUNDING_MODE: ROUNDING_MODE,\r\n EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],\r\n RANGE: [MIN_EXP, MAX_EXP],\r\n CRYPTO: CRYPTO,\r\n MODULO_MODE: MODULO_MODE,\r\n POW_PRECISION: POW_PRECISION,\r\n FORMAT: FORMAT,\r\n ALPHABET: ALPHABET\r\n };\r\n };\r\n\r\n\r\n /*\r\n * Return true if v is a BigNumber instance, otherwise return false.\r\n *\r\n * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.\r\n *\r\n * v {any}\r\n *\r\n * '[BigNumber Error] Invalid BigNumber: {v}'\r\n */\r\n BigNumber.isBigNumber = function (v) {\r\n if (!v || v._isBigNumber !== true) return false;\r\n if (!BigNumber.DEBUG) return true;\r\n\r\n var i, n,\r\n c = v.c,\r\n e = v.e,\r\n s = v.s;\r\n\r\n out: if ({}.toString.call(c) == '[object Array]') {\r\n\r\n if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {\r\n\r\n // If the first element is zero, the BigNumber value must be zero.\r\n if (c[0] === 0) {\r\n if (e === 0 && c.length === 1) return true;\r\n break out;\r\n }\r\n\r\n // Calculate number of digits that c[0] should have, based on the exponent.\r\n i = (e + 1) % LOG_BASE;\r\n if (i < 1) i += LOG_BASE;\r\n\r\n // Calculate number of digits of c[0].\r\n //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {\r\n if (String(c[0]).length == i) {\r\n\r\n for (i = 0; i < c.length; i++) {\r\n n = c[i];\r\n if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;\r\n }\r\n\r\n // Last element cannot be zero, unless it is the only element.\r\n if (n !== 0) return true;\r\n }\r\n }\r\n\r\n // Infinity/NaN\r\n } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {\r\n return true;\r\n }\r\n\r\n throw Error\r\n (bignumberError + 'Invalid BigNumber: ' + v);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.maximum = BigNumber.max = function () {\r\n return maxOrMin(arguments, P.lt);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.minimum = BigNumber.min = function () {\r\n return maxOrMin(arguments, P.gt);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,\r\n * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing\r\n * zeros are produced).\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'\r\n * '[BigNumber Error] crypto unavailable'\r\n */\r\n BigNumber.random = (function () {\r\n var pow2_53 = 0x20000000000000;\r\n\r\n // Return a 53 bit integer n, where 0 <= n < 9007199254740992.\r\n // Check if Math.random() produces more than 32 bits of randomness.\r\n // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.\r\n // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.\r\n var random53bitInt = (Math.random() * pow2_53) & 0x1fffff\r\n ? function () { return mathfloor(Math.random() * pow2_53); }\r\n : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +\r\n (Math.random() * 0x800000 | 0); };\r\n\r\n return function (dp) {\r\n var a, b, e, k, v,\r\n i = 0,\r\n c = [],\r\n rand = new BigNumber(ONE);\r\n\r\n if (dp == null) dp = DECIMAL_PLACES;\r\n else intCheck(dp, 0, MAX);\r\n\r\n k = mathceil(dp / LOG_BASE);\r\n\r\n if (CRYPTO) {\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n if (crypto.getRandomValues) {\r\n\r\n a = crypto.getRandomValues(new Uint32Array(k *= 2));\r\n\r\n for (; i < k;) {\r\n\r\n // 53 bits:\r\n // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)\r\n // 11111 11111111 11111111 11111111 11100000 00000000 00000000\r\n // ((Math.pow(2, 32) - 1) >>> 11).toString(2)\r\n // 11111 11111111 11111111\r\n // 0x20000 is 2^21.\r\n v = a[i] * 0x20000 + (a[i + 1] >>> 11);\r\n\r\n // Rejection sampling:\r\n // 0 <= v < 9007199254740992\r\n // Probability that v >= 9e15, is\r\n // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251\r\n if (v >= 9e15) {\r\n b = crypto.getRandomValues(new Uint32Array(2));\r\n a[i] = b[0];\r\n a[i + 1] = b[1];\r\n } else {\r\n\r\n // 0 <= v <= 8999999999999999\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 2;\r\n }\r\n }\r\n i = k / 2;\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n a = crypto.randomBytes(k *= 7);\r\n\r\n for (; i < k;) {\r\n\r\n // 0x1000000000000 is 2^48, 0x10000000000 is 2^40\r\n // 0x100000000 is 2^32, 0x1000000 is 2^24\r\n // 11111 11111111 11111111 11111111 11111111 11111111 11111111\r\n // 0 <= v < 9007199254740992\r\n v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +\r\n (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +\r\n (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];\r\n\r\n if (v >= 9e15) {\r\n crypto.randomBytes(7).copy(a, i);\r\n } else {\r\n\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 7;\r\n }\r\n }\r\n i = k / 7;\r\n } else {\r\n CRYPTO = false;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n }\r\n\r\n // Use Math.random.\r\n if (!CRYPTO) {\r\n\r\n for (; i < k;) {\r\n v = random53bitInt();\r\n if (v < 9e15) c[i++] = v % 1e14;\r\n }\r\n }\r\n\r\n k = c[--i];\r\n dp %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to dp.\r\n if (k && dp) {\r\n v = POWS_TEN[LOG_BASE - dp];\r\n c[i] = mathfloor(k / v) * v;\r\n }\r\n\r\n // Remove trailing elements which are zero.\r\n for (; c[i] === 0; c.pop(), i--);\r\n\r\n // Zero?\r\n if (i < 0) {\r\n c = [e = 0];\r\n } else {\r\n\r\n // Remove leading elements which are zero and adjust exponent accordingly.\r\n for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);\r\n\r\n // Count the digits of the first element of c to determine leading zeros, and...\r\n for (i = 1, v = c[0]; v >= 10; v /= 10, i++);\r\n\r\n // adjust the exponent accordingly.\r\n if (i < LOG_BASE) e -= LOG_BASE - i;\r\n }\r\n\r\n rand.e = e;\r\n rand.c = c;\r\n return rand;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the sum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.sum = function () {\r\n var i = 1,\r\n args = arguments,\r\n sum = new BigNumber(args[0]);\r\n for (; i < args.length;) sum = sum.plus(args[i++]);\r\n return sum;\r\n };\r\n\r\n\r\n // PRIVATE FUNCTIONS\r\n\r\n\r\n // Called by BigNumber and BigNumber.prototype.toString.\r\n convertBase = (function () {\r\n var decimal = '0123456789';\r\n\r\n /*\r\n * Convert string of baseIn to an array of numbers of baseOut.\r\n * Eg. toBaseOut('255', 10, 16) returns [15, 15].\r\n * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].\r\n */\r\n function toBaseOut(str, baseIn, baseOut, alphabet) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n len = str.length;\r\n\r\n for (; i < len;) {\r\n for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);\r\n\r\n arr[0] += alphabet.indexOf(str.charAt(i++));\r\n\r\n for (j = 0; j < arr.length; j++) {\r\n\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] == null) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n }\r\n\r\n // Convert a numeric string of baseIn to a numeric string of baseOut.\r\n // If the caller is toString, we are converting from base 10 to baseOut.\r\n // If the caller is BigNumber, we are converting from baseIn to base 10.\r\n return function (str, baseIn, baseOut, sign, callerIsToString) {\r\n var alphabet, d, e, k, r, x, xc, y,\r\n i = str.indexOf('.'),\r\n dp = DECIMAL_PLACES,\r\n rm = ROUNDING_MODE;\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n k = POW_PRECISION;\r\n\r\n // Unlimited precision.\r\n POW_PRECISION = 0;\r\n str = str.replace('.', '');\r\n y = new BigNumber(baseIn);\r\n x = y.pow(str.length - i);\r\n POW_PRECISION = k;\r\n\r\n // Convert str as if an integer, then restore the fraction part by dividing the\r\n // result by its base raised to a power.\r\n\r\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),\r\n 10, baseOut, decimal);\r\n y.e = y.c.length;\r\n }\r\n\r\n // Convert the number as integer.\r\n\r\n xc = toBaseOut(str, baseIn, baseOut, callerIsToString\r\n ? (alphabet = ALPHABET, decimal)\r\n : (alphabet = decimal, ALPHABET));\r\n\r\n // xc now represents str as an integer and converted to baseOut. e is the exponent.\r\n e = k = xc.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xc[--k] == 0; xc.pop());\r\n\r\n // Zero?\r\n if (!xc[0]) return alphabet.charAt(0);\r\n\r\n // Does str represent an integer? If so, no need for the division.\r\n if (i < 0) {\r\n --e;\r\n } else {\r\n x.c = xc;\r\n x.e = e;\r\n\r\n // The sign is needed for correct rounding.\r\n x.s = sign;\r\n x = div(x, y, dp, rm, baseOut);\r\n xc = x.c;\r\n r = x.r;\r\n e = x.e;\r\n }\r\n\r\n // xc now represents str converted to baseOut.\r\n\r\n // THe index of the rounding digit.\r\n d = e + dp + 1;\r\n\r\n // The rounding digit: the digit to the right of the digit that may be rounded up.\r\n i = xc[d];\r\n\r\n // Look at the rounding digits and mode to determine whether to round up.\r\n\r\n k = baseOut / 2;\r\n r = r || d < 0 || xc[d + 1] != null;\r\n\r\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n // If the index of the rounding digit is not greater than zero, or xc represents\r\n // zero, then the result of the base conversion is zero or, if rounding up, a value\r\n // such as 0.00001.\r\n if (d < 1 || !xc[0]) {\r\n\r\n // 1^-dp or 0\r\n str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);\r\n } else {\r\n\r\n // Truncate xc to the required number of decimal places.\r\n xc.length = d;\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (--baseOut; ++xc[--d] > baseOut;) {\r\n xc[d] = 0;\r\n\r\n if (!d) {\r\n ++e;\r\n xc = [1].concat(xc);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (k = xc.length; !xc[--k];);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));\r\n\r\n // Add leading zeros, decimal point and trailing zeros as required.\r\n str = toFixedPoint(str, e, alphabet.charAt(0));\r\n }\r\n\r\n // The caller will add the sign.\r\n return str;\r\n };\r\n })();\r\n\r\n\r\n // Perform division in the specified base. Called by div and convertBase.\r\n div = (function () {\r\n\r\n // Assume non-zero x and k.\r\n function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, cmp;\r\n\r\n if (aL != bL) {\r\n cmp = aL > bL ? 1 : -1;\r\n } else {\r\n\r\n for (i = cmp = 0; i < aL; i++) {\r\n\r\n if (a[i] != b[i]) {\r\n cmp = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return cmp;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1; a.splice(0, 1));\r\n }\r\n\r\n // x: dividend, y: divisor.\r\n return function (x, y, dp, rm, base) {\r\n var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,\r\n yL, yz,\r\n s = x.s == y.s ? 1 : -1,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xc || !xc[0] || !yc || !yc[0]) {\r\n\r\n return new BigNumber(\r\n\r\n // Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :\r\n\r\n // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.\r\n xc && xc[0] == 0 || !yc ? s * 0 : s / 0\r\n );\r\n }\r\n\r\n q = new BigNumber(s);\r\n qc = q.c = [];\r\n e = x.e - y.e;\r\n s = dp + e + 1;\r\n\r\n if (!base) {\r\n base = BASE;\r\n e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);\r\n s = s / LOG_BASE | 0;\r\n }\r\n\r\n // Result exponent may be one less then the current value of e.\r\n // The coefficients of the BigNumbers from convertBase may have trailing zeros.\r\n for (i = 0; yc[i] == (xc[i] || 0); i++);\r\n\r\n if (yc[i] > (xc[i] || 0)) e--;\r\n\r\n if (s < 0) {\r\n qc.push(1);\r\n more = true;\r\n } else {\r\n xL = xc.length;\r\n yL = yc.length;\r\n i = 0;\r\n s += 2;\r\n\r\n // Normalise xc and yc so highest order digit of yc is >= base / 2.\r\n\r\n n = mathfloor(base / (yc[0] + 1));\r\n\r\n // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.\r\n // if (n > 1 || n++ == 1 && yc[0] < base / 2) {\r\n if (n > 1) {\r\n yc = multiply(yc, n, base);\r\n xc = multiply(xc, n, base);\r\n yL = yc.length;\r\n xL = xc.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xc.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL; rem[remL++] = 0);\r\n yz = yc.slice();\r\n yz = [0].concat(yz);\r\n yc0 = yc[0];\r\n if (yc[1] >= base / 2) yc0++;\r\n // Not necessary, but to prevent trial digit n > base, when using base 3.\r\n // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;\r\n\r\n do {\r\n n = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yc, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, n.\r\n\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // n is how many times the divisor goes into the current remainder.\r\n n = mathfloor(rem0 / yc0);\r\n\r\n // Algorithm:\r\n // product = divisor multiplied by trial digit (n).\r\n // Compare product and remainder.\r\n // If product is greater than remainder:\r\n // Subtract divisor from product, decrement trial digit.\r\n // Subtract product from remainder.\r\n // If product was less than remainder at the last compare:\r\n // Compare new remainder and divisor.\r\n // If remainder is greater than divisor:\r\n // Subtract divisor from remainder, increment trial digit.\r\n\r\n if (n > 1) {\r\n\r\n // n may be > base only when base is 3.\r\n if (n >= base) n = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiply(yc, n, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n // If product > remainder then trial digit n too high.\r\n // n is 1 too high about 5% of the time, and is not known to have\r\n // ever been more than 1 too high.\r\n while (compare(prod, rem, prodL, remL) == 1) {\r\n n--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yc, prodL, base);\r\n prodL = prod.length;\r\n cmp = 1;\r\n }\r\n } else {\r\n\r\n // n is 0 or 1, cmp is -1.\r\n // If n is 0, there is no need to compare yc and rem again below,\r\n // so change cmp to 1 to avoid it.\r\n // If n is 1, leave cmp as -1, so yc and rem are compared again.\r\n if (n == 0) {\r\n\r\n // divisor < remainder, so n must be at least 1.\r\n cmp = n = 1;\r\n }\r\n\r\n // product = divisor\r\n prod = yc.slice();\r\n prodL = prod.length;\r\n }\r\n\r\n if (prodL < remL) prod = [0].concat(prod);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n remL = rem.length;\r\n\r\n // If product was < remainder.\r\n if (cmp == -1) {\r\n\r\n // Compare divisor and new remainder.\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n // Trial digit n too low.\r\n // n is 1 too low about 5% of the time, and very rarely 2 too low.\r\n while (compare(yc, rem, yL, remL) < 1) {\r\n n++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yc, remL, base);\r\n remL = rem.length;\r\n }\r\n }\r\n } else if (cmp === 0) {\r\n n++;\r\n rem = [0];\r\n } // else cmp === 1 and n will be 0\r\n\r\n // Add the next digit, n, to the result array.\r\n qc[i++] = n;\r\n\r\n // Update the remainder.\r\n if (rem[0]) {\r\n rem[remL++] = xc[xi] || 0;\r\n } else {\r\n rem = [xc[xi]];\r\n remL = 1;\r\n }\r\n } while ((xi++ < xL || rem[0] != null) && s--);\r\n\r\n more = rem[0] != null;\r\n\r\n // Leading zero?\r\n if (!qc[0]) qc.splice(0, 1);\r\n }\r\n\r\n if (base == BASE) {\r\n\r\n // To calculate q.e, first get the number of digits of qc[0].\r\n for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);\r\n\r\n round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);\r\n\r\n // Caller is convertBase.\r\n } else {\r\n q.e = e;\r\n q.r = +more;\r\n }\r\n\r\n return q;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a string representing the value of BigNumber n in fixed-point or exponential\r\n * notation rounded to the specified decimal places or significant digits.\r\n *\r\n * n: a BigNumber.\r\n * i: the index of the last digit required (i.e. the digit that may be rounded up).\r\n * rm: the rounding mode.\r\n * id: 1 (toExponential) or 2 (toPrecision).\r\n */\r\n function format(n, i, rm, id) {\r\n var c0, e, ne, len, str;\r\n\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n if (!n.c) return n.toString();\r\n\r\n c0 = n.c[0];\r\n ne = n.e;\r\n\r\n if (i == null) {\r\n str = coeffToString(n.c);\r\n str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)\r\n ? toExponential(str, ne)\r\n : toFixedPoint(str, ne, '0');\r\n } else {\r\n n = round(new BigNumber(n), i, rm);\r\n\r\n // n.e may have changed if the value was rounded up.\r\n e = n.e;\r\n\r\n str = coeffToString(n.c);\r\n len = str.length;\r\n\r\n // toPrecision returns exponential notation if the number of significant digits\r\n // specified is less than the number of digits necessary to represent the integer\r\n // part of the value in fixed-point notation.\r\n\r\n // Exponential notation.\r\n if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {\r\n\r\n // Append zeros?\r\n for (; len < i; str += '0', len++);\r\n str = toExponential(str, e);\r\n\r\n // Fixed-point notation.\r\n } else {\r\n i -= ne;\r\n str = toFixedPoint(str, e, '0');\r\n\r\n // Append zeros?\r\n if (e + 1 > len) {\r\n if (--i > 0) for (str += '.'; i--; str += '0');\r\n } else {\r\n i += e - len;\r\n if (i > 0) {\r\n if (e + 1 == len) str += '.';\r\n for (; i--; str += '0');\r\n }\r\n }\r\n }\r\n }\r\n\r\n return n.s < 0 && c0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // Handle BigNumber.max and BigNumber.min.\r\n function maxOrMin(args, method) {\r\n var n,\r\n i = 1,\r\n m = new BigNumber(args[0]);\r\n\r\n for (; i < args.length; i++) {\r\n n = new BigNumber(args[i]);\r\n\r\n // If any number is NaN, return NaN.\r\n if (!n.s) {\r\n m = n;\r\n break;\r\n } else if (method.call(m, n)) {\r\n m = n;\r\n }\r\n }\r\n\r\n return m;\r\n }\r\n\r\n\r\n /*\r\n * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.\r\n * Called by minus, plus and times.\r\n */\r\n function normalise(n, c, e) {\r\n var i = 1,\r\n j = c.length;\r\n\r\n // Remove trailing zeros.\r\n for (; !c[--j]; c.pop());\r\n\r\n // Calculate the base 10 exponent. First get the number of digits of c[0].\r\n for (j = c[0]; j >= 10; j /= 10, i++);\r\n\r\n // Overflow?\r\n if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n n.c = n.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n n.c = [n.e = 0];\r\n } else {\r\n n.e = e;\r\n n.c = c;\r\n }\r\n\r\n return n;\r\n }\r\n\r\n\r\n // Handle values that fail the validity test in BigNumber.\r\n parseNumeric = (function () {\r\n var basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i,\r\n dotAfter = /^([^.]+)\\.$/,\r\n dotBefore = /^\\.([^.]+)$/,\r\n isInfinityOrNaN = /^-?(Infinity|NaN)$/,\r\n whitespaceOrPlus = /^\\s*\\+(?=[\\w.])|^\\s+|\\s+$/g;\r\n\r\n return function (x, str, isNum, b) {\r\n var base,\r\n s = isNum ? str : str.replace(whitespaceOrPlus, '');\r\n\r\n // No exception on ±Infinity or NaN.\r\n if (isInfinityOrNaN.test(s)) {\r\n x.s = isNaN(s) ? null : s < 0 ? -1 : 1;\r\n } else {\r\n if (!isNum) {\r\n\r\n // basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i\r\n s = s.replace(basePrefix, function (m, p1, p2) {\r\n base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;\r\n return !b || b == base ? p1 : m;\r\n });\r\n\r\n if (b) {\r\n base = b;\r\n\r\n // E.g. '1.' to '1', '.1' to '0.1'\r\n s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');\r\n }\r\n\r\n if (str != s) return new BigNumber(s, base);\r\n }\r\n\r\n // '[BigNumber Error] Not a number: {n}'\r\n // '[BigNumber Error] Not a base {b} number: {n}'\r\n if (BigNumber.DEBUG) {\r\n throw Error\r\n (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);\r\n }\r\n\r\n // NaN\r\n x.s = null;\r\n }\r\n\r\n x.c = x.e = null;\r\n }\r\n })();\r\n\r\n\r\n /*\r\n * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.\r\n * If r is truthy, it is known that there are more digits after the rounding digit.\r\n */\r\n function round(x, sd, rm, r) {\r\n var d, i, j, k, n, ni, rd,\r\n xc = x.c,\r\n pows10 = POWS_TEN;\r\n\r\n // if x is not Infinity or NaN...\r\n if (xc) {\r\n\r\n // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // n is a base 1e14 number, the value of the element of array x.c containing rd.\r\n // ni is the index of n within x.c.\r\n // d is the number of digits of n.\r\n // i is the index of rd within n including leading zeros.\r\n // j is the actual index of rd within n (if < 0, rd is a leading zero).\r\n out: {\r\n\r\n // Get the number of digits of the first element of xc.\r\n for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);\r\n i = sd - d;\r\n\r\n // If the rounding digit is in the first element of xc...\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n n = xc[ni = 0];\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = n / pows10[d - j - 1] % 10 | 0;\r\n } else {\r\n ni = mathceil((i + 1) / LOG_BASE);\r\n\r\n if (ni >= xc.length) {\r\n\r\n if (r) {\r\n\r\n // Needed by sqrt.\r\n for (; xc.length <= ni; xc.push(0));\r\n n = rd = 0;\r\n d = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n n = k = xc[ni];\r\n\r\n // Get the number of digits of n.\r\n for (d = 1; k >= 10; k /= 10, d++);\r\n\r\n // Get the index of rd within n.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within n, adjusted for leading zeros.\r\n // The number of leading zeros of n is given by LOG_BASE - d.\r\n j = i - LOG_BASE + d;\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0;\r\n }\r\n }\r\n\r\n r = r || sd < 0 ||\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n // The expression n % pows10[d - j - 1] returns all digits of n to the right\r\n // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.\r\n xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);\r\n\r\n r = rm < 4\r\n ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xc[0]) {\r\n xc.length = 0;\r\n\r\n if (r) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xc[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xc.length = ni;\r\n k = 1;\r\n ni--;\r\n } else {\r\n xc.length = ni + 1;\r\n k = pows10[LOG_BASE - i];\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of n.\r\n xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;\r\n }\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n for (; ;) {\r\n\r\n // If the digit to be rounded up is in the first element of xc...\r\n if (ni == 0) {\r\n\r\n // i will be the length of xc[0] before k is added.\r\n for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);\r\n j = xc[0] += k;\r\n for (k = 1; j >= 10; j /= 10, k++);\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xc[0] == BASE) xc[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xc[ni] += k;\r\n if (xc[ni] != BASE) break;\r\n xc[ni--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xc.length; xc[--i] === 0; xc.pop());\r\n }\r\n\r\n // Overflow? Infinity.\r\n if (x.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n\r\n // Underflow? Zero.\r\n } else if (x.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n function valueOf(n) {\r\n var str,\r\n e = n.e;\r\n\r\n if (e === null) return n.toString();\r\n\r\n str = coeffToString(n.c);\r\n\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(str, e)\r\n : toFixedPoint(str, e, '0');\r\n\r\n return n.s < 0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // PROTOTYPE/INSTANCE METHODS\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the absolute value of this BigNumber.\r\n */\r\n P.absoluteValue = P.abs = function () {\r\n var x = new BigNumber(this);\r\n if (x.s < 0) x.s = 1;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * 0 if they have the same value,\r\n * or null if the value of either is NaN.\r\n */\r\n P.comparedTo = function (y, b) {\r\n return compare(this, new BigNumber(y, b));\r\n };\r\n\r\n\r\n /*\r\n * If dp is undefined or null or true or false, return the number of decimal places of the\r\n * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n *\r\n * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * [dp] {number} Decimal places: integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.decimalPlaces = P.dp = function (dp, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), dp + x.e + 1, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last number.\r\n if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);\r\n if (n < 0) n = 0;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber divided by the value of\r\n * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.dividedBy = P.div = function (y, b) {\r\n return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the integer part of dividing the value of this\r\n * BigNumber by the value of BigNumber(y, b).\r\n */\r\n P.dividedToIntegerBy = P.idiv = function (y, b) {\r\n return div(this, new BigNumber(y, b), 0, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.\r\n *\r\n * If m is present, return the result modulo m.\r\n * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.\r\n * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.\r\n *\r\n * The modular power operation works efficiently when x, n, and m are integers, otherwise it\r\n * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.\r\n *\r\n * n {number|string|BigNumber} The exponent. An integer.\r\n * [m] {number|string|BigNumber} The modulus.\r\n *\r\n * '[BigNumber Error] Exponent not an integer: {n}'\r\n */\r\n P.exponentiatedBy = P.pow = function (n, m) {\r\n var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,\r\n x = this;\r\n\r\n n = new BigNumber(n);\r\n\r\n // Allow NaN and ±Infinity, but not other non-integers.\r\n if (n.c && !n.isInteger()) {\r\n throw Error\r\n (bignumberError + 'Exponent not an integer: ' + valueOf(n));\r\n }\r\n\r\n if (m != null) m = new BigNumber(m);\r\n\r\n // Exponent of MAX_SAFE_INTEGER is 15.\r\n nIsBig = n.e > 14;\r\n\r\n // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0.\r\n if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {\r\n\r\n // The sign of the result of pow when x is negative depends on the evenness of n.\r\n // If +n overflows to ±Infinity, the evenness of n would be not be known.\r\n y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n)));\r\n return m ? y.mod(m) : y;\r\n }\r\n\r\n nIsNeg = n.s < 0;\r\n\r\n if (m) {\r\n\r\n // x % m returns NaN if abs(m) is zero, or m is NaN.\r\n if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);\r\n\r\n isModExp = !nIsNeg && x.isInteger() && m.isInteger();\r\n\r\n if (isModExp) x = x.mod(m);\r\n\r\n // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15.\r\n // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15.\r\n } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0\r\n // [1, 240000000]\r\n ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7\r\n // [80000000000000] [99999750000000]\r\n : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {\r\n\r\n // If x is negative and n is odd, k = -0, else k = 0.\r\n k = x.s < 0 && isOdd(n) ? -0 : 0;\r\n\r\n // If x >= 1, k = ±Infinity.\r\n if (x.e > -1) k = 1 / k;\r\n\r\n // If n is negative return ±0, else return ±Infinity.\r\n return new BigNumber(nIsNeg ? 1 / k : k);\r\n\r\n } else if (POW_PRECISION) {\r\n\r\n // Truncating each coefficient array to a length of k after each multiplication\r\n // equates to truncating significant digits to POW_PRECISION + [28, 41],\r\n // i.e. there will be a minimum of 28 guard digits retained.\r\n k = mathceil(POW_PRECISION / LOG_BASE + 2);\r\n }\r\n\r\n if (nIsBig) {\r\n half = new BigNumber(0.5);\r\n if (nIsNeg) n.s = 1;\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = Math.abs(+valueOf(n));\r\n nIsOdd = i % 2;\r\n }\r\n\r\n y = new BigNumber(ONE);\r\n\r\n // Performs 54 loop iterations for n of 9007199254740991.\r\n for (; ;) {\r\n\r\n if (nIsOdd) {\r\n y = y.times(x);\r\n if (!y.c) break;\r\n\r\n if (k) {\r\n if (y.c.length > k) y.c.length = k;\r\n } else if (isModExp) {\r\n y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (i) {\r\n i = mathfloor(i / 2);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n } else {\r\n n = n.times(half);\r\n round(n, n.e + 1, 1);\r\n\r\n if (n.e > 14) {\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = +valueOf(n);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n }\r\n }\r\n\r\n x = x.times(x);\r\n\r\n if (k) {\r\n if (x.c && x.c.length > k) x.c.length = k;\r\n } else if (isModExp) {\r\n x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (isModExp) return y;\r\n if (nIsNeg) y = ONE.div(y);\r\n\r\n return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer\r\n * using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'\r\n */\r\n P.integerValue = function (rm) {\r\n var n = new BigNumber(this);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n return round(n, n.e + 1, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isEqualTo = P.eq = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is a finite number, otherwise return false.\r\n */\r\n P.isFinite = function () {\r\n return !!this.c;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isGreaterThan = P.gt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isGreaterThanOrEqualTo = P.gte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;\r\n\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is an integer, otherwise return false.\r\n */\r\n P.isInteger = function () {\r\n return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isLessThan = P.lt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isLessThanOrEqualTo = P.lte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is NaN, otherwise return false.\r\n */\r\n P.isNaN = function () {\r\n return !this.s;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is negative, otherwise return false.\r\n */\r\n P.isNegative = function () {\r\n return this.s < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is positive, otherwise return false.\r\n */\r\n P.isPositive = function () {\r\n return this.s > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is 0 or -0, otherwise return false.\r\n */\r\n P.isZero = function () {\r\n return !!this.c && this.c[0] == 0;\r\n };\r\n\r\n\r\n /*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber minus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.minus = function (y, b) {\r\n var i, j, t, xLTy,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.plus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);\r\n\r\n // Either zero?\r\n if (!xc[0] || !yc[0]) {\r\n\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :\r\n\r\n // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity\r\n ROUNDING_MODE == 3 ? -0 : 0);\r\n }\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Determine which is the bigger number.\r\n if (a = xe - ye) {\r\n\r\n if (xLTy = a < 0) {\r\n a = -a;\r\n t = xc;\r\n } else {\r\n ye = xe;\r\n t = yc;\r\n }\r\n\r\n t.reverse();\r\n\r\n // Prepend zeros to equalise exponents.\r\n for (b = a; b--; t.push(0));\r\n t.reverse();\r\n } else {\r\n\r\n // Exponents equal. Check digit by digit.\r\n j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;\r\n\r\n for (a = b = 0; b < j; b++) {\r\n\r\n if (xc[b] != yc[b]) {\r\n xLTy = xc[b] < yc[b];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // x < y? Point xc to the array of the bigger number.\r\n if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;\r\n\r\n b = (j = yc.length) - (i = xc.length);\r\n\r\n // Append zeros to xc if shorter.\r\n // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.\r\n if (b > 0) for (; b--; xc[i++] = 0);\r\n b = BASE - 1;\r\n\r\n // Subtract yc from xc.\r\n for (; j > a;) {\r\n\r\n if (xc[--j] < yc[j]) {\r\n for (i = j; i && !xc[--i]; xc[i] = b);\r\n --xc[i];\r\n xc[j] += BASE;\r\n }\r\n\r\n xc[j] -= yc[j];\r\n }\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xc[0] == 0; xc.splice(0, 1), --ye);\r\n\r\n // Zero?\r\n if (!xc[0]) {\r\n\r\n // Following IEEE 754 (2008) 6.3,\r\n // n - n = +0 but n - n = -0 when rounding towards -Infinity.\r\n y.s = ROUNDING_MODE == 3 ? -1 : 1;\r\n y.c = [y.e = 0];\r\n return y;\r\n }\r\n\r\n // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity\r\n // for finite x and y.\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber modulo the value of\r\n * BigNumber(y, b). The result depends on the value of MODULO_MODE.\r\n */\r\n P.modulo = P.mod = function (y, b) {\r\n var q, s,\r\n x = this;\r\n\r\n y = new BigNumber(y, b);\r\n\r\n // Return NaN if x is Infinity or NaN, or y is NaN or zero.\r\n if (!x.c || !y.s || y.c && !y.c[0]) {\r\n return new BigNumber(NaN);\r\n\r\n // Return x if y is Infinity or x is zero.\r\n } else if (!y.c || x.c && !x.c[0]) {\r\n return new BigNumber(x);\r\n }\r\n\r\n if (MODULO_MODE == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // r = x - qy where 0 <= r < abs(y)\r\n s = y.s;\r\n y.s = 1;\r\n q = div(x, y, 0, 3);\r\n y.s = s;\r\n q.s *= s;\r\n } else {\r\n q = div(x, y, 0, MODULO_MODE);\r\n }\r\n\r\n y = x.minus(q.times(y));\r\n\r\n // To match JavaScript %, ensure sign of zero is sign of dividend.\r\n if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;\r\n\r\n return y;\r\n };\r\n\r\n\r\n /*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value\r\n * of BigNumber(y, b).\r\n */\r\n P.multipliedBy = P.times = function (y, b) {\r\n var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,\r\n base, sqrtBase,\r\n x = this,\r\n xc = x.c,\r\n yc = (y = new BigNumber(y, b)).c;\r\n\r\n // Either NaN, ±Infinity or ±0?\r\n if (!xc || !yc || !xc[0] || !yc[0]) {\r\n\r\n // Return NaN if either is NaN, or one is 0 and the other is Infinity.\r\n if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {\r\n y.c = y.e = y.s = null;\r\n } else {\r\n y.s *= x.s;\r\n\r\n // Return ±Infinity if either is ±Infinity.\r\n if (!xc || !yc) {\r\n y.c = y.e = null;\r\n\r\n // Return ±0 if either is ±0.\r\n } else {\r\n y.c = [0];\r\n y.e = 0;\r\n }\r\n }\r\n\r\n return y;\r\n }\r\n\r\n e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);\r\n y.s *= x.s;\r\n xcL = xc.length;\r\n ycL = yc.length;\r\n\r\n // Ensure xc points to longer array and xcL to its length.\r\n if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;\r\n\r\n // Initialise the result array with zeros.\r\n for (i = xcL + ycL, zc = []; i--; zc.push(0));\r\n\r\n base = BASE;\r\n sqrtBase = SQRT_BASE;\r\n\r\n for (i = ycL; --i >= 0;) {\r\n c = 0;\r\n ylo = yc[i] % sqrtBase;\r\n yhi = yc[i] / sqrtBase | 0;\r\n\r\n for (k = xcL, j = i + k; j > i;) {\r\n xlo = xc[--k] % sqrtBase;\r\n xhi = xc[k] / sqrtBase | 0;\r\n m = yhi * xlo + xhi * ylo;\r\n xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;\r\n c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;\r\n zc[j--] = xlo % base;\r\n }\r\n\r\n zc[j] = c;\r\n }\r\n\r\n if (c) {\r\n ++e;\r\n } else {\r\n zc.splice(0, 1);\r\n }\r\n\r\n return normalise(y, zc, e);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber negated,\r\n * i.e. multiplied by -1.\r\n */\r\n P.negated = function () {\r\n var x = new BigNumber(this);\r\n x.s = -x.s || null;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber plus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.plus = function (y, b) {\r\n var t,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.minus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Return ±Infinity if either ±Infinity.\r\n if (!xc || !yc) return new BigNumber(a / 0);\r\n\r\n // Either zero?\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.\r\n if (a = xe - ye) {\r\n if (a > 0) {\r\n ye = xe;\r\n t = yc;\r\n } else {\r\n a = -a;\r\n t = xc;\r\n }\r\n\r\n t.reverse();\r\n for (; a--; t.push(0));\r\n t.reverse();\r\n }\r\n\r\n a = xc.length;\r\n b = yc.length;\r\n\r\n // Point xc to the longer array, and b to the shorter length.\r\n if (a - b < 0) t = yc, yc = xc, xc = t, b = a;\r\n\r\n // Only start adding at yc.length - 1 as the further digits of xc can be ignored.\r\n for (a = 0; b;) {\r\n a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;\r\n xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;\r\n }\r\n\r\n if (a) {\r\n xc = [a].concat(xc);\r\n ++ye;\r\n }\r\n\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n // ye = MAX_EXP + 1 possible\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * If sd is undefined or null or true or false, return the number of significant digits of\r\n * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n * If sd is true include integer-part trailing zeros in the count.\r\n *\r\n * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.\r\n * boolean: whether to count integer-part trailing zeros: true or false.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.precision = P.sd = function (sd, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (sd != null && sd !== !!sd) {\r\n intCheck(sd, 1, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), sd, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n v = c.length - 1;\r\n n = v * LOG_BASE + 1;\r\n\r\n if (v = c[v]) {\r\n\r\n // Subtract the number of trailing zeros of the last element.\r\n for (; v % 10 == 0; v /= 10, n--);\r\n\r\n // Add the number of digits of the first element.\r\n for (v = c[0]; v >= 10; v /= 10, n++);\r\n }\r\n\r\n if (sd && x.e + 1 > n) n = x.e + 1;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber shifted by k places\r\n * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.\r\n *\r\n * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'\r\n */\r\n P.shiftedBy = function (k) {\r\n intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);\r\n return this.times('1e' + k);\r\n };\r\n\r\n\r\n /*\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n * Return a new BigNumber whose value is the square root of the value of this BigNumber,\r\n * rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.squareRoot = P.sqrt = function () {\r\n var m, n, r, rep, t,\r\n x = this,\r\n c = x.c,\r\n s = x.s,\r\n e = x.e,\r\n dp = DECIMAL_PLACES + 4,\r\n half = new BigNumber('0.5');\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !c || !c[0]) {\r\n return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);\r\n }\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+valueOf(x));\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = coeffToString(c);\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(+n);\r\n e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new BigNumber(n);\r\n } else {\r\n r = new BigNumber(s + '');\r\n }\r\n\r\n // Check for zero.\r\n // r could be zero if MIN_EXP is changed after the this value was created.\r\n // This would cause a division by zero (x/t) and hence Infinity below, which would cause\r\n // coeffToString to throw.\r\n if (r.c[0]) {\r\n e = r.e;\r\n s = e + dp;\r\n if (s < 3) s = 0;\r\n\r\n // Newton-Raphson iteration.\r\n for (; ;) {\r\n t = r;\r\n r = half.times(t.plus(div(x, t, dp, 1)));\r\n\r\n if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {\r\n\r\n // The exponent of r may here be one less than the final result exponent,\r\n // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits\r\n // are indexed correctly.\r\n if (r.e < e) --s;\r\n n = n.slice(s - 3, s + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits\r\n // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the\r\n // iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the\r\n // exact result as the nines may infinitely repeat.\r\n if (!rep) {\r\n round(t, t.e + DECIMAL_PLACES + 2, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n dp += 4;\r\n s += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact\r\n // result. If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n round(r, r.e + DECIMAL_PLACES + 2, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in exponential notation and\r\n * rounded using ROUNDING_MODE to dp fixed decimal places.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toExponential = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp++;\r\n }\r\n return format(this, dp, rm, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounding\r\n * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',\r\n * but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toFixed = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp = dp + this.e + 1;\r\n }\r\n return format(this, dp, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounded\r\n * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties\r\n * of the format or FORMAT object (see BigNumber.set).\r\n *\r\n * The formatting object may contain some or all of the properties shown below.\r\n *\r\n * FORMAT = {\r\n * prefix: '',\r\n * groupSize: 3,\r\n * secondaryGroupSize: 0,\r\n * groupSeparator: ',',\r\n * decimalSeparator: '.',\r\n * fractionGroupSize: 0,\r\n * fractionGroupSeparator: '\\xA0', // non-breaking space\r\n * suffix: ''\r\n * };\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n * [format] {object} Formatting options. See FORMAT pbject above.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n * '[BigNumber Error] Argument not an object: {format}'\r\n */\r\n P.toFormat = function (dp, rm, format) {\r\n var str,\r\n x = this;\r\n\r\n if (format == null) {\r\n if (dp != null && rm && typeof rm == 'object') {\r\n format = rm;\r\n rm = null;\r\n } else if (dp && typeof dp == 'object') {\r\n format = dp;\r\n dp = rm = null;\r\n } else {\r\n format = FORMAT;\r\n }\r\n } else if (typeof format != 'object') {\r\n throw Error\r\n (bignumberError + 'Argument not an object: ' + format);\r\n }\r\n\r\n str = x.toFixed(dp, rm);\r\n\r\n if (x.c) {\r\n var i,\r\n arr = str.split('.'),\r\n g1 = +format.groupSize,\r\n g2 = +format.secondaryGroupSize,\r\n groupSeparator = format.groupSeparator || '',\r\n intPart = arr[0],\r\n fractionPart = arr[1],\r\n isNeg = x.s < 0,\r\n intDigits = isNeg ? intPart.slice(1) : intPart,\r\n len = intDigits.length;\r\n\r\n if (g2) i = g1, g1 = g2, g2 = i, len -= i;\r\n\r\n if (g1 > 0 && len > 0) {\r\n i = len % g1 || g1;\r\n intPart = intDigits.substr(0, i);\r\n for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);\r\n if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);\r\n if (isNeg) intPart = '-' + intPart;\r\n }\r\n\r\n str = fractionPart\r\n ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)\r\n ? fractionPart.replace(new RegExp('\\\\d{' + g2 + '}\\\\B', 'g'),\r\n '$&' + (format.fractionGroupSeparator || ''))\r\n : fractionPart)\r\n : intPart;\r\n }\r\n\r\n return (format.prefix || '') + str + (format.suffix || '');\r\n };\r\n\r\n\r\n /*\r\n * Return an array of two BigNumbers representing the value of this BigNumber as a simple\r\n * fraction with an integer numerator and an integer denominator.\r\n * The denominator will be a positive non-zero value less than or equal to the specified\r\n * maximum denominator. If a maximum denominator is not specified, the denominator will be\r\n * the lowest value necessary to represent the number exactly.\r\n *\r\n * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.\r\n *\r\n * '[BigNumber Error] Argument {not an integer|out of range} : {md}'\r\n */\r\n P.toFraction = function (md) {\r\n var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,\r\n x = this,\r\n xc = x.c;\r\n\r\n if (md != null) {\r\n n = new BigNumber(md);\r\n\r\n // Throw if md is less than one or is not an integer, unless it is Infinity.\r\n if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {\r\n throw Error\r\n (bignumberError + 'Argument ' +\r\n (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));\r\n }\r\n }\r\n\r\n if (!xc) return new BigNumber(x);\r\n\r\n d = new BigNumber(ONE);\r\n n1 = d0 = new BigNumber(ONE);\r\n d1 = n0 = new BigNumber(ONE);\r\n s = coeffToString(xc);\r\n\r\n // Determine initial denominator.\r\n // d is a power of 10 and the minimum max denominator that specifies the value exactly.\r\n e = d.e = s.length - x.e - 1;\r\n d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];\r\n md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;\r\n\r\n exp = MAX_EXP;\r\n MAX_EXP = 1 / 0;\r\n n = new BigNumber(s);\r\n\r\n // n0 = d1 = 0\r\n n0.c[0] = 0;\r\n\r\n for (; ;) {\r\n q = div(n, d, 0, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.comparedTo(md) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n n1 = n0.plus(q.times(d2 = n1));\r\n n0 = d2;\r\n d = n.minus(q.times(d2 = d));\r\n n = d2;\r\n }\r\n\r\n d2 = div(md.minus(d0), d1, 0, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n e = e * 2;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1\r\n r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(\r\n div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];\r\n\r\n MAX_EXP = exp;\r\n\r\n return r;\r\n };\r\n\r\n\r\n /*\r\n * Return the value of this BigNumber converted to a number primitive.\r\n */\r\n P.toNumber = function () {\r\n return +valueOf(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber rounded to sd significant digits\r\n * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits\r\n * necessary to represent the integer part of the value in fixed-point notation, then use\r\n * exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.toPrecision = function (sd, rm) {\r\n if (sd != null) intCheck(sd, 1, MAX);\r\n return format(this, sd, rm, 2);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in base b, or base 10 if b is\r\n * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and\r\n * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent\r\n * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than\r\n * TO_EXP_NEG, return exponential notation.\r\n *\r\n * [b] {number} Integer, 2 to ALPHABET.length inclusive.\r\n *\r\n * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n */\r\n P.toString = function (b) {\r\n var str,\r\n n = this,\r\n s = n.s,\r\n e = n.e;\r\n\r\n // Infinity or NaN?\r\n if (e === null) {\r\n if (s) {\r\n str = 'Infinity';\r\n if (s < 0) str = '-' + str;\r\n } else {\r\n str = 'NaN';\r\n }\r\n } else {\r\n if (b == null) {\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(coeffToString(n.c), e)\r\n : toFixedPoint(coeffToString(n.c), e, '0');\r\n } else if (b === 10) {\r\n n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);\r\n str = toFixedPoint(coeffToString(n.c), n.e, '0');\r\n } else {\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);\r\n }\r\n\r\n if (s < 0 && n.c[0]) str = '-' + str;\r\n }\r\n\r\n return str;\r\n };\r\n\r\n\r\n /*\r\n * Return as toString, but do not accept a base argument, and include the minus sign for\r\n * negative zero.\r\n */\r\n P.valueOf = P.toJSON = function () {\r\n return valueOf(this);\r\n };\r\n\r\n\r\n P._isBigNumber = true;\r\n\r\n if (configObject != null) BigNumber.set(configObject);\r\n\r\n return BigNumber;\r\n }\r\n\r\n\r\n // PRIVATE HELPER FUNCTIONS\r\n\r\n // These functions don't need access to variables,\r\n // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.\r\n\r\n\r\n function bitFloor(n) {\r\n var i = n | 0;\r\n return n > 0 || n === i ? i : i - 1;\r\n }\r\n\r\n\r\n // Return a coefficient array as a string of base 10 digits.\r\n function coeffToString(a) {\r\n var s, z,\r\n i = 1,\r\n j = a.length,\r\n r = a[0] + '';\r\n\r\n for (; i < j;) {\r\n s = a[i++] + '';\r\n z = LOG_BASE - s.length;\r\n for (; z--; s = '0' + s);\r\n r += s;\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (j = r.length; r.charCodeAt(--j) === 48;);\r\n\r\n return r.slice(0, j + 1 || 1);\r\n }\r\n\r\n\r\n // Compare the value of BigNumbers x and y.\r\n function compare(x, y) {\r\n var a, b,\r\n xc = x.c,\r\n yc = y.c,\r\n i = x.s,\r\n j = y.s,\r\n k = x.e,\r\n l = y.e;\r\n\r\n // Either NaN?\r\n if (!i || !j) return null;\r\n\r\n a = xc && !xc[0];\r\n b = yc && !yc[0];\r\n\r\n // Either zero?\r\n if (a || b) return a ? b ? 0 : -j : i;\r\n\r\n // Signs differ?\r\n if (i != j) return i;\r\n\r\n a = i < 0;\r\n b = k == l;\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;\r\n\r\n // Compare exponents.\r\n if (!b) return k > l ^ a ? 1 : -1;\r\n\r\n j = (k = xc.length) < (l = yc.length) ? k : l;\r\n\r\n // Compare digit by digit.\r\n for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;\r\n\r\n // Compare lengths.\r\n return k == l ? 0 : k > l ^ a ? 1 : -1;\r\n }\r\n\r\n\r\n /*\r\n * Check that n is a primitive number, an integer, and in range, otherwise throw.\r\n */\r\n function intCheck(n, min, max, name) {\r\n if (n < min || n > max || n !== mathfloor(n)) {\r\n throw Error\r\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\r\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\r\n : ' not a primitive number: ') + String(n));\r\n }\r\n }\r\n\r\n\r\n // Assumes finite n.\r\n function isOdd(n) {\r\n var k = n.c.length - 1;\r\n return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;\r\n }\r\n\r\n\r\n function toExponential(str, e) {\r\n return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +\r\n (e < 0 ? 'e' : 'e+') + e;\r\n }\r\n\r\n\r\n function toFixedPoint(str, e, z) {\r\n var len, zs;\r\n\r\n // Negative exponent?\r\n if (e < 0) {\r\n\r\n // Prepend zeros.\r\n for (zs = z + '.'; ++e; zs += z);\r\n str = zs + str;\r\n\r\n // Positive exponent\r\n } else {\r\n len = str.length;\r\n\r\n // Append zeros.\r\n if (++e > len) {\r\n for (zs = z, e -= len; --e; zs += z);\r\n str += zs;\r\n } else if (e < len) {\r\n str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n return str;\r\n }\r\n\r\n\r\n // EXPORT\r\n\r\n\r\n BigNumber = clone();\r\n BigNumber['default'] = BigNumber.BigNumber = BigNumber;\r\n\r\n // AMD.\r\n if (true) {\r\n !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return BigNumber; }).call(exports, __webpack_require__, exports, module),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\r\n\r\n // Node.js and other environments that support module.exports.\r\n } else {}\r\n})(this);\r\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/bignumber.js/bignumber.js?");
338
-
339
- /***/ }),
340
-
341
301
  /***/ "../../node_modules/bip39/src/_wordlists.js":
342
302
  /*!**************************************************!*\
343
303
  !*** ../../node_modules/bip39/src/_wordlists.js ***!
@@ -358,36 +318,6 @@ eval("var __webpack_unused_export__;\n/* provided dependency */ var Buffer = __w
358
318
 
359
319
  /***/ }),
360
320
 
361
- /***/ "../../node_modules/bs58/index.js":
362
- /*!****************************************!*\
363
- !*** ../../node_modules/bs58/index.js ***!
364
- \****************************************/
365
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
366
-
367
- eval("var basex = __webpack_require__(/*! base-x */ \"../../node_modules/base-x/src/index.js\")\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\nmodule.exports = basex(ALPHABET)\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/bs58/index.js?");
368
-
369
- /***/ }),
370
-
371
- /***/ "../../node_modules/bs58check/base.js":
372
- /*!********************************************!*\
373
- !*** ../../node_modules/bs58check/base.js ***!
374
- \********************************************/
375
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
376
-
377
- eval("\n\nvar base58 = __webpack_require__(/*! bs58 */ \"../../node_modules/bs58/index.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"../../node_modules/safe-buffer/index.js\").Buffer)\n\nmodule.exports = function (checksumFn) {\n // Encode a buffer as a base58-check encoded string\n function encode (payload) {\n var checksum = checksumFn(payload)\n\n return base58.encode(Buffer.concat([\n payload,\n checksum\n ], payload.length + 4))\n }\n\n function decodeRaw (buffer) {\n var payload = buffer.slice(0, -4)\n var checksum = buffer.slice(-4)\n var newChecksum = checksumFn(payload)\n\n if (checksum[0] ^ newChecksum[0] |\n checksum[1] ^ newChecksum[1] |\n checksum[2] ^ newChecksum[2] |\n checksum[3] ^ newChecksum[3]) return\n\n return payload\n }\n\n // Decode a base58-check encoded string to a buffer, no result if checksum is wrong\n function decodeUnsafe (string) {\n var buffer = base58.decodeUnsafe(string)\n if (!buffer) return\n\n return decodeRaw(buffer)\n }\n\n function decode (string) {\n var buffer = base58.decode(string)\n var payload = decodeRaw(buffer, checksumFn)\n if (!payload) throw new Error('Invalid checksum')\n return payload\n }\n\n return {\n encode: encode,\n decode: decode,\n decodeUnsafe: decodeUnsafe\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/bs58check/base.js?");
378
-
379
- /***/ }),
380
-
381
- /***/ "../../node_modules/bs58check/index.js":
382
- /*!*********************************************!*\
383
- !*** ../../node_modules/bs58check/index.js ***!
384
- \*********************************************/
385
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
386
-
387
- eval("\n\nvar createHash = __webpack_require__(/*! create-hash */ \"../../node_modules/create-hash/browser.js\")\nvar bs58checkBase = __webpack_require__(/*! ./base */ \"../../node_modules/bs58check/base.js\")\n\n// SHA256(SHA256(buffer))\nfunction sha256x2 (buffer) {\n var tmp = createHash('sha256').update(buffer).digest()\n return createHash('sha256').update(tmp).digest()\n}\n\nmodule.exports = bs58checkBase(sha256x2)\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/bs58check/index.js?");
388
-
389
- /***/ }),
390
-
391
321
  /***/ "../../node_modules/buffer/index.js":
392
322
  /*!******************************************!*\
393
323
  !*** ../../node_modules/buffer/index.js ***!
@@ -398,46 +328,6 @@ eval("/*!\n * The buffer module from node.js, for the browser.\n *\n * @author
398
328
 
399
329
  /***/ }),
400
330
 
401
- /***/ "../../node_modules/cashaddrjs-slp/src/base32.js":
402
- /*!*******************************************************!*\
403
- !*** ../../node_modules/cashaddrjs-slp/src/base32.js ***!
404
- \*******************************************************/
405
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
406
-
407
- eval("/**\n * @license\n * https://github.com/bitcoincashjs/cashaddr\n * Copyright (c) 2017-2018 Emilio Almansi\n * Distributed under the MIT software license, see the accompanying\n * file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n */\n\n\n\nvar validate = (__webpack_require__(/*! ./validation */ \"../../node_modules/cashaddrjs-slp/src/validation.js\").validate);\n\n/**\n * Base32 encoding and decoding.\n *\n * @module base32\n */\n\n/**\n * Charset containing the 32 symbols used in the base32 encoding.\n * @private\n */\nvar CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';\n\n/**\n * Inverted index mapping each symbol into its index within the charset.\n * @private\n */\nvar CHARSET_INVERSE_INDEX = {\n 'q': 0, 'p': 1, 'z': 2, 'r': 3, 'y': 4, '9': 5, 'x': 6, '8': 7,\n 'g': 8, 'f': 9, '2': 10, 't': 11, 'v': 12, 'd': 13, 'w': 14, '0': 15,\n 's': 16, '3': 17, 'j': 18, 'n': 19, '5': 20, '4': 21, 'k': 22, 'h': 23,\n 'c': 24, 'e': 25, '6': 26, 'm': 27, 'u': 28, 'a': 29, '7': 30, 'l': 31,\n};\n\n/**\n * Encodes the given array of 5-bit integers as a base32-encoded string.\n *\n * @static\n * @param {Uint8Array} data Array of integers between 0 and 31 inclusive.\n * @returns {string}\n * @throws {ValidationError}\n */\nfunction encode(data) {\n validate(data instanceof Uint8Array, 'Invalid data: ' + data + '.');\n var base32 = '';\n for (var i = 0; i < data.length; ++i) {\n var value = data[i];\n validate(0 <= value && value < 32, 'Invalid value: ' + value + '.');\n base32 += CHARSET[value];\n }\n return base32;\n}\n\n/**\n * Decodes the given base32-encoded string into an array of 5-bit integers.\n *\n * @static\n * @param {string} string\n * @returns {Uint8Array}\n * @throws {ValidationError}\n */\nfunction decode(string) {\n validate(typeof string === 'string', 'Invalid base32-encoded string: ' + string + '.');\n var data = new Uint8Array(string.length);\n for (var i = 0; i < string.length; ++i) {\n var value = string[i];\n validate(value in CHARSET_INVERSE_INDEX, 'Invalid value: ' + value + '.');\n data[i] = CHARSET_INVERSE_INDEX[value];\n }\n return data;\n}\n\nmodule.exports = {\n encode: encode,\n decode: decode,\n};\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/cashaddrjs-slp/src/base32.js?");
408
-
409
- /***/ }),
410
-
411
- /***/ "../../node_modules/cashaddrjs-slp/src/cashaddr.js":
412
- /*!*********************************************************!*\
413
- !*** ../../node_modules/cashaddrjs-slp/src/cashaddr.js ***!
414
- \*********************************************************/
415
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
416
-
417
- eval("/**\n * @license\n * https://github.com/bitcoincashjs/cashaddr\n * Copyright (c) 2017-2018 Emilio Almansi\n * Distributed under the MIT software license, see the accompanying\n * file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n */\n\n\n\nvar base32 = __webpack_require__(/*! ./base32 */ \"../../node_modules/cashaddrjs-slp/src/base32.js\");\nvar bigInt = __webpack_require__(/*! big-integer */ \"../../node_modules/big-integer/BigInteger.js\");\nvar convertBits = __webpack_require__(/*! ./convertBits */ \"../../node_modules/cashaddrjs-slp/src/convertBits.js\");\nvar validation = __webpack_require__(/*! ./validation */ \"../../node_modules/cashaddrjs-slp/src/validation.js\");\nvar validate = validation.validate;\n\n/**\n * Encoding and decoding of the new Cash Address format for Bitcoin Cash. <br />\n * Compliant with the original cashaddr specification:\n * {@link https://github.com/Bitcoin-UAHF/spec/blob/master/cashaddr.md}\n * @module cashaddr\n */\n\n/**\n * Encodes a hash from a given type into a Bitcoin Cash address with the given prefix.\n * \n * @static\n * @param {string} prefix Network prefix. E.g.: 'bitcoincash'.\n * @param {string} type Type of address to generate. Either 'P2PKH' or 'P2SH'.\n * @param {Uint8Array} hash Hash to encode represented as an array of 8-bit integers.\n * @returns {string}\n * @throws {ValidationError}\n */\nfunction encode(prefix, type, hash) {\n validate(typeof prefix === 'string' && isValidPrefix(prefix), 'Invalid prefix: ' + prefix + '.');\n validate(typeof type === 'string', 'Invalid type: ' + type + '.');\n validate(hash instanceof Uint8Array, 'Invalid hash: ' + hash + '.');\n var prefixData = concat(prefixToUint5Array(prefix), new Uint8Array(1));\n var versionByte = getTypeBits(type) + getHashSizeBits(hash);\n var payloadData = toUint5Array(concat(Uint8Array.of(versionByte), hash));\n var checksumData = concat(concat(prefixData, payloadData), new Uint8Array(8));\n var payload = concat(payloadData, checksumToUint5Array(polymod(checksumData)));\n return prefix + ':' + base32.encode(payload);\n}\n\n/**\n * Decodes the given address into its constituting prefix, type and hash. See [#encode()]{@link encode}.\n * \n * @static\n * @param {string} address Address to decode. E.g.: 'bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a'.\n * @returns {object}\n * @throws {ValidationError}\n */\nfunction decode(address) {\n validate(typeof address === 'string' && hasSingleCase(address), 'Invalid address: ' + address + '.');\n var pieces = address.toLowerCase().split(':');\n validate(pieces.length === 2, 'Missing prefix: ' + address + '.');\n var prefix = pieces[0];\n var payload = base32.decode(pieces[1]);\n validate(validChecksum(prefix, payload), 'Invalid checksum: ' + address + '.');\n var payloadData = fromUint5Array(payload.slice(0, -8));\n var versionByte = payloadData[0];\n var hash = payloadData.slice(1);\n validate(getHashSize(versionByte) === hash.length * 8, 'Invalid hash size: ' + address + '.');\n var type = getType(versionByte);\n return {\n prefix: prefix,\n type: type,\n hash: hash,\n };\n}\n\n/**\n * Error thrown when encoding or decoding fail due to invalid input.\n *\n * @constructor ValidationError\n * @param {string} message Error description.\n */\nvar ValidationError = validation.ValidationError;\n\n/**\n * Valid address prefixes.\n *\n * @private\n */\nvar VALID_PREFIXES = ['bitcoincash', 'bchtest', 'bchreg', 'simpleledger', 'slptest', 'slpreg'];\n\n/**\n * Checks whether a string is a valid prefix; ie., it has a single letter case\n * and is one of 'bitcoincash', 'bchtest', or 'bchreg'.\n *\n * @private\n * @param {string} prefix \n * @returns {boolean}\n */\nfunction isValidPrefix(prefix) {\n return hasSingleCase(prefix) && VALID_PREFIXES.indexOf(prefix.toLowerCase()) !== -1;\n}\n\n/**\n * Derives an array from the given prefix to be used in the computation\n * of the address' checksum.\n *\n * @private\n * @param {string} prefix Network prefix. E.g.: 'bitcoincash'. \n * @returns {Uint8Array}\n */\nfunction prefixToUint5Array(prefix) {\n var result = new Uint8Array(prefix.length);\n for (var i = 0; i < prefix.length; ++i) {\n result[i] = prefix[i].charCodeAt(0) & 31;\n }\n return result;\n}\n\n/**\n * Returns an array representation of the given checksum to be encoded\n * within the address' payload.\n *\n * @private\n * @param {BigInteger} checksum Computed checksum.\n * @returns {Uint8Array}\n */\nfunction checksumToUint5Array(checksum) {\n var result = new Uint8Array(8);\n for (var i = 0; i < 8; ++i) {\n result[7 - i] = checksum.and(31).toJSNumber();\n checksum = checksum.shiftRight(5);\n }\n return result;\n}\n\n/**\n * Returns the bit representation of the given type within the version\n * byte.\n *\n * @private\n * @param {string} type Address type. Either 'P2PKH' or 'P2SH'.\n * @returns {number}\n * @throws {ValidationError}\n */\nfunction getTypeBits(type) {\n switch (type) {\n case 'P2PKH':\n return 0;\n case 'P2SH':\n return 8;\n default:\n throw new ValidationError('Invalid type: ' + type + '.');\n }\n}\n\n/**\n * Retrieves the address type from its bit representation within the\n * version byte.\n *\n * @private\n * @param {number} versionByte\n * @returns {string}\n * @throws {ValidationError}\n */\nfunction getType(versionByte) {\n switch (versionByte & 120) {\n case 0:\n return 'P2PKH';\n case 8:\n return 'P2SH';\n default:\n throw new ValidationError('Invalid address type in version byte: ' + versionByte + '.');\n }\n}\n\n/**\n * Returns the bit representation of the length in bits of the given\n * hash within the version byte.\n *\n * @private\n * @param {Uint8Array} hash Hash to encode represented as an array of 8-bit integers.\n * @returns {number}\n * @throws {ValidationError}\n */\nfunction getHashSizeBits(hash) {\n switch (hash.length * 8) {\n case 160:\n return 0;\n case 192:\n return 1;\n case 224:\n return 2;\n case 256:\n return 3;\n case 320:\n return 4;\n case 384:\n return 5;\n case 448:\n return 6;\n case 512:\n return 7;\n default:\n throw new ValidationError('Invalid hash size: ' + hash.length + '.');\n }\n}\n\n/**\n * Retrieves the the length in bits of the encoded hash from its bit\n * representation within the version byte.\n *\n * @private\n * @param {number} versionByte\n * @returns {number}\n */\nfunction getHashSize(versionByte) {\n switch (versionByte & 7) {\n case 0:\n return 160;\n case 1:\n return 192;\n case 2:\n return 224;\n case 3:\n return 256;\n case 4:\n return 320;\n case 5:\n return 384;\n case 6:\n return 448;\n case 7:\n return 512;\n }\n}\n\n/**\n * Converts an array of 8-bit integers into an array of 5-bit integers,\n * right-padding with zeroes if necessary.\n *\n * @private\n * @param {Uint8Array} data\n * @returns {Uint8Array}\n */\nfunction toUint5Array(data) {\n return convertBits(data, 8, 5);\n}\n\n/**\n * Converts an array of 5-bit integers back into an array of 8-bit integers,\n * removing extra zeroes left from padding if necessary.\n * Throws a {@link ValidationError} if input is not a zero-padded array of 8-bit integers.\n *\n * @private\n * @param {Uint8Array} data\n * @returns {Uint8Array}\n * @throws {ValidationError}\n */\nfunction fromUint5Array(data) {\n return convertBits(data, 5, 8, true);\n}\n\n/**\n * Returns the concatenation a and b.\n *\n * @private\n * @param {Uint8Array} a \n * @param {Uint8Array} b \n * @returns {Uint8Array}\n * @throws {ValidationError}\n */\nfunction concat(a, b) {\n var ab = new Uint8Array(a.length + b.length);\n ab.set(a);\n ab.set(b, a.length);\n return ab;\n}\n\n/**\n * Computes a checksum from the given input data as specified for the CashAddr\n * format: https://github.com/Bitcoin-UAHF/spec/blob/master/cashaddr.md.\n *\n * @private\n * @param {Uint8Array} data Array of 5-bit integers over which the checksum is to be computed.\n * @returns {BigInteger}\n */\nfunction polymod(data) {\n var GENERATOR = [0x98f2bc8e61, 0x79b76d99e2, 0xf33e5fb3c4, 0xae2eabe2a8, 0x1e4f43e470];\n var checksum = bigInt(1);\n for (var i = 0; i < data.length; ++i) {\n var value = data[i];\n var topBits = checksum.shiftRight(35);\n checksum = checksum.and(0x07ffffffff).shiftLeft(5).xor(value);\n for (var j = 0; j < GENERATOR.length; ++j) {\n if (topBits.shiftRight(j).and(1).equals(1)) {\n checksum = checksum.xor(GENERATOR[j]);\n }\n }\n }\n return checksum.xor(1);\n}\n\n/**\n * Verify that the payload has not been corrupted by checking that the\n * checksum is valid.\n * \n * @private\n * @param {string} prefix Network prefix. E.g.: 'bitcoincash'.\n * @param {Uint8Array} payload Array of 5-bit integers containing the address' payload.\n * @returns {boolean}\n */\nfunction validChecksum(prefix, payload) {\n var prefixData = concat(prefixToUint5Array(prefix), new Uint8Array(1));\n var checksumData = concat(prefixData, payload);\n return polymod(checksumData).equals(0);\n}\n\n/**\n * Returns true if, and only if, the given string contains either uppercase\n * or lowercase letters, but not both.\n *\n * @private\n * @param {string} string Input string.\n * @returns {boolean}\n */\nfunction hasSingleCase(string) {\n return string === string.toLowerCase() || string === string.toUpperCase();\n}\n\nmodule.exports = {\n encode: encode,\n decode: decode,\n ValidationError: ValidationError,\n};\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/cashaddrjs-slp/src/cashaddr.js?");
418
-
419
- /***/ }),
420
-
421
- /***/ "../../node_modules/cashaddrjs-slp/src/convertBits.js":
422
- /*!************************************************************!*\
423
- !*** ../../node_modules/cashaddrjs-slp/src/convertBits.js ***!
424
- \************************************************************/
425
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
426
-
427
- eval("// Copyright (c) 2017-2018 Emilio Almansi\n// Copyright (c) 2017 Pieter Wuille\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n\n\nvar validate = (__webpack_require__(/*! ./validation */ \"../../node_modules/cashaddrjs-slp/src/validation.js\").validate);\n\n/**\n * Converts an array of integers made up of 'from' bits into an\n * array of integers made up of 'to' bits. The output array is\n * zero-padded if necessary, unless strict mode is true.\n * Throws a {@link ValidationError} if input is invalid.\n * Original by Pieter Wuille: https://github.com/sipa/bech32.\n *\n * @param {Uint8Array} data Array of integers made up of 'from' bits.\n * @param {number} from Length in bits of elements in the input array.\n * @param {number} to Length in bits of elements in the output array.\n * @param {bool} strictMode Require the conversion to be completed without padding.\n * @returns {Uint8Array}\n */\nmodule.exports = function(data, from, to, strictMode) {\n var length = strictMode\n ? Math.floor(data.length * from / to)\n : Math.ceil(data.length * from / to);\n var mask = (1 << to) - 1;\n var result = new Uint8Array(length);\n var index = 0;\n var accumulator = 0;\n var bits = 0;\n for (var i = 0; i < data.length; ++i) {\n var value = data[i];\n validate(0 <= value && (value >> from) === 0, 'Invalid value: ' + value + '.');\n accumulator = (accumulator << from) | value;\n bits += from;\n while (bits >= to) {\n bits -= to;\n result[index] = (accumulator >> bits) & mask;\n ++index;\n }\n }\n if (!strictMode) {\n if (bits > 0) {\n result[index] = (accumulator << (to - bits)) & mask;\n ++index;\n }\n } else {\n validate(\n bits < from && ((accumulator << (to - bits)) & mask) === 0,\n 'Input cannot be converted to ' + to + ' bits without padding, but strict mode was used.'\n );\n }\n return result;\n};\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/cashaddrjs-slp/src/convertBits.js?");
428
-
429
- /***/ }),
430
-
431
- /***/ "../../node_modules/cashaddrjs-slp/src/validation.js":
432
- /*!***********************************************************!*\
433
- !*** ../../node_modules/cashaddrjs-slp/src/validation.js ***!
434
- \***********************************************************/
435
- /***/ ((module) => {
436
-
437
- eval("/**\n * @license\n * https://github.com/bitcoincashjs/cashaddr\n * Copyright (c) 2017-2018 Emilio Almansi\n * Distributed under the MIT software license, see the accompanying\n * file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n */\n\n\n\n/**\n * Validation utility.\n *\n * @module validation\n */\n\n/**\n * Error thrown when encoding or decoding fail due to invalid input.\n *\n * @constructor ValidationError\n * @param {string} message Error description.\n */\nfunction ValidationError(message) {\n var error = new Error();\n this.name = error.name = 'ValidationError';\n this.message = error.message = message;\n this.stack = error.stack;\n}\n\nValidationError.prototype = Object.create(Error.prototype);\n\n/**\n * Validates a given condition, throwing a {@link ValidationError} if\n * the given condition does not hold.\n *\n * @static\n * @param {boolean} condition Condition to validate.\n * @param {string} message Error message in case the condition does not hold.\n */\nfunction validate(condition, message) {\n if (!condition) {\n throw new ValidationError(message);\n }\n}\n\nmodule.exports = {\n ValidationError: ValidationError,\n validate: validate,\n};\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/cashaddrjs-slp/src/validation.js?");
438
-
439
- /***/ }),
440
-
441
331
  /***/ "../../node_modules/cipher-base/index.js":
442
332
  /*!***********************************************!*\
443
333
  !*** ../../node_modules/cipher-base/index.js ***!
@@ -908,16 +798,6 @@ eval("var inherits = __webpack_require__(/*! inherits */ \"../../node_modules/in
908
798
 
909
799
  /***/ }),
910
800
 
911
- /***/ "../../node_modules/slp-parser/dist/index.js":
912
- /*!***************************************************!*\
913
- !*** ../../node_modules/slp-parser/dist/index.js ***!
914
- \***************************************************/
915
- /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
916
-
917
- eval("/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\")[\"Buffer\"];\n\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst bignumber_js_1 = __importDefault(__webpack_require__(/*! bignumber.js */ \"../../node_modules/bignumber.js/bignumber.js\"));\nexports.BN = bignumber_js_1.default;\n;\n;\n;\n;\n;\nexports.parseSLP = (scriptpubkey) => {\n if (typeof scriptpubkey === \"string\") {\n scriptpubkey = Buffer.from(scriptpubkey, 'hex');\n }\n let it = 0; // position in itObj\n let itObj = scriptpubkey; // object it refers to\n const OP_0 = 0x00;\n const OP_16 = 0x60;\n const OP_RETURN = 0x6a;\n const OP_PUSHDATA1 = 0x4c;\n const OP_PUSHDATA2 = 0x4d;\n const OP_PUSHDATA4 = 0x4e;\n const PARSE_CHECK = (v, str) => {\n if (v) {\n throw Error(str);\n }\n };\n const extractU8 = () => {\n const r = itObj.readUInt8(it);\n it += 1;\n return new bignumber_js_1.default(r);\n };\n const extractU16 = () => {\n const r = itObj.readUInt16LE(it);\n it += 2;\n return new bignumber_js_1.default(r);\n };\n const extractU32 = () => {\n const r = itObj.readUInt32LE(it);\n it += 4;\n return new bignumber_js_1.default(r);\n };\n const extractU64 = () => {\n const r1 = itObj.readUInt32LE(it);\n it += 4;\n const r2 = itObj.readUInt32LE(it);\n it += 4;\n return new bignumber_js_1.default(r2).multipliedBy(Math.pow(2, 32)).plus(r1);\n };\n PARSE_CHECK(itObj.length === 0, \"scriptpubkey cannot be empty\");\n PARSE_CHECK(itObj[it] !== OP_RETURN, \"scriptpubkey not op_return\");\n PARSE_CHECK(itObj.length < 10, \"scriptpubkey too small\"); // TODO what is correct minimum size?\n ++it;\n const extractPushdata = () => {\n if (it === itObj.length) {\n return -1;\n }\n const cnt = extractU8().toNumber();\n if (cnt > OP_0 && cnt < OP_PUSHDATA1) {\n if (it + cnt > itObj.length) {\n --it;\n return -1;\n }\n return cnt;\n }\n else if (cnt === OP_PUSHDATA1) {\n if (it + 1 >= itObj.length) {\n --it;\n return -1;\n }\n return extractU8().toNumber();\n }\n else if (cnt === OP_PUSHDATA2) {\n if (it + 2 >= itObj.length) {\n --it;\n return -1;\n }\n return extractU16().toNumber();\n }\n else if (cnt === OP_PUSHDATA4) {\n if (it + 4 >= itObj.length) {\n --it;\n return -1;\n }\n return extractU32().toNumber();\n }\n // other opcodes not allowed\n --it;\n return -1;\n };\n const bufferToBN = () => {\n if (itObj.length === 1)\n return extractU8();\n if (itObj.length === 2)\n return extractU16();\n if (itObj.length === 4)\n return extractU32();\n if (itObj.length === 8)\n return extractU64();\n throw new Error('extraction of number from buffer failed');\n };\n const checkValidTokenId = (tokenId) => tokenId.length === 32;\n const chunks = [];\n for (let len = extractPushdata(); len >= 0; len = extractPushdata()) {\n const buf = itObj.slice(it, it + len);\n PARSE_CHECK(it + len > itObj.length, \"pushdata data extraction failed\");\n it += len;\n chunks.push(buf);\n if (chunks.length === 1) {\n const lokadIdStr = chunks[0];\n PARSE_CHECK(lokadIdStr.length !== 4, \"lokad id wrong size\");\n PARSE_CHECK(lokadIdStr[0] !== 'S'.charCodeAt(0)\n || lokadIdStr[1] !== 'L'.charCodeAt(0)\n || lokadIdStr[2] !== 'P'.charCodeAt(0)\n || lokadIdStr[3] !== 0x00, \"SLP not in first chunk\");\n }\n }\n PARSE_CHECK(it !== itObj.length, \"trailing data\");\n PARSE_CHECK(chunks.length === 0, \"chunks empty\");\n let cit = 0;\n const CHECK_NEXT = () => {\n ++cit;\n PARSE_CHECK(cit === chunks.length, \"parsing ended early\");\n it = 0;\n itObj = chunks[cit];\n };\n CHECK_NEXT(); // for quick exit check done above\n const tokenTypeBuf = itObj.reverse();\n PARSE_CHECK(tokenTypeBuf.length !== 1 && tokenTypeBuf.length !== 2, \"token_type string length must be 1 or 2\");\n const tokenType = bufferToBN().toNumber();\n PARSE_CHECK(![0x01, 0x41, 0x81].includes(tokenType), \"token_type not token-type1, nft1-group, or nft1-child\");\n CHECK_NEXT();\n const transactionType = itObj.toString();\n if (transactionType === 'GENESIS') {\n PARSE_CHECK(chunks.length !== 10, \"wrong number of chunks\");\n CHECK_NEXT();\n const ticker = itObj;\n CHECK_NEXT();\n const name = itObj;\n CHECK_NEXT();\n const documentUri = itObj;\n CHECK_NEXT();\n const documentHash = itObj;\n PARSE_CHECK(!(documentHash.length === 0 || documentHash.length === 32), \"document_hash must be size 0 or 32\");\n CHECK_NEXT();\n const decimalsBuf = itObj;\n PARSE_CHECK(decimalsBuf.length !== 1, \"decimals string length must be 1\");\n const decimals = bufferToBN().toNumber();\n PARSE_CHECK(decimals > 9, \"decimals bigger than 9\");\n CHECK_NEXT();\n const mintBatonVoutBuf = itObj;\n let mintBatonVout = 0;\n PARSE_CHECK(mintBatonVoutBuf.length >= 2, \"mint_baton_vout string length must be 0 or 1\");\n if (mintBatonVoutBuf.length > 0) {\n mintBatonVout = bufferToBN().toNumber();\n PARSE_CHECK(mintBatonVout < 2, \"mint_baton_vout must be at least 2\");\n }\n CHECK_NEXT();\n const qtyBuf = itObj.reverse();\n PARSE_CHECK(qtyBuf.length !== 8, \"initial_qty must be provided as an 8-byte buffer\");\n const qty = bufferToBN();\n if (tokenType === 0x41) {\n PARSE_CHECK(decimals !== 0, \"NFT1 child token must have divisibility set to 0 decimal places\");\n PARSE_CHECK(mintBatonVout !== 0, \"NFT1 child token must not have a minting baton\");\n PARSE_CHECK(!qty.isEqualTo(1), \"NFT1 child token must have quantity of 1\");\n }\n const actionData = {\n ticker,\n name,\n documentUri,\n documentHash,\n decimals,\n mintBatonVout,\n qty\n };\n return {\n tokenType,\n transactionType,\n data: actionData\n };\n }\n else if (transactionType === \"MINT\") {\n PARSE_CHECK(tokenType === 0x41, \"NFT1 Child cannot have MINT transaction type.\");\n PARSE_CHECK(chunks.length !== 6, \"wrong number of chunks\");\n CHECK_NEXT();\n const tokenId = itObj;\n PARSE_CHECK(!checkValidTokenId(tokenId), \"tokenId invalid size\");\n CHECK_NEXT();\n const mintBatonVoutBuf = itObj;\n let mintBatonVout = 0;\n PARSE_CHECK(mintBatonVoutBuf.length >= 2, \"mint_baton_vout string length must be 0 or 1\");\n if (mintBatonVoutBuf.length > 0) {\n mintBatonVout = bufferToBN().toNumber();\n PARSE_CHECK(mintBatonVout < 2, \"mint_baton_vout must be at least 2\");\n }\n CHECK_NEXT();\n const additionalQtyBuf = itObj.reverse();\n PARSE_CHECK(additionalQtyBuf.length !== 8, \"additional_qty must be provided as an 8-byte buffer\");\n const qty = bufferToBN();\n const actionData = {\n tokenId,\n mintBatonVout,\n qty\n };\n return {\n tokenType,\n transactionType,\n data: actionData\n };\n }\n else if (transactionType === \"SEND\") {\n PARSE_CHECK(chunks.length < 4, \"wrong number of chunks\");\n CHECK_NEXT();\n const tokenId = itObj;\n PARSE_CHECK(!checkValidTokenId(tokenId), \"tokenId invalid size\");\n CHECK_NEXT();\n const amounts = [];\n while (cit !== chunks.length) {\n const amountBuf = itObj.reverse();\n PARSE_CHECK(amountBuf.length !== 8, \"amount string size not 8 bytes\");\n const value = bufferToBN();\n amounts.push(value);\n ++cit;\n itObj = chunks[cit];\n it = 0;\n }\n PARSE_CHECK(amounts.length === 0, \"token_amounts size is 0\");\n PARSE_CHECK(amounts.length > 19, \"token_amounts size is greater than 19\");\n const actionData = {\n tokenId,\n amounts\n };\n return {\n tokenType,\n transactionType,\n data: actionData\n };\n }\n else {\n PARSE_CHECK(true, \"unknown action type\");\n }\n // unreachable code\n return {\n tokenType,\n transactionType,\n data: {}\n };\n};\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/slp-parser/dist/index.js?");
918
-
919
- /***/ }),
920
-
921
801
  /***/ "../../node_modules/stream-browserify/index.js":
922
802
  /*!*****************************************************!*\
923
803
  !*** ../../node_modules/stream-browserify/index.js ***!
@@ -988,23 +868,13 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
988
868
 
989
869
  /***/ }),
990
870
 
991
- /***/ "./src/db/SqlProvider.ts":
992
- /*!*******************************!*\
993
- !*** ./src/db/SqlProvider.ts ***!
994
- \*******************************/
995
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
996
-
997
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ SqlProvider)\n/* harmony export */ });\n/* harmony import */ var _webhook_Webhook_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../webhook/Webhook.js */ \"./src/webhook/Webhook.ts\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/bchaddr.js */ \"../../node_modules/bchaddrjs-slp/src/bchaddr.js\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./util.js */ \"./src/db/util.ts\");\n/* harmony import */ var parse_database_url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! parse-database-url */ \"?a3a2\");\n/* harmony import */ var parse_database_url__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(parse_database_url__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var pg__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! pg */ \"?0b82\");\n/* harmony import */ var pg__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(pg__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var pg_format__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! pg-format */ \"?28a0\");\n/* harmony import */ var pg_format__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(pg_format__WEBPACK_IMPORTED_MODULE_2__);\n\n\n\n\n\n\nclass SqlProvider {\n constructor(walletTable) {\n this.webhookTable = \"webhook\";\n this.faucetQueueTable = \"faucet_queue\";\n this.isInit = false;\n this.walletTable = walletTable ? walletTable : \"wallet\";\n if (!process.env.DATABASE_URL) {\n throw new Error(\"Named wallets and webhooks require a postgres DATABASE_URL environment variable to be set\");\n }\n let dbConfig = parse_database_url__WEBPACK_IMPORTED_MODULE_0___default()(process.env.DATABASE_URL);\n let ssl = (0,_util_js__WEBPACK_IMPORTED_MODULE_3__.getSslConfig)();\n if (ssl) {\n dbConfig.ssl = ssl;\n }\n this.config = dbConfig;\n const Pool = (pg__WEBPACK_IMPORTED_MODULE_1___default().Pool);\n this.db = new Pool(dbConfig);\n this.formatter = (pg_format__WEBPACK_IMPORTED_MODULE_2___default());\n }\n getConfig() {\n return this.config;\n }\n async init() {\n if (!this.isInit) {\n this.isInit = true;\n await this.db;\n await this.formatter;\n let createWalletTable = this.formatter(\"CREATE TABLE IF NOT EXISTS %I (id SERIAL, name TEXT PRIMARY KEY, wallet TEXT );\", this.walletTable);\n const resWallet = await this.db.query(createWalletTable);\n let createWebhookTable = this.formatter(\"CREATE TABLE IF NOT EXISTS %I (\" +\n \"id SERIAL PRIMARY KEY,\" +\n \"cashaddr TEXT,\" +\n \"type TEXT,\" +\n \"recurrence TEXT,\" +\n \"url TEXT,\" +\n \"status TEXT,\" +\n \"tx_seen JSON,\" +\n \"last_height INTEGER,\" +\n \"token_id TEXT,\" +\n \"expires_at TIMESTAMPTZ\" +\n \");\", this.webhookTable);\n const resWebhook = await this.db.query(createWebhookTable);\n let createFaucetQueueTable = this.formatter(\"CREATE TABLE IF NOT EXISTS %I (\" +\n \"id SERIAL PRIMARY KEY,\" +\n \"address TEXT,\" +\n \"token TEXT,\" +\n \"value TEXT\" +\n \");\", this.faucetQueueTable);\n const resFaucetQueue = await this.db.query(createFaucetQueueTable);\n if (!resWallet || !resWebhook || !resFaucetQueue)\n throw new Error(\"Failed to init SqlProvider\");\n }\n return this;\n }\n async close() {\n await this.db.end();\n return this;\n }\n getInfo() {\n return this.info;\n }\n async addWallet(name, walletId) {\n let text = this.formatter(\"INSERT into %I (name,wallet) VALUES ($1, $2);\", this.walletTable);\n return await this.db.query(text, [name, walletId]);\n }\n async getWallets() {\n let text = this.formatter(\"SELECT * FROM %I;\", this.walletTable);\n let result = await this.db.query(text);\n if (result) {\n const WalletArray = await Promise.all(result.rows.map(async (obj) => {\n return obj;\n }));\n return WalletArray;\n }\n else {\n return [];\n }\n }\n async getWallet(name) {\n let text = this.formatter(\"SELECT * FROM %I WHERE name = $1;\", this.walletTable);\n let result = await this.db.query(text, [name]);\n let w = result.rows[0];\n return w;\n }\n async updateWallet(name, walletId) {\n let text = this.formatter(\"UPDATE %I SET wallet = $1 WHERE name = $2;\", this.walletTable);\n await this.db.query(text, [walletId, name]);\n }\n async walletExists(name) {\n return (await this.getWallet(name)) !== undefined;\n }\n async webhookFromDb(hook) {\n // map tokenId field from postgres\n hook.tokenId = hook.token_id;\n delete hook.token_id;\n if (hook.type.indexOf(\"slp\") === 0) {\n const { WebhookSlp } = await Promise.resolve(/*! import() */).then(__webpack_require__.bind(__webpack_require__, /*! ../webhook/WebhookSlp.js */ \"./src/webhook/WebhookSlp.ts\"));\n return new WebhookSlp(hook);\n }\n else if ((0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_4__.isCashAddress)(hook.cashaddr)) {\n const { WebhookBch } = await Promise.resolve(/*! import() */).then(__webpack_require__.bind(__webpack_require__, /*! ../webhook/WebhookBch.js */ \"./src/webhook/WebhookBch.ts\"));\n return new WebhookBch(hook);\n }\n throw new Error(`Unsupported or incorrect hook address ${hook.cashaddr}`);\n }\n async addWebhook(params) {\n // init db if it was not, useful for external api calls\n await this.init();\n params.type = params.type || _webhook_Webhook_js__WEBPACK_IMPORTED_MODULE_5__.WebhookType.transactionInOut;\n params.recurrence = params.recurrence || _webhook_Webhook_js__WEBPACK_IMPORTED_MODULE_5__.WebhookRecurrence.once;\n const expireTimeout = Number(process.env.WEBHOOK_EXPIRE_TIMEOUT_SECONDS) || 86400;\n params.duration_sec = params.duration_sec || expireTimeout;\n params.duration_sec =\n params.duration_sec > expireTimeout ? expireTimeout : params.duration_sec;\n params.tokenId = params.tokenId || \"\";\n if (params.type.indexOf(\"slp\") === 0 && !params.tokenId) {\n throw new Error(\"'tokenId' parameter is required for SLP webhooks\");\n }\n const expires_at = new Date(new Date().getTime() + params.duration_sec * 1000);\n let text = this.formatter(\"INSERT into %I (cashaddr,type,recurrence,url,status,tx_seen,last_height,token_id,expires_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *;\", this.webhookTable);\n const result = await this.db.query(text, [\n params.cashaddr,\n params.type,\n params.recurrence,\n params.url,\n \"\",\n \"[]\",\n 0,\n params.tokenId,\n expires_at.toISOString(),\n ]);\n const hook = await this.webhookFromDb(result.rows[0]);\n hook.db = this;\n return hook;\n }\n async getWebhooks() {\n let text = this.formatter(\"SELECT * FROM %I;\", this.webhookTable);\n let result = await this.db.query(text);\n if (result) {\n const WebhookArray = await Promise.all(result.rows.map(async (obj) => {\n obj = await this.webhookFromDb(obj);\n obj.db = this;\n return obj;\n }));\n return WebhookArray;\n }\n else {\n return [];\n }\n }\n async getWebhook(id) {\n const text = this.formatter(\"SELECT * FROM %I WHERE id = $1;\", this.webhookTable);\n const result = await this.db.query(text, [id]);\n let hook = result.rows[0];\n if (hook) {\n hook = this.webhookFromDb(hook);\n hook.db = this;\n }\n return hook;\n }\n async setWebhookStatus(id, status) {\n let text = this.formatter(\"UPDATE %I SET status = $1 WHERE id = $2;\", this.webhookTable);\n await this.db.query(text, [status, id]);\n }\n async setWebhookSeenTxLastHeight(id, tx_seen, last_height) {\n let text = this.formatter(\"UPDATE %I SET tx_seen = $1, last_height = $2 WHERE id = $3;\", this.webhookTable);\n await this.db.query(text, [JSON.stringify(tx_seen), last_height, id]);\n }\n async deleteWebhook(id) {\n let text = this.formatter(\"DELETE FROM %I WHERE id = $1;\", this.webhookTable);\n await this.db.query(text, [id]);\n }\n async clearWebhooks() {\n let text = this.formatter(\"DELETE FROM %I;\", this.webhookTable);\n await this.db.query(text);\n }\n async addFaucetQueueItem(address, tokenId, value) {\n let text = this.formatter(\"INSERT into %I (address,token,value) VALUES ($1, $2, $3);\", this.faucetQueueTable);\n return await this.db.query(text, [address, tokenId, value]);\n }\n async getFaucetQueue() {\n let text = this.formatter(\"SELECT * FROM %I;\", this.faucetQueueTable);\n let result = await this.db.query(text);\n if (result) {\n const FaucetQueueItemArray = await Promise.all(result.rows.map(async (obj) => {\n return obj;\n }));\n return FaucetQueueItemArray;\n }\n else {\n return [];\n }\n }\n async deleteFaucetQueueItems(items) {\n const ids = items.map((val) => val.id);\n let text = this.formatter(\"DELETE FROM %I WHERE id IN (%L);\", this.faucetQueueTable, ids);\n let result = await this.db.query(text);\n return result;\n }\n async beginTransaction() {\n return await this.db.query(\"BEGIN\");\n }\n async commitTransaction() {\n return await this.db.query(\"COMMIT\");\n }\n async rollbackTransaction() {\n return await this.db.query(\"ROLLBACK\");\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/SqlProvider.ts?");
998
-
999
- /***/ }),
1000
-
1001
871
  /***/ "./src/db/getStorageProvider.ts":
1002
872
  /*!**************************************!*\
1003
873
  !*** ./src/db/getStorageProvider.ts ***!
1004
874
  \**************************************/
1005
875
  /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1006
876
 
1007
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getStorageProvider\": () => (/* binding */ getStorageProvider)\n/* harmony export */ });\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./IndexedDBProvider.js */ \"./src/db/IndexedDBProvider.ts\");\n/* harmony import */ var _SqlProvider_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./SqlProvider.js */ \"./src/db/SqlProvider.ts\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util.js */ \"./src/db/util.ts\");\n\n\n\n\nfunction getStorageProvider(dbName) {\n if ((0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__.getRuntimePlatform)() !== \"node\" && (0,_util_js__WEBPACK_IMPORTED_MODULE_1__.indexedDbIsAvailable)()) {\n return new _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"](dbName);\n }\n else {\n if (\"DATABASE_URL\" in process.env) {\n return new _SqlProvider_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](dbName);\n }\n else {\n console.warn(\"DATABASE_URL was not configured, storage unavailable\");\n return;\n }\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/getStorageProvider.ts?");
877
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getStorageProvider\": () => (/* binding */ getStorageProvider)\n/* harmony export */ });\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./IndexedDBProvider.js */ \"./src/db/IndexedDBProvider.ts\");\n/* harmony import */ var _SqlProvider_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SqlProvider.js */ \"?7652\");\n/* harmony import */ var _SqlProvider_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_SqlProvider_js__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util.js */ \"./src/db/util.ts\");\n\n\n\n\nfunction getStorageProvider(dbName) {\n if ((0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_1__.getRuntimePlatform)() !== \"node\" && (0,_util_js__WEBPACK_IMPORTED_MODULE_2__.indexedDbIsAvailable)()) {\n return new _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](dbName);\n }\n else {\n if (\"DATABASE_URL\" in process.env) {\n return new (_SqlProvider_js__WEBPACK_IMPORTED_MODULE_0___default())(dbName);\n }\n else {\n console.warn(\"DATABASE_URL was not configured, storage unavailable\");\n return;\n }\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/getStorageProvider.ts?");
1008
878
 
1009
879
  /***/ }),
1010
880
 
@@ -1014,7 +884,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
1014
884
  \*************************/
1015
885
  /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1016
886
 
1017
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"IndexedDBProvider\": () => (/* reexport safe */ _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"]),\n/* harmony export */ \"SqlProvider\": () => (/* reexport safe */ _SqlProvider_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])\n/* harmony export */ });\n/* harmony import */ var _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./IndexedDBProvider.js */ \"./src/db/IndexedDBProvider.ts\");\n/* harmony import */ var _SqlProvider_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SqlProvider.js */ \"./src/db/SqlProvider.ts\");\n\n\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/index.ts?");
887
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"IndexedDBProvider\": () => (/* reexport safe */ _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"]),\n/* harmony export */ \"SqlProvider\": () => (/* reexport default from dynamic */ _SqlProvider_js__WEBPACK_IMPORTED_MODULE_1___default.a)\n/* harmony export */ });\n/* harmony import */ var _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./IndexedDBProvider.js */ \"./src/db/IndexedDBProvider.ts\");\n/* harmony import */ var _SqlProvider_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SqlProvider.js */ \"?7652\");\n/* harmony import */ var _SqlProvider_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_SqlProvider_js__WEBPACK_IMPORTED_MODULE_1__);\n\n\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/index.ts?");
1018
888
 
1019
889
  /***/ }),
1020
890
 
@@ -1024,7 +894,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
1024
894
  \************************/
1025
895
  /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1026
896
 
1027
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getSslConfig\": () => (/* binding */ getSslConfig),\n/* harmony export */ \"indexedDbIsAvailable\": () => (/* binding */ indexedDbIsAvailable)\n/* harmony export */ });\n/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\")[\"Buffer\"];\nfunction indexedDbIsAvailable() {\n return \"indexedDB\" in globalThis;\n}\nfunction getSslConfig() {\n const ca = process.env.DATABASE_SSL_CA\n ? Buffer.from(process.env.DATABASE_SSL_CA, \"base64\").toString(\"ascii\")\n : undefined;\n const key = process.env.DATABASE_SSL_KEY\n ? Buffer.from(process.env.DATABASE_SSL_KEY, \"base64\").toString(\"ascii\")\n : undefined;\n const cert = process.env.DATABASE_SSL_CERT\n ? Buffer.from(process.env.DATABASE_SSL_CERT, \"base64\").toString(\"ascii\")\n : undefined;\n let ssl = {\n rejectUnauthorized: process.env.DATABASE_SSL_REJECT_UNAUTHORIZED == \"false\" ? false : true,\n ca: ca,\n key: key,\n cert: cert,\n };\n if (ssl.ca || ssl.cert || ssl.key) {\n return ssl;\n }\n else {\n return;\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/util.ts?");
897
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"indexedDbIsAvailable\": () => (/* binding */ indexedDbIsAvailable)\n/* harmony export */ });\n/* unused harmony export getSslConfig */\n/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\")[\"Buffer\"];\nfunction indexedDbIsAvailable() {\n return \"indexedDB\" in globalThis;\n}\nfunction getSslConfig() {\n const ca = process.env.DATABASE_SSL_CA\n ? Buffer.from(process.env.DATABASE_SSL_CA, \"base64\").toString(\"ascii\")\n : undefined;\n const key = process.env.DATABASE_SSL_KEY\n ? Buffer.from(process.env.DATABASE_SSL_KEY, \"base64\").toString(\"ascii\")\n : undefined;\n const cert = process.env.DATABASE_SSL_CERT\n ? Buffer.from(process.env.DATABASE_SSL_CERT, \"base64\").toString(\"ascii\")\n : undefined;\n let ssl = {\n rejectUnauthorized: process.env.DATABASE_SSL_REJECT_UNAUTHORIZED == \"false\" ? false : true,\n ca: ca,\n key: key,\n cert: cert,\n };\n if (ssl.ca || ssl.cert || ssl.key) {\n return ssl;\n }\n else {\n return;\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/util.ts?");
1028
898
 
1029
899
  /***/ }),
1030
900
 
@@ -1054,7 +924,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1054
924
  \**********************/
1055
925
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1056
926
 
1057
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* reexport safe */ _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_6__.BCMR),\n/* harmony export */ \"BalanceResponse\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.BalanceResponse),\n/* harmony export */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_9__.BaseWallet),\n/* harmony export */ \"BigNumber\": () => (/* reexport safe */ _slp_index_js__WEBPACK_IMPORTED_MODULE_2__.BigNumber),\n/* harmony export */ \"CONST\": () => (/* reexport module object */ _constant_js__WEBPACK_IMPORTED_MODULE_20__),\n/* harmony export */ \"Config\": () => (/* reexport safe */ _config_js__WEBPACK_IMPORTED_MODULE_13__.Config),\n/* harmony export */ \"Connection\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_7__.Connection),\n/* harmony export */ \"DefaultProvider\": () => (/* reexport safe */ _network_configuration_js__WEBPACK_IMPORTED_MODULE_12__.DefaultProvider),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_7__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.ExchangeRate),\n/* harmony export */ \"GsppProvider\": () => (/* reexport safe */ _slp_index_js__WEBPACK_IMPORTED_MODULE_2__.GsppProvider),\n/* harmony export */ \"IndexedDBProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_0__.IndexedDBProvider),\n/* harmony export */ \"Mainnet\": () => (/* reexport module object */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__),\n/* harmony export */ \"NFTCapability\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_21__.NFTCapability),\n/* harmony export */ \"Network\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_21__.Network),\n/* harmony export */ \"NetworkType\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_14__.NetworkType),\n/* harmony export */ \"OpReturnData\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__.OpReturnData),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__.RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__.RegTestWifWallet),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.RuntimePlatform),\n/* harmony export */ \"SendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__.SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__.SendResponse),\n/* harmony export */ \"SignedMessage\": () => (/* reexport safe */ _message_signed_js__WEBPACK_IMPORTED_MODULE_8__.SignedMessage),\n/* harmony export */ \"SlpDbProvider\": () => (/* reexport safe */ _slp_index_js__WEBPACK_IMPORTED_MODULE_2__.SlpDbProvider),\n/* harmony export */ \"SlpTokenType\": () => (/* reexport safe */ _slp_index_js__WEBPACK_IMPORTED_MODULE_2__.SlpTokenType),\n/* harmony export */ \"SqlProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_0__.SqlProvider),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__.TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__.TestNetWifWallet),\n/* harmony export */ \"TokenBurnRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__.TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__.TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__.TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__.TokenSendRequest),\n/* harmony export */ \"UnitEnum\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_14__.UnitEnum),\n/* harmony export */ \"Wallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__.Wallet),\n/* harmony export */ \"WalletTypeEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_15__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__.WatchWallet),\n/* harmony export */ \"Webhook\": () => (/* reexport safe */ _webhook_index_js__WEBPACK_IMPORTED_MODULE_5__.Webhook),\n/* harmony export */ \"WebhookBch\": () => (/* reexport safe */ _webhook_index_js__WEBPACK_IMPORTED_MODULE_5__.WebhookBch),\n/* harmony export */ \"WebhookRecurrence\": () => (/* reexport safe */ _webhook_index_js__WEBPACK_IMPORTED_MODULE_5__.WebhookRecurrence),\n/* harmony export */ \"WebhookSlp\": () => (/* reexport safe */ _webhook_index_js__WEBPACK_IMPORTED_MODULE_5__.WebhookSlp),\n/* harmony export */ \"WebhookType\": () => (/* reexport safe */ _webhook_index_js__WEBPACK_IMPORTED_MODULE_5__.WebhookType),\n/* harmony export */ \"WebhookWorker\": () => (/* reexport safe */ _webhook_index_js__WEBPACK_IMPORTED_MODULE_5__.WebhookWorker),\n/* harmony export */ \"WifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__.WifWallet),\n/* harmony export */ \"XPubKey\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__.XPubKey),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.convert),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.convertObject),\n/* harmony export */ \"createSlpWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__.createSlpWallet),\n/* harmony export */ \"createSlpWalletResponse\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__.createSlpWalletResponse),\n/* harmony export */ \"createWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__.createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__.createWalletResponse),\n/* harmony export */ \"cube\": () => (/* binding */ cube),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.derivedNetwork),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_7__.disconnectProviders),\n/* harmony export */ \"expect\": () => (/* reexport safe */ _test_expect_js__WEBPACK_IMPORTED_MODULE_3__.expect),\n/* harmony export */ \"fromUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__.fromUtxoId),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_7__.getNetworkProvider),\n/* harmony export */ \"getRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.getRandomInt),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.getUsdRate),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.hexToBin),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_7__.initProviders),\n/* harmony export */ \"isCashAddress\": () => (/* reexport safe */ _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_22__.isCashAddress),\n/* harmony export */ \"isSlpAddress\": () => (/* reexport safe */ _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_22__.isSlpAddress),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_22__.isValidAddress),\n/* harmony export */ \"libauth\": () => (/* reexport module object */ _libauth_js__WEBPACK_IMPORTED_MODULE_18__),\n/* harmony export */ \"mine\": () => (/* reexport safe */ _mine_index_js__WEBPACK_IMPORTED_MODULE_1__.mine),\n/* harmony export */ \"namedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__.namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__.namedWalletExists),\n/* harmony export */ \"qrAddress\": () => (/* reexport safe */ _qr_Qr_js__WEBPACK_IMPORTED_MODULE_19__.qrAddress),\n/* harmony export */ \"randomValues\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.randomValues),\n/* harmony export */ \"removeAxiosMock\": () => (/* reexport safe */ _test_axios_js__WEBPACK_IMPORTED_MODULE_4__.removeAxiosMock),\n/* harmony export */ \"replaceNamedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__.replaceNamedWallet),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.sanitizeUnit),\n/* harmony export */ \"setupAxiosMock\": () => (/* reexport safe */ _test_axios_js__WEBPACK_IMPORTED_MODULE_4__.setupAxiosMock),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.sha256),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.sumUtxoValue),\n/* harmony export */ \"toCashAddress\": () => (/* reexport safe */ _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_22__.toCashAddress),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.toCashaddr),\n/* harmony export */ \"toSlpAddress\": () => (/* reexport safe */ _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_22__.toSlpAddress),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.toTokenaddr),\n/* harmony export */ \"toUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__.toUtxoId),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_17__.utf8ToBin),\n/* harmony export */ \"walletClassMap\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__.walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__.walletFromId)\n/* harmony export */ });\n/* harmony import */ var _db_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./db/index.js */ \"./src/db/index.ts\");\n/* harmony import */ var _mine_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mine/index.js */ \"./src/mine/index.ts\");\n/* harmony import */ var _slp_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./slp/index.js */ \"./src/slp/index.ts\");\n/* harmony import */ var _test_expect_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./test/expect.js */ \"./src/test/expect.ts\");\n/* harmony import */ var _test_axios_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./test/axios.js */ \"./src/test/axios.ts\");\n/* harmony import */ var _webhook_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webhook/index.js */ \"./src/webhook/index.ts\");\n/* harmony import */ var _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./wallet/Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./wallet/createWallet.js */ \"./src/wallet/createWallet.ts\");\n/* harmony import */ var _network_configuration_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./network/configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./util/index.js */ \"./src/util/index.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./util/bchaddr.js */ \"./src/util/bchaddr.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_slp_index_js__WEBPACK_IMPORTED_MODULE_2__, _webhook_index_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_6__, _network_index_js__WEBPACK_IMPORTED_MODULE_7__, _message_signed_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_9__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_12__, _enum_js__WEBPACK_IMPORTED_MODULE_14__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__, _util_index_js__WEBPACK_IMPORTED_MODULE_17__, _libauth_js__WEBPACK_IMPORTED_MODULE_18__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_19__]);\n([_slp_index_js__WEBPACK_IMPORTED_MODULE_2__, _webhook_index_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_6__, _network_index_js__WEBPACK_IMPORTED_MODULE_7__, _message_signed_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_9__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_10__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_11__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_12__, _enum_js__WEBPACK_IMPORTED_MODULE_14__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_16__, _util_index_js__WEBPACK_IMPORTED_MODULE_17__, _libauth_js__WEBPACK_IMPORTED_MODULE_18__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_19__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n// provider\n\n// config\n\n// Enum\n\n\n// models\n\n// utils\n\n\n\n// libauth\n\n// qr\n\n// constants\n\n\n// interfaces\n\n// TODO move this up to util (Mainnet) ?\n\nfunction cube(x) {\n return x * x * x;\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
927
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* reexport safe */ _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_5__.BCMR),\n/* harmony export */ \"BalanceResponse\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.BalanceResponse),\n/* harmony export */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_8__.BaseWallet),\n/* harmony export */ \"CONST\": () => (/* reexport module object */ _constant_js__WEBPACK_IMPORTED_MODULE_19__),\n/* harmony export */ \"Config\": () => (/* reexport safe */ _config_js__WEBPACK_IMPORTED_MODULE_12__.Config),\n/* harmony export */ \"Connection\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_6__.Connection),\n/* harmony export */ \"DefaultProvider\": () => (/* reexport safe */ _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__.DefaultProvider),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_6__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"IndexedDBProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_0__.IndexedDBProvider),\n/* harmony export */ \"Mainnet\": () => (/* reexport module object */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__),\n/* harmony export */ \"NFTCapability\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_20__.NFTCapability),\n/* harmony export */ \"Network\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_20__.Network),\n/* harmony export */ \"NetworkType\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_13__.NetworkType),\n/* harmony export */ \"OpReturnData\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.OpReturnData),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.RegTestWifWallet),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.RuntimePlatform),\n/* harmony export */ \"SendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.SendResponse),\n/* harmony export */ \"SignedMessage\": () => (/* reexport safe */ _message_signed_js__WEBPACK_IMPORTED_MODULE_7__.SignedMessage),\n/* harmony export */ \"SqlProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_0__.SqlProvider),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.TestNetWifWallet),\n/* harmony export */ \"TokenBurnRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenSendRequest),\n/* harmony export */ \"UnitEnum\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_13__.UnitEnum),\n/* harmony export */ \"Wallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.Wallet),\n/* harmony export */ \"WalletTypeEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.WifWallet),\n/* harmony export */ \"XPubKey\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.XPubKey),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convert),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convertObject),\n/* harmony export */ \"createWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.createWalletResponse),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.derivedNetwork),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_6__.disconnectProviders),\n/* harmony export */ \"expect\": () => (/* reexport safe */ _test_expect_js__WEBPACK_IMPORTED_MODULE_2__.expect),\n/* harmony export */ \"fromUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.fromUtxoId),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_6__.getNetworkProvider),\n/* harmony export */ \"getRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getRandomInt),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getUsdRate),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.hexToBin),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_6__.initProviders),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.isValidAddress),\n/* harmony export */ \"libauth\": () => (/* reexport module object */ _libauth_js__WEBPACK_IMPORTED_MODULE_17__),\n/* harmony export */ \"mine\": () => (/* reexport safe */ _mine_index_js__WEBPACK_IMPORTED_MODULE_1__.mine),\n/* harmony export */ \"namedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.namedWalletExists),\n/* harmony export */ \"qrAddress\": () => (/* reexport safe */ _qr_Qr_js__WEBPACK_IMPORTED_MODULE_18__.qrAddress),\n/* harmony export */ \"randomValues\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.randomValues),\n/* harmony export */ \"removeAxiosMock\": () => (/* reexport safe */ _test_axios_js__WEBPACK_IMPORTED_MODULE_3__.removeAxiosMock),\n/* harmony export */ \"replaceNamedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.replaceNamedWallet),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sanitizeUnit),\n/* harmony export */ \"setupAxiosMock\": () => (/* reexport safe */ _test_axios_js__WEBPACK_IMPORTED_MODULE_3__.setupAxiosMock),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sha256),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toTokenaddr),\n/* harmony export */ \"toUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.toUtxoId),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.utf8ToBin),\n/* harmony export */ \"walletClassMap\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.walletFromId)\n/* harmony export */ });\n/* harmony import */ var _db_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./db/index.js */ \"./src/db/index.ts\");\n/* harmony import */ var _mine_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mine/index.js */ \"./src/mine/index.ts\");\n/* harmony import */ var _test_expect_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./test/expect.js */ \"./src/test/expect.ts\");\n/* harmony import */ var _test_axios_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./test/axios.js */ \"./src/test/axios.ts\");\n/* harmony import */ var _webhook_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./webhook/index.js */ \"?6f8b\");\n/* harmony import */ var _webhook_index_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_webhook_index_js__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {};\n/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _webhook_index_js__WEBPACK_IMPORTED_MODULE_4__) if([\"default\",\"SignedMessage\",\"BaseWallet\",\"DefaultProvider\",\"Config\",\"NetworkType\",\"UnitEnum\",\"WalletTypeEnum\",\"Mainnet\",\"libauth\",\"CONST\",\"IndexedDBProvider\",\"SqlProvider\",\"mine\",\"expect\",\"removeAxiosMock\",\"setupAxiosMock\"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _webhook_index_js__WEBPACK_IMPORTED_MODULE_4__[__WEBPACK_IMPORT_KEY__]\n/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__);\n/* harmony import */ var _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./wallet/Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./wallet/createWallet.js */ \"./src/wallet/createWallet.ts\");\n/* harmony import */ var _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./network/configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./util/index.js */ \"./src/util/index.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./interface.js */ \"./src/interface.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_5__, _network_index_js__WEBPACK_IMPORTED_MODULE_6__, _message_signed_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_13__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__, _util_index_js__WEBPACK_IMPORTED_MODULE_16__, _libauth_js__WEBPACK_IMPORTED_MODULE_17__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_18__]);\n([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_5__, _network_index_js__WEBPACK_IMPORTED_MODULE_6__, _message_signed_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_13__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__, _util_index_js__WEBPACK_IMPORTED_MODULE_16__, _libauth_js__WEBPACK_IMPORTED_MODULE_17__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_18__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n// provider\n\n// config\n\n// Enum\n\n\n// models\n\n// utils\n\n\n\n// libauth\n\n// qr\n\n// constants\n\n\n// interfaces\n\n// export function cube(x: number) {\n// return x * x * x;\n// }\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
1058
928
 
1059
929
  /***/ }),
1060
930
 
@@ -1208,76 +1078,6 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1208
1078
 
1209
1079
  /***/ }),
1210
1080
 
1211
- /***/ "./src/slp/GsppProvider.ts":
1212
- /*!*********************************!*\
1213
- !*** ./src/slp/GsppProvider.ts ***!
1214
- \*********************************/
1215
- /***/ ((module, __webpack_exports__, __webpack_require__) => {
1216
-
1217
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"GsppProvider\": () => (/* binding */ GsppProvider)\n/* harmony export */ });\n/* unused harmony exports _convertBalanceBigNumbers, _convertUtxoBigNumbers, _convertSlpTokenInfo */\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bignumber.js */ \"../../node_modules/bignumber.js/bignumber.js\");\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(bignumber_js__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _SlpProvider_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./SlpProvider.js */ \"./src/slp/SlpProvider.ts\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var _util_base64_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/base64.js */ \"./src/util/base64.ts\");\n/* harmony import */ var _util_eventsource_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/eventsource.js */ \"./src/util/eventsource.ts\");\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_base64_js__WEBPACK_IMPORTED_MODULE_6__]);\n_util_base64_js__WEBPACK_IMPORTED_MODULE_6__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\n\n//import EventSource from \"../../polyfill/eventsource.js\";\n\n\nclass GsppProvider {\n constructor(network = _interface_js__WEBPACK_IMPORTED_MODULE_3__.Network.MAINNET) {\n this.network = network;\n this.servers = { ...GsppProvider.defaultServers };\n this.caching = false;\n if ((0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__.getRuntimePlatform)() === _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__.RuntimePlatform.node) {\n if (process.env.GSPP_MAINNET_DATA)\n this.servers.mainnet.dataSource = process.env.GSPP_MAINNET_DATA;\n if (process.env.GSPP_MAINNET_EVENTS)\n this.servers.mainnet.eventSource = process.env.GSPP_MAINNET_EVENTS;\n if (process.env.GSPP_TESTNET_DATA)\n this.servers.testnet.dataSource = process.env.GSPP_TESTNET_DATA;\n if (process.env.GSPP_TESTNET_EVENTS)\n this.servers.testnet.eventSource = process.env.GSPP_TESTNET_EVENTS;\n if (process.env.GSPP_REGTEST_DATA)\n this.servers.regtest.dataSource = process.env.GSPP_REGTEST_DATA;\n if (process.env.GSPP_REGTEST_EVENTS)\n this.servers.regtest.eventSource = process.env.GSPP_REGTEST_EVENTS;\n }\n }\n // all oupoints, including mint batons\n async SlpOutpoints(slpaddr) {\n return (await this.GsppQuery({ cashaddr: slpaddr }, \"v1/graphsearch/slpoutpoints\")).outpoints;\n }\n // all utxos, including mint batons\n async SlpUtxos(slpaddr) {\n const response = (await this.GsppQuery({ cashaddr: slpaddr }, \"v1/graphsearch/slputxos\")).utxos;\n if (!response) {\n return [];\n }\n return _convertUtxoBigNumbers(response);\n }\n // safe-spendable token utxos, without baton\n async SlpSpendableUtxos(slpaddr, tokenId) {\n return (await this.SlpUtxos(slpaddr)).filter((val) => val.isBaton === false && (tokenId ? val.tokenId === tokenId : true));\n }\n // token mint baton utxos\n async SlpBatonUtxos(slpaddr, tokenId) {\n return (await this.SlpUtxos(slpaddr)).filter((val) => val.isBaton === true && (tokenId ? val.tokenId === tokenId : true));\n }\n // look up the token information\n async SlpTokenInfo(tokenId) {\n const info = (await this.GsppQuery({ tokenId: tokenId }, \"v1/graphsearch/slptokeninfo\"));\n return _convertSlpTokenInfo(info);\n }\n // get all token balances\n async SlpAllTokenBalances(slpaddr) {\n return _convertBalanceBigNumbers(((await this.GsppQuery({ cashaddr: slpaddr }, \"v1/graphsearch/slpalltokenbalances\")).balances || []));\n }\n // get specific token balance\n async SlpTokenBalance(slpaddr, tokenId) {\n const response = await this.GsppQuery({ cashaddr: slpaddr, tokenId: tokenId }, \"v1/graphsearch/slptokenbalance\");\n if (!response) {\n return (0,_SlpProvider_js__WEBPACK_IMPORTED_MODULE_5__._emptyTokenBalance)(tokenId);\n }\n const balances = _convertBalanceBigNumbers([response]);\n if (balances[0].value.isZero()) {\n return (0,_SlpProvider_js__WEBPACK_IMPORTED_MODULE_5__._emptyTokenBalance)(tokenId);\n }\n return balances[0];\n }\n // get all slp transactions of this address\n async SlpAddressTransactionHistory(_slpaddr, _tokenId, _limit = 100, _skip = 0) {\n throw \"Not implemented\";\n }\n // waits for next slp transaction to appear in mempool, code execution is halted\n async SlpWaitForTransaction(slpaddr, tokenId) {\n return new Promise(async (resolve) => {\n const cancelFn = this.SlpWatchTransactions(async (tx) => {\n await cancelFn();\n resolve(tx);\n }, slpaddr, tokenId);\n });\n }\n // waits for a certain slp token balance to be available in this wallet, code execution is halted\n async SlpWaitForBalance(value, slpaddr, tokenId) {\n return new Promise((resolve) => {\n const cancelFn = this.SlpWatchBalance(async (balance) => {\n if (balance.value.isGreaterThanOrEqualTo(new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(value))) {\n await cancelFn();\n resolve(balance);\n }\n }, slpaddr, tokenId);\n });\n }\n // sets up a callback to be executed each time the token balance of the wallet is changed\n SlpWatchBalance(callback, slpaddr, tokenId) {\n return this.SlpWatchTransactions(async () => {\n const balance = await this.SlpTokenBalance(slpaddr, tokenId);\n callback(balance);\n }, slpaddr, tokenId);\n }\n // sets up a callback to be executed each time a new transaction associated with this wallet's address is entering the mempool\n SlpWatchTransactions(callback, slpaddr, tokenId) {\n const eventSource = this.SlpSocketEventSource({\n query: { slpaddr, tokenId },\n });\n const cancelFn = async () => {\n eventSource.close();\n };\n eventSource.addEventListener(\"message\", async (txEvent) => {\n const data = JSON.parse(txEvent.data);\n if (data.type === \"rawtx\") {\n const tx = {\n tx_hash: data.data.txHash,\n height: 0,\n details: data.data,\n };\n callback(tx);\n }\n }, false);\n return cancelFn;\n }\n GsppQuery(queryObject, endpoint) {\n if (this.caching) {\n axiosInstance.defaults.headers = {};\n }\n else {\n axiosInstance.defaults.headers = noCacheHeaders;\n }\n // console.log(queryObject, endpoint);\n return new Promise((resolve, reject) => {\n const url = `${this.servers[this.network].dataSource}/${endpoint}`;\n fetch_retry(url, queryObject)\n .then((response) => {\n resolve(response.data);\n })\n .catch((error) => {\n if (error.isAxiosError) {\n // console.trace(JSON.stringify(error, null, 2));\n reject(error.response.data);\n }\n reject(error);\n });\n });\n }\n SlpSocketEventSource(queryObject) {\n const url = `${this.servers[this.network].eventSource}/s/${B64QueryString(queryObject)}`;\n return new _util_eventsource_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"](url);\n }\n}\nGsppProvider.defaultServers = {\n mainnet: {\n dataSource: \"https://gs.fountainhead.cash\",\n eventSource: \"https://slpsocket.fountainhead.cash\",\n },\n testnet: {\n dataSource: \"https://gs-testnet.fountainhead.cash\",\n eventSource: \"https://slpsocket-testnet.fountainhead.cash\",\n },\n regtest: {\n dataSource: \"http://localhost:12400\",\n eventSource: \"http://localhost:12401\",\n },\n};\nconst noCacheHeaders = {\n \"Cache-Control\": \"no-cache\",\n Pragma: \"no-cache\",\n Expires: \"0\",\n};\nconst axiosInstance = axios__WEBPACK_IMPORTED_MODULE_1___default().create({\n headers: noCacheHeaders,\n});\nconst fetch_retry = (url, data = {}, n = 1) => axiosInstance.post(url, data).catch(function (error) {\n if (n === 0) {\n throw error;\n }\n return new Promise((resolve) => {\n setTimeout(() => resolve(fetch_retry(url, data, n - 1)), 1000);\n });\n});\nconst B64QueryString = function (queryObject) {\n if (!queryObject || !Object.keys(queryObject).length) {\n throw new Error(\"Empty query\");\n }\n return (0,_util_base64_js__WEBPACK_IMPORTED_MODULE_6__.btoa)(JSON.stringify(queryObject));\n};\nfunction _convertBalanceBigNumbers(balances) {\n balances.forEach((val) => (val.value = new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(val.value).shiftedBy(-1 * val.decimals)));\n return balances;\n}\nfunction _convertUtxoBigNumbers(utxos) {\n utxos.forEach((val) => {\n val.value = new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(val.value).shiftedBy(-1 * val.decimals);\n val.satoshis = Number(val.satoshis);\n });\n return utxos;\n}\nfunction _convertSlpTokenInfo(tokenInfo) {\n if (!tokenInfo)\n return tokenInfo;\n tokenInfo.initialAmount = new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(tokenInfo.initialAmount).shiftedBy(-1 * tokenInfo.decimals);\n tokenInfo.parentTokenId = tokenInfo.groupId;\n return tokenInfo;\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/slp/GsppProvider.ts?");
1218
-
1219
- /***/ }),
1220
-
1221
- /***/ "./src/slp/SlpDbProvider.ts":
1222
- /*!**********************************!*\
1223
- !*** ./src/slp/SlpDbProvider.ts ***!
1224
- \**********************************/
1225
- /***/ ((module, __webpack_exports__, __webpack_require__) => {
1226
-
1227
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"SlpDbProvider\": () => (/* binding */ SlpDbProvider)\n/* harmony export */ });\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _SlpDbTemplates_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./SlpDbTemplates.js */ \"./src/slp/SlpDbTemplates.ts\");\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bignumber.js */ \"../../node_modules/bignumber.js/bignumber.js\");\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(bignumber_js__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _SlpProvider_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./SlpProvider.js */ \"./src/slp/SlpProvider.ts\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var _util_base64_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/base64.js */ \"./src/util/base64.ts\");\n/* harmony import */ var _util_eventsource_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/eventsource.js */ \"./src/util/eventsource.ts\");\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_base64_js__WEBPACK_IMPORTED_MODULE_7__]);\n_util_base64_js__WEBPACK_IMPORTED_MODULE_7__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\n\n\n//import EventSource from \"../../polyfill/eventsource.js\";\n\n\nclass SlpDbProvider {\n constructor(network = _interface_js__WEBPACK_IMPORTED_MODULE_3__.Network.MAINNET) {\n this.network = network;\n this.servers = { ...SlpDbProvider.defaultServers };\n this.caching = false;\n if ((0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__.getRuntimePlatform)() === _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__.RuntimePlatform.node) {\n if (process.env.SLPDB_MAINNET_DATA)\n this.servers.mainnet.dataSource = process.env.SLPDB_MAINNET_DATA;\n if (process.env.SLPDB_MAINNET_EVENTS)\n this.servers.mainnet.eventSource = process.env.SLPDB_MAINNET_EVENTS;\n if (process.env.SLPDB_TESTNET_DATA)\n this.servers.testnet.dataSource = process.env.SLPDB_TESTNET_DATA;\n if (process.env.SLPDB_TESTNET_EVENTS)\n this.servers.testnet.eventSource = process.env.SLPDB_TESTNET_EVENTS;\n if (process.env.SLPDB_REGTEST_DATA)\n this.servers.regtest.dataSource = process.env.SLPDB_REGTEST_DATA;\n if (process.env.SLPDB_REGTEST_EVENTS)\n this.servers.regtest.eventSource = process.env.SLPDB_REGTEST_EVENTS;\n }\n }\n // all oupoints, including mint batons\n async SlpOutpoints(slpaddr) {\n return (await this.SlpDbQuery((0,_SlpDbTemplates_js__WEBPACK_IMPORTED_MODULE_5__.SlpAllOutpointsTemplate)(slpaddr)))\n .g;\n }\n // all utxos, including mint batons\n async SlpUtxos(slpaddr) {\n return (0,_SlpProvider_js__WEBPACK_IMPORTED_MODULE_6__._convertUtxoBigNumbers)((await this.SlpDbQuery((0,_SlpDbTemplates_js__WEBPACK_IMPORTED_MODULE_5__.SlpAllUtxosTemplate)(slpaddr))).g);\n }\n // look up the token information\n async SlpTokenInfo(tokenId) {\n const infos = (await this.SlpDbQuery((0,_SlpDbTemplates_js__WEBPACK_IMPORTED_MODULE_5__.SlpTokenInfoTemplate)(tokenId)))\n .t;\n return (0,_SlpProvider_js__WEBPACK_IMPORTED_MODULE_6__._convertSlpTokenInfo)(infos[0]);\n }\n // safe-spendable token utxos, without baton\n async SlpSpendableUtxos(slpaddr, tokenId) {\n return (0,_SlpProvider_js__WEBPACK_IMPORTED_MODULE_6__._convertUtxoBigNumbers)((await this.SlpDbQuery((0,_SlpDbTemplates_js__WEBPACK_IMPORTED_MODULE_5__.SlpSpendableUtxosTemplate)(slpaddr, tokenId)))\n .g);\n }\n // token mint baton utxos\n async SlpBatonUtxos(slpaddr, tokenId) {\n return (0,_SlpProvider_js__WEBPACK_IMPORTED_MODULE_6__._convertUtxoBigNumbers)((await this.SlpDbQuery((0,_SlpDbTemplates_js__WEBPACK_IMPORTED_MODULE_5__.SlpBatonUtxosTemplate)(slpaddr, tokenId)))\n .g);\n }\n // get all token balances\n async SlpAllTokenBalances(slpaddr) {\n return (0,_SlpProvider_js__WEBPACK_IMPORTED_MODULE_6__._convertBalanceBigNumbers)((await this.SlpDbQuery((0,_SlpDbTemplates_js__WEBPACK_IMPORTED_MODULE_5__.SlpAllTokenBalancesTemplate)(slpaddr)))\n .g);\n }\n // get specific token balance\n async SlpTokenBalance(slpaddr, tokenId) {\n const balances = (0,_SlpProvider_js__WEBPACK_IMPORTED_MODULE_6__._convertBalanceBigNumbers)((await this.SlpDbQuery((0,_SlpDbTemplates_js__WEBPACK_IMPORTED_MODULE_5__.SlpTokenBalanceTemplate)(slpaddr, tokenId)))\n .g);\n return balances[0] || (0,_SlpProvider_js__WEBPACK_IMPORTED_MODULE_6__._emptyTokenBalance)(tokenId);\n }\n // get all slp transactions of this address\n async SlpAddressTransactionHistory(slpaddr, tokenId, limit = 100, skip = 0) {\n const response = await this.SlpDbQuery((0,_SlpDbTemplates_js__WEBPACK_IMPORTED_MODULE_5__.SlpAddressTransactionHistoryTemplate)(slpaddr, tokenId, limit, skip));\n return response.c.concat(response.u);\n }\n // waits for next slp transaction to appear in mempool, code execution is halted\n async SlpWaitForTransaction(slpaddr, tokenId) {\n return new Promise(async (resolve) => {\n const cancelFn = this.SlpWatchTransactions(async (tx) => {\n await cancelFn();\n resolve(tx);\n }, slpaddr, tokenId);\n });\n }\n // waits for a certain slp token balance to be available in this wallet, code execution is halted\n async SlpWaitForBalance(value, slpaddr, tokenId) {\n return new Promise((resolve) => {\n const cancelFn = this.SlpWatchBalance(async (balance) => {\n if (balance.value.isGreaterThanOrEqualTo(new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(value))) {\n await cancelFn();\n resolve(balance);\n }\n }, slpaddr, tokenId);\n });\n }\n // set's up a callback to be executed each time the token balance of the wallet is changed\n SlpWatchBalance(callback, slpaddr, tokenId) {\n return this.SlpWatchTransactions(async () => {\n const balance = await this.SlpTokenBalance(slpaddr, tokenId);\n callback(balance);\n }, slpaddr, tokenId);\n }\n // sets up a callback to be executed each time a new transaction associated with this wallet's address is entering the mempool\n SlpWatchTransactions(callback, slpaddr, tokenId) {\n const eventSource = this.SlpSocketEventSource((0,_SlpDbTemplates_js__WEBPACK_IMPORTED_MODULE_5__.SlpWaitForTransactionTemplate)(slpaddr, tokenId));\n const cancelFn = async () => {\n eventSource.close();\n };\n eventSource.addEventListener(\"message\", async (txEvent) => {\n const data = JSON.parse(txEvent.data);\n if (data.data && data.data.length) {\n const tx = {\n tx_hash: data.data[0].tx.h,\n height: 0,\n details: data.data[0],\n };\n callback(tx);\n }\n }, false);\n return cancelFn;\n }\n SlpDbQuery(queryObject) {\n if (this.caching) {\n axiosInstance.defaults.headers = {};\n }\n else {\n axiosInstance.defaults.headers = noCacheHeaders;\n }\n return new Promise((resolve, reject) => {\n const url = `${this.servers[this.network].dataSource}/q/${B64QueryString(queryObject)}`;\n fetch_retry(url).then((response) => {\n if (response.hasOwnProperty(\"error\")) {\n reject(new Error(response[\"error\"]));\n }\n resolve(response.data);\n });\n });\n }\n SlpSocketEventSource(queryObject) {\n const url = `${this.servers[this.network].eventSource}/s/${B64QueryString(queryObject)}`;\n return new _util_eventsource_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"](url);\n }\n}\nSlpDbProvider.defaultServers = {\n mainnet: {\n dataSource: \"https://slpdb.fountainhead.cash\",\n eventSource: \"https://slpsocket.fountainhead.cash\",\n },\n testnet: {\n dataSource: \"https://slpdb-testnet.fountainhead.cash\",\n eventSource: \"https://slpsocket-testnet.fountainhead.cash\",\n },\n regtest: {\n dataSource: \"http://localhost:12300\",\n eventSource: \"http://localhost:12301\",\n },\n};\nconst noCacheHeaders = {\n \"Cache-Control\": \"no-cache\",\n Pragma: \"no-cache\",\n Expires: \"0\",\n};\nconst axiosInstance = axios__WEBPACK_IMPORTED_MODULE_1___default().create({\n headers: noCacheHeaders,\n});\nconst fetch_retry = (url, options = {}, n = 5) => axiosInstance.get(url, options).catch(function (error) {\n if (n === 0) {\n throw error;\n }\n return new Promise((resolve) => {\n setTimeout(() => resolve(fetch_retry(url, options, n - 1)), 1000);\n });\n});\nconst B64QueryString = function (queryObject) {\n if (!queryObject || !Object.keys(queryObject).length) {\n throw new Error(\"Empty SLPDB query\");\n }\n return (0,_util_base64_js__WEBPACK_IMPORTED_MODULE_7__.btoa)(JSON.stringify(queryObject));\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/slp/SlpDbProvider.ts?");
1228
-
1229
- /***/ }),
1230
-
1231
- /***/ "./src/slp/SlpDbTemplates.ts":
1232
- /*!***********************************!*\
1233
- !*** ./src/slp/SlpDbTemplates.ts ***!
1234
- \***********************************/
1235
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1236
-
1237
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"SlpAddressTransactionHistoryTemplate\": () => (/* binding */ SlpAddressTransactionHistoryTemplate),\n/* harmony export */ \"SlpAllOutpointsTemplate\": () => (/* binding */ SlpAllOutpointsTemplate),\n/* harmony export */ \"SlpAllTokenBalancesTemplate\": () => (/* binding */ SlpAllTokenBalancesTemplate),\n/* harmony export */ \"SlpAllUtxosTemplate\": () => (/* binding */ SlpAllUtxosTemplate),\n/* harmony export */ \"SlpBatonUtxosTemplate\": () => (/* binding */ SlpBatonUtxosTemplate),\n/* harmony export */ \"SlpSpendableUtxosTemplate\": () => (/* binding */ SlpSpendableUtxosTemplate),\n/* harmony export */ \"SlpTokenBalanceTemplate\": () => (/* binding */ SlpTokenBalanceTemplate),\n/* harmony export */ \"SlpTokenInfoTemplate\": () => (/* binding */ SlpTokenInfoTemplate),\n/* harmony export */ \"SlpWaitForTransactionTemplate\": () => (/* binding */ SlpWaitForTransactionTemplate)\n/* harmony export */ });\n// Slp Utxos for bch operation, to prevent accident burning of tokens and baton\n// prettier-ignore\nconst SlpAllUtxosTemplate = (slpaddr) => ({\n \"v\": 3,\n \"q\": {\n \"db\": [\"g\"],\n \"aggregate\": [\n {\n \"$match\": {\n \"graphTxn.outputs.address\": slpaddr,\n \"graphTxn.outputs.status\": {\n \"$in\": [\n \"UNSPENT\",\n \"BATON_UNSPENT\"\n ]\n }\n }\n },\n {\n \"$unwind\": \"$graphTxn.outputs\"\n },\n {\n \"$match\": {\n \"graphTxn.outputs.address\": slpaddr,\n \"graphTxn.outputs.status\": {\n \"$in\": [\n \"UNSPENT\",\n \"BATON_UNSPENT\"\n ]\n }\n }\n }\n ],\n \"limit\": 1e6,\n },\n \"r\": {\n \"f\": \"[ .[] | { txid: .graphTxn.txid, vout: .graphTxn.outputs.vout, satoshis: .graphTxn.outputs.bchSatoshis, value: .graphTxn.outputs.slpAmount, decimals: .graphTxn.details.decimals, ticker: .graphTxn.details.symbol, tokenId: .graphTxn.details.tokenIdHex, type: .graphTxn.details.versionType, parentTokenId: .tokenDetails.nftGroupIdHex } ]\"\n }\n});\n// Slp outpoints for bch operation, to prevent accident burning of tokens and baton\n// prettier-ignore\nconst SlpAllOutpointsTemplate = (slpaddr) => ({\n \"v\": 3,\n \"q\": {\n \"db\": [\"g\"],\n \"aggregate\": [\n {\n \"$match\": {\n \"graphTxn.outputs.address\": slpaddr,\n \"graphTxn.outputs.status\": {\n \"$in\": [\n \"UNSPENT\",\n \"BATON_UNSPENT\"\n ]\n }\n }\n },\n {\n \"$unwind\": \"$graphTxn.outputs\"\n },\n {\n \"$match\": {\n \"graphTxn.outputs.address\": slpaddr,\n \"graphTxn.outputs.status\": {\n \"$in\": [\n \"UNSPENT\",\n \"BATON_UNSPENT\"\n ]\n }\n }\n },\n {\n \"$project\": {\n \"graphTxn\": 1\n }\n }\n ],\n \"limit\": 1e6,\n },\n \"r\": {\n \"f\": \"[ .[] | [.graphTxn.txid, .graphTxn.outputs.vout | tostring] | join(\\\":\\\") ]\"\n }\n});\n// Slp Utxos for spending\n// prettier-ignore\nconst SlpSpendableUtxosTemplate = (slpaddr, tokenId) => {\n let q = {\n \"v\": 3,\n \"q\": {\n \"db\": [\"g\"],\n \"aggregate\": [\n {\n \"$match\": {\n \"graphTxn.outputs.address\": slpaddr,\n \"graphTxn.outputs.status\": \"UNSPENT\"\n }\n },\n {\n \"$unwind\": \"$graphTxn.outputs\"\n },\n {\n \"$match\": {\n \"graphTxn.outputs.address\": slpaddr,\n \"graphTxn.outputs.status\": \"UNSPENT\"\n }\n },\n {\n \"$lookup\": {\n \"from\": \"tokens\",\n \"localField\": \"graphTxn.details.tokenIdHex\",\n \"foreignField\": \"tokenDetails.tokenIdHex\",\n \"as\": \"token\"\n }\n }\n ]\n },\n \"r\": {\n \"f\": \"[ .[] | { txid: .graphTxn.txid, vout: .graphTxn.outputs.vout, satoshis: .graphTxn.outputs.bchSatoshis, value: .graphTxn.outputs.slpAmount, decimals: .token[0].tokenDetails.decimals, ticker: .token[0].tokenDetails.symbol, tokenId: .graphTxn.details.tokenIdHex, type: .graphTxn.details.versionType, parentTokenId: .token[0].nftParentId } ]\"\n }\n };\n if (tokenId) {\n q[\"q\"][\"aggregate\"][0][\"$match\"][\"graphTxn.details.tokenIdHex\"] = tokenId;\n }\n // console.log(JSON.stringify(q, null, 2));\n return q;\n};\n// prettier-ignore\nconst SlpAllTokenBalancesTemplate = (slpaddr) => {\n let q = {\n \"v\": 3,\n \"q\": {\n \"db\": [\"g\"],\n \"aggregate\": [\n {\n \"$match\": {\n \"graphTxn.outputs.status\": \"UNSPENT\",\n \"graphTxn.outputs.address\": slpaddr\n }\n },\n {\n \"$unwind\": \"$graphTxn.outputs\"\n },\n {\n \"$match\": {\n \"graphTxn.outputs.status\": \"UNSPENT\",\n \"graphTxn.outputs.address\": slpaddr\n }\n },\n {\n \"$group\": {\n \"_id\": \"$tokenDetails.tokenIdHex\",\n \"slpAmount\": {\n \"$sum\": \"$graphTxn.outputs.slpAmount\"\n }\n }\n },\n {\n \"$sort\": {\n \"slpAmount\": -1\n }\n },\n {\n \"$lookup\": {\n \"from\": \"tokens\",\n \"localField\": \"_id\",\n \"foreignField\": \"tokenDetails.tokenIdHex\",\n \"as\": \"token\"\n }\n },\n {\n \"$match\": {\n \"slpAmount\": {\n \"$gt\": 0\n }\n }\n }\n ],\n \"sort\": {\n \"slpAmount\": -1\n }\n },\n \"r\": {\n \"f\": \"[ .[] | { value: .slpAmount, ticker: .token[0].tokenDetails.symbol, name: .token[0].tokenDetails.name, tokenId: ._id, type: .token[0].tokenDetails.versionType, parentTokenId: .token[0].nftParentId } ]\"\n }\n };\n return q;\n};\n// prettier-ignore\nconst SlpTokenBalanceTemplate = (slpaddr, tokenId) => {\n let q = {\n \"v\": 3,\n \"q\": {\n \"db\": [\"g\"],\n \"aggregate\": [\n {\n \"$match\": {\n \"tokenDetails.tokenIdHex\": tokenId\n }\n },\n {\n \"$match\": {\n \"graphTxn.outputs.status\": \"UNSPENT\",\n \"graphTxn.outputs.address\": slpaddr\n }\n },\n {\n \"$unwind\": \"$graphTxn.outputs\"\n },\n {\n \"$match\": {\n \"graphTxn.outputs.status\": \"UNSPENT\",\n \"graphTxn.outputs.address\": slpaddr\n }\n },\n {\n \"$group\": {\n \"_id\": \"$tokenDetails.tokenIdHex\",\n \"slpAmount\": {\n \"$sum\": \"$graphTxn.outputs.slpAmount\"\n }\n }\n },\n {\n \"$sort\": {\n \"slpAmount\": -1\n }\n },\n {\n \"$lookup\": {\n \"from\": \"tokens\",\n \"localField\": \"_id\",\n \"foreignField\": \"tokenDetails.tokenIdHex\",\n \"as\": \"token\"\n }\n }\n ],\n \"sort\": {\n \"slpAmount\": -1\n }\n },\n \"r\": {\n \"f\": \"[ .[] | { value: .slpAmount, ticker: .token[0].tokenDetails.symbol, name: .token[0].tokenDetails.name, tokenId: ._id, type: .token[0].tokenDetails.versionType, parentTokenId: .token[0].nftParentId } ]\"\n }\n };\n // console.log(JSON.stringify(q, null, 2));\n return q;\n};\n// prettier-ignore\nconst SlpAddressTransactionHistoryTemplate = (address, tokenId, limit = 100, skip = 0) => {\n const q = {\n \"v\": 3,\n \"q\": {\n \"db\": [\"c\", \"u\"],\n \"find\": {\n \"$query\": {\n \"$or\": [\n { \"in.e.a\": address },\n { \"out.e.a\": address },\n ],\n \"$and\": [\n { \"slp.valid\": true },\n ]\n },\n },\n \"sort\": { \"blk.i\": 1 },\n \"limit\": limit,\n \"skip\": skip,\n },\n \"r\": {\n \"f\": \"[ .[] | { tx_hash: .tx.h, height: .blk.i, details: . } ]\"\n }\n };\n if (tokenId) {\n q[\"q\"][\"find\"][\"$query\"][\"$and\"].push({ \"slp.detail.tokenIdHex\": tokenId });\n }\n // console.log(JSON.stringify(q, null, 2));\n return q;\n};\n// prettier-ignore\nconst SlpWaitForTransactionTemplate = (slpaddr, tokenId) => {\n let q = {\n \"v\": 3,\n \"q\": {\n \"db\": [\"c\", \"u\"],\n \"find\": {}\n }\n };\n if (slpaddr) {\n q[\"q\"][\"find\"][\"$or\"] = [\n {\n \"in.e.a\": slpaddr\n },\n {\n \"out.e.a\": slpaddr\n }\n ];\n }\n if (tokenId) {\n q[\"q\"][\"find\"][\"slp.detail.tokenIdHex\"] = tokenId;\n }\n return q;\n};\n// Lookup SLP token information\n// prettier-ignore\nconst SlpTokenInfoTemplate = (tokenId, limit = 100, skip = 0) => {\n let q = {\n \"v\": 3,\n \"q\": {\n \"db\": [\"t\"],\n \"find\": {},\n \"sort\": {\n \"tokenStats.approx_txns_since_genesis\": -1\n },\n \"limit\": limit,\n \"skip\": skip,\n },\n \"r\": {\n \"f\": \"[ .[] | { ticker: .tokenDetails.symbol, name: .tokenDetails.name, tokenId: .tokenDetails.tokenIdHex, decimals: .tokenDetails.decimals, documentUrl: .tokenDetails.documentUri, documentHash: .tokenDetails.documentSha256Hex, initialAmount: .tokenDetails.genesisOrMintQuantity, type: .tokenDetails.versionType, parentTokenId: .nftParentId } ]\"\n }\n };\n if (tokenId) {\n q[\"q\"][\"find\"][\"tokenDetails.tokenIdHex\"] = tokenId;\n }\n // console.log(q);\n return q;\n};\n// Slp Utxos for bch operation, to prevent accident burning of tokens and baton\n// prettier-ignore\nconst SlpBatonUtxosTemplate = (slpaddr, tokenId) => {\n let q = {\n \"v\": 3,\n \"q\": {\n \"db\": [\"g\"],\n \"aggregate\": [\n {\n \"$match\": {\n \"graphTxn.outputs.address\": slpaddr,\n \"graphTxn.outputs.status\": \"BATON_UNSPENT\"\n }\n },\n {\n \"$unwind\": \"$graphTxn.outputs\"\n },\n {\n \"$match\": {\n \"graphTxn.outputs.address\": slpaddr,\n \"graphTxn.outputs.status\": \"BATON_UNSPENT\"\n }\n },\n {\n \"$project\": {\n \"graphTxn\": 1\n }\n },\n {\n \"$lookup\": {\n \"from\": \"tokens\",\n \"localField\": \"graphTxn.details.tokenIdHex\",\n \"foreignField\": \"tokenDetails.tokenIdHex\",\n \"as\": \"token\"\n }\n }\n ]\n },\n \"r\": {\n \"f\": \"[ .[] | { txid: .graphTxn.txid, vout: .graphTxn.outputs.vout, satoshis: .graphTxn.outputs.bchSatoshis, value: .graphTxn.outputs.slpAmount, decimals: .token[0].tokenDetails.decimals, ticker: .token[0].tokenDetails.symbol, tokenId: .graphTxn.details.tokenIdHex, type: .graphTxn.details.versionType } ]\"\n }\n };\n if (tokenId) {\n q[\"q\"][\"aggregate\"][0][\"$match\"][\"graphTxn.details.tokenIdHex\"] = tokenId;\n }\n // console.log(JSON.stringify(q, null, 2));\n return q;\n};\n\n\n//# sourceURL=webpack://mainnet-js/./src/slp/SlpDbTemplates.ts?");
1238
-
1239
- /***/ }),
1240
-
1241
- /***/ "./src/slp/SlpLibAuth.ts":
1242
- /*!*******************************!*\
1243
- !*** ./src/slp/SlpLibAuth.ts ***!
1244
- \*******************************/
1245
- /***/ ((module, __webpack_exports__, __webpack_require__) => {
1246
-
1247
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"SlpGetGenesisOutputs\": () => (/* binding */ SlpGetGenesisOutputs),\n/* harmony export */ \"SlpGetMintOutputs\": () => (/* binding */ SlpGetMintOutputs),\n/* harmony export */ \"SlpGetSendOutputs\": () => (/* binding */ SlpGetSendOutputs)\n/* harmony export */ });\n/* unused harmony exports bigIntToBinUint64BE, SlpTxoTemplate */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/number.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/schema/authentication-template.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/compiler-bch/compiler-bch.js\");\n/* harmony import */ var slp_parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! slp-parser */ \"../../node_modules/slp-parser/dist/index.js\");\n/* harmony import */ var slp_parser__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(slp_parser__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _slp_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../slp/interface.js */ \"./src/slp/interface.ts\");\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! bignumber.js */ \"../../node_modules/bignumber.js/bignumber.js\");\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(bignumber_js__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/bchaddr.js */ \"../../node_modules/bchaddrjs-slp/src/bchaddr.js\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_6__);\n/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\")[\"Buffer\"];\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_model_js__WEBPACK_IMPORTED_MODULE_7__, _enum_js__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__]);\n([_wallet_model_js__WEBPACK_IMPORTED_MODULE_7__, _enum_js__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\nconst bigIntToBinUint64BE = (value) => {\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.bigIntToBinUint64LE)(value).reverse();\n};\nconst stringToBin = (value, hex = false) => {\n if (!value)\n return Uint8Array.from([0x4c, 0x00]);\n if (hex)\n return Uint8Array.from([...[value.length / 2], ...(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin)(value)]);\n const length = new TextEncoder().encode(value).length;\n return Uint8Array.from([...[length], ...(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.utf8ToBin)(value)]);\n};\nconst supportedTokenTypes = [\n _slp_interface_js__WEBPACK_IMPORTED_MODULE_5__.SlpTokenType.Type1,\n _slp_interface_js__WEBPACK_IMPORTED_MODULE_5__.SlpTokenType.NftParent,\n _slp_interface_js__WEBPACK_IMPORTED_MODULE_5__.SlpTokenType.NftChild,\n];\nconst SlpGetGenesisOutputs = async (options) => {\n if (!(0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_6__.isValidAddress)(options.tokenReceiverSlpAddr)) {\n throw new Error(`Invalid tokenReceiverSlpAddr ${options.tokenReceiverSlpAddr}`);\n }\n if (!(0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_6__.isValidAddress)(options.batonReceiverSlpAddr)) {\n throw new Error(`Invalid batonReceiverSlpAddr ${options.batonReceiverSlpAddr}`);\n }\n if (!options.type) {\n options.type = _slp_interface_js__WEBPACK_IMPORTED_MODULE_5__.SlpTokenType.Type1;\n }\n if (!supportedTokenTypes.includes(options.type)) {\n throw new Error(`Unsupported token type ${options.type}`);\n }\n // explicitly convert initial amount to bignumber\n options.initialAmount = new (bignumber_js__WEBPACK_IMPORTED_MODULE_1___default())(options.initialAmount);\n if (options.initialAmount.isLessThanOrEqualTo(0)) {\n throw Error(\"Initial genesis token amount should be greater than zero\");\n }\n if (options.decimals < 0 || options.decimals > 9) {\n throw new Error(\"Genesis allows decimal places between 0\");\n }\n const addrs = options.endBaton\n ? [options.tokenReceiverSlpAddr]\n : [options.tokenReceiverSlpAddr, options.batonReceiverSlpAddr];\n const bchSendRequests = addrs.map((val) => new _wallet_model_js__WEBPACK_IMPORTED_MODULE_7__.SendRequest({\n cashaddr: (0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_6__.toCashAddress)(val),\n value: _constant_js__WEBPACK_IMPORTED_MODULE_8__.DUST_UTXO_THRESHOLD,\n unit: _enum_js__WEBPACK_IMPORTED_MODULE_9__.UnitEnum.SAT,\n }));\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.importAuthenticationTemplate)(SlpTxoTemplate);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = await (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.authenticationTemplateToCompilerBCH)(template);\n const rawTokenAmount = BigInt(options.initialAmount.shiftedBy(options.decimals));\n const batonVout = options.endBaton ? [0x4c, 0x00] : [0x01, 0x02];\n let genesisTxoBytecode = compiler.generateBytecode({\n scriptId: \"genesis_lock\",\n data: {\n bytecode: {\n g_token_type: Uint8Array.from([...[0x01], ...[options.type]]),\n g_token_ticker: stringToBin(options.ticker),\n g_token_name: stringToBin(options.name),\n g_token_document_url: stringToBin(options.documentUrl),\n g_token_document_hash: stringToBin(options.documentHash, true),\n g_decimals: Uint8Array.from([...[0x01], ...[options.decimals]]),\n g_mint_baton_vout: Uint8Array.from(batonVout),\n g_initial_token_mint_quantity: Uint8Array.from([\n ...[0x08],\n ...bigIntToBinUint64BE(rawTokenAmount),\n ]),\n },\n },\n });\n if (!genesisTxoBytecode.success) {\n throw new Error(genesisTxoBytecode.errors.map((e) => e.error).join(\"\\n\"));\n }\n return {\n SlpOutputs: [\n {\n lockingBytecode: genesisTxoBytecode.bytecode,\n valueSatoshis: 0n,\n },\n ],\n FundingSlpUtxos: [],\n BchSendRequests: bchSendRequests,\n };\n};\nconst SlpGetMintOutputs = async (options, slpBatonUtxos) => {\n if (!(0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_6__.isValidAddress)(options.tokenReceiverSlpAddr)) {\n throw new Error(`Invalid tokenReceiverSlpAddr ${options.tokenReceiverSlpAddr}`);\n }\n if (!(0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_6__.isValidAddress)(options.batonReceiverSlpAddr)) {\n throw new Error(`Invalid batonReceiverSlpAddr ${options.batonReceiverSlpAddr}`);\n }\n const tokenType = slpBatonUtxos[0].type;\n if (!supportedTokenTypes.includes(tokenType)) {\n throw new Error(`Unsupported token type ${tokenType}`);\n }\n const addrs = options.endBaton\n ? [options.tokenReceiverSlpAddr]\n : [options.tokenReceiverSlpAddr, options.batonReceiverSlpAddr];\n const bchSendRequests = addrs.map((val) => new _wallet_model_js__WEBPACK_IMPORTED_MODULE_7__.SendRequest({\n cashaddr: (0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_6__.toCashAddress)(val),\n value: _constant_js__WEBPACK_IMPORTED_MODULE_8__.DUST_UTXO_THRESHOLD,\n unit: _enum_js__WEBPACK_IMPORTED_MODULE_9__.UnitEnum.SAT,\n }));\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.importAuthenticationTemplate)(SlpTxoTemplate);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = await (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.authenticationTemplateToCompilerBCH)(template);\n const decimals = slpBatonUtxos[0].decimals;\n const amount = new (bignumber_js__WEBPACK_IMPORTED_MODULE_1___default())(options.value).shiftedBy(decimals);\n const batonVout = options.endBaton ? [0x4c, 0x00] : [0x01, 0x02];\n let mintTxoBytecode = compiler.generateBytecode({\n scriptId: \"mint_lock\",\n data: {\n bytecode: {\n m_token_type: Uint8Array.from([...[0x01], ...[tokenType]]),\n m_token_id: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin)(options.tokenId),\n m_mint_baton_vout: Uint8Array.from(batonVout),\n m_additional_token_quantity: Uint8Array.from([\n ...[0x08],\n ...bigIntToBinUint64BE(BigInt(amount.toString())),\n ]),\n },\n },\n });\n if (!mintTxoBytecode.success) {\n throw new Error(mintTxoBytecode.errors.map((e) => e.error).join(\"\\n\"));\n }\n return {\n SlpOutputs: [\n {\n lockingBytecode: mintTxoBytecode.bytecode,\n valueSatoshis: 0n,\n },\n ],\n FundingSlpUtxos: slpBatonUtxos,\n BchSendRequests: bchSendRequests,\n };\n};\nconst SlpGetSendOutputs = async (changeSlpaddr, slpUtxos, sendRequests) => {\n if (!(0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_6__.isValidAddress)(changeSlpaddr)) {\n throw new Error(`Invalid changeSlpaddr ${changeSlpaddr}`);\n }\n if (!slpUtxos.length) {\n throw new Error(\"No available tokens to spend\");\n }\n const decimals = slpUtxos[0].decimals;\n const tokenId = slpUtxos[0].tokenId;\n const tokenType = slpUtxos[0].type;\n if (!supportedTokenTypes.includes(tokenType)) {\n throw new Error(`Unsupported token type ${tokenType}`);\n }\n // sort inputs in ascending order to eliminate the unnecessary splitting\n // and to prefer the consolidation of small inputs\n slpUtxos = slpUtxos.sort((a, b) => a.value.comparedTo(b.value));\n const slpAvailableAmount = slpUtxos\n .map((val) => new (bignumber_js__WEBPACK_IMPORTED_MODULE_1___default())(val.value))\n .reduce((a, b) => bignumber_js__WEBPACK_IMPORTED_MODULE_1___default().sum(a, b), new (bignumber_js__WEBPACK_IMPORTED_MODULE_1___default())(0));\n const slpSpendAmount = sendRequests\n .map((val) => new (bignumber_js__WEBPACK_IMPORTED_MODULE_1___default())(val.value))\n .reduce((a, b) => bignumber_js__WEBPACK_IMPORTED_MODULE_1___default().sum(a, b), new (bignumber_js__WEBPACK_IMPORTED_MODULE_1___default())(0));\n if (slpSpendAmount.isLessThanOrEqualTo(0)) {\n throw new Error(\"Refusing to spend 0 tokens\");\n }\n if (slpSpendAmount.isGreaterThan(slpAvailableAmount)) {\n throw new Error(\"Not enough tokens to spend\");\n }\n let fundingSlpUtxos = [];\n let totalInputTokens = new (bignumber_js__WEBPACK_IMPORTED_MODULE_1___default())(0);\n for (let slputxo of slpUtxos) {\n const amountTooLow = totalInputTokens.isLessThan(slpSpendAmount);\n if (amountTooLow) {\n totalInputTokens = totalInputTokens.plus(slputxo.value);\n fundingSlpUtxos.push(slputxo);\n }\n else {\n break;\n }\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.importAuthenticationTemplate)(SlpTxoTemplate);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = await (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.authenticationTemplateToCompilerBCH)(template);\n const change = totalInputTokens.minus(slpSpendAmount);\n let values = sendRequests.map((val) => new (bignumber_js__WEBPACK_IMPORTED_MODULE_1___default())(val.value));\n if (change.isGreaterThan(new (bignumber_js__WEBPACK_IMPORTED_MODULE_1___default())(0))) {\n values.push(change);\n sendRequests.push({\n slpaddr: changeSlpaddr,\n tokenId: tokenId,\n value: new (bignumber_js__WEBPACK_IMPORTED_MODULE_1___default())(0),\n });\n }\n const bchSendRequests = sendRequests.map((val) => new _wallet_model_js__WEBPACK_IMPORTED_MODULE_7__.SendRequest({\n cashaddr: (0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_6__.toCashAddress)(val.slpaddr),\n value: _constant_js__WEBPACK_IMPORTED_MODULE_8__.DUST_UTXO_THRESHOLD,\n unit: _enum_js__WEBPACK_IMPORTED_MODULE_9__.UnitEnum.SAT,\n }));\n values = values.map((val) => val.shiftedBy(decimals));\n let result = new Uint8Array();\n for (const val of values) {\n result = new Uint8Array([\n ...result,\n ...[0x08],\n ...bigIntToBinUint64BE(BigInt(val.toString())),\n ]);\n }\n let sendTxoBytecode = compiler.generateBytecode({\n scriptId: \"send_lock\",\n data: {\n bytecode: {\n s_token_type: Uint8Array.from([...[0x01], ...[tokenType]]),\n s_token_id: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin)(tokenId),\n s_token_output_quantities: result,\n },\n },\n });\n if (!sendTxoBytecode.success) {\n throw new Error(sendTxoBytecode.errors.map((e) => e.error).join(\"\\n\"));\n }\n // enforce checking\n (0,slp_parser__WEBPACK_IMPORTED_MODULE_0__.parseSLP)(Buffer.from((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex)(sendTxoBytecode.bytecode), \"hex\"));\n return {\n SlpOutputs: [\n {\n lockingBytecode: sendTxoBytecode.bytecode,\n valueSatoshis: 0n,\n },\n ],\n FundingSlpUtxos: fundingSlpUtxos,\n BchSendRequests: bchSendRequests,\n };\n};\n// prettier-ignore\nconst SlpTxoTemplate = {\n \"$schema\": \"https://bitauth.com/schemas/authentication-template-v0.schema.json\",\n \"description\": \"SLP Token transaction output templates\",\n \"name\": \"SLP\",\n \"entities\": {\n \"genesis_variables\": {\n \"description\": \"Variables used in genesis template.\",\n \"name\": \"Genesis_Variables\",\n \"scripts\": [\n \"genesis_lock\",\n \"genesis_unlock\"\n ],\n \"variables\": {\n \"g_token_type\": {\n \"description\": \"1 to 2 byte integer\",\n \"name\": \"token_type\",\n \"type\": \"AddressData\"\n },\n \"g_token_ticker\": {\n \"description\": \"0 to ∞ bytes, suggested utf-8\",\n \"name\": \"token_ticker\",\n \"type\": \"AddressData\"\n },\n \"g_token_name\": {\n \"description\": \"0 to ∞ bytes, suggested utf-8\",\n \"name\": \"token_name\",\n \"type\": \"AddressData\"\n },\n \"g_token_document_url\": {\n \"description\": \"0 to ∞ bytes, suggested ascii\",\n \"name\": \"token_document_url\",\n \"type\": \"AddressData\"\n },\n \"g_token_document_hash\": {\n \"description\": \"0 bytes or 32 bytes\",\n \"name\": \"token_document_hash\",\n \"type\": \"AddressData\"\n },\n \"g_decimals\": {\n \"description\": \"1 byte in range 0x00-0x09\",\n \"name\": \"decimals\",\n \"type\": \"AddressData\"\n },\n \"g_mint_baton_vout\": {\n \"description\": \"0 bytes, or 1 byte in range 0x02-0xff\",\n \"name\": \"mint_baton_vout\",\n \"type\": \"AddressData\"\n },\n \"g_initial_token_mint_quantity\": {\n \"description\": \"8 byte integer\",\n \"name\": \"initial_token_mint_quantity\",\n \"type\": \"AddressData\"\n }\n }\n },\n \"send_variables\": {\n \"description\": \"\",\n \"name\": \"Send_Variables\",\n \"scripts\": [\n \"send_lock\",\n \"send_unlock\"\n ],\n \"variables\": {\n \"s_token_type\": {\n \"description\": \"1 to 2 byte integer\",\n \"name\": \"token_type\",\n \"type\": \"AddressData\"\n },\n \"s_token_id\": {\n \"description\": \"Token Id, genesis transaction hex\",\n \"name\": \"Token_Id\",\n \"type\": \"AddressData\"\n },\n \"s_token_output_quantities\": {\n \"description\": \"N 8 byte integer token amounts (up to 19). At least one is required. Each one is a push.\\nN BCH transaction outputs should be specified\",\n \"name\": \"Token Output Quantities\",\n \"type\": \"AddressData\"\n }\n }\n },\n \"mint_variables\": {\n \"description\": \"\",\n \"name\": \"Mint_Variables\",\n \"scripts\": [\n \"mint_lock\",\n \"mint_unlock\"\n ],\n \"variables\": {\n \"m_token_type\": {\n \"description\": \"1 to 2 byte integer\",\n \"name\": \"token_type\",\n \"type\": \"AddressData\"\n },\n \"m_token_id\": {\n \"description\": \"Token Id, genesis transaction hex\",\n \"name\": \"Token_Id\",\n \"type\": \"AddressData\"\n },\n \"m_mint_baton_vout\": {\n \"description\": \"0 bytes, or 1 byte in range 0x02-0xff\",\n \"name\": \"mint_baton_vout\",\n \"type\": \"AddressData\"\n },\n \"m_additional_token_quantity\": {\n \"description\": \"Amount of tokens to mint, 8 byte integer\",\n \"name\": \"Additinial token quantity\",\n \"type\": \"AddressData\"\n }\n }\n }\n },\n \"scenarios\": {\n \"genesis\": {\n \"data\": {\n \"bytecode\": {\n \"g_token_type\": \"0x01\",\n \"g_token_ticker\": \"0x00\",\n \"g_token_name\": \"0x00\",\n \"g_token_document_url\": \"0x00\",\n \"g_token_document_hash\": \"\",\n \"g_decimals\": \"0x09\",\n \"g_mint_baton_vout\": \"0x02\",\n \"g_initial_token_mint_quantity\": \"0x0102030405060708\"\n }\n },\n \"description\": \"Genesis\",\n \"name\": \"Genesis\",\n \"transaction\": {\n \"locktime\": 100\n }\n },\n \"send\": {\n \"data\": {\n \"bytecode\": {\n \"s_token_type\": \"0x01\",\n \"s_token_id\": \"0x0000000000000000'0000000000000000'0000000000000000'0000000000000000'\",\n \"s_token_output_quantities\": \"0x0000000000000000\"\n }\n },\n \"description\": \"Send\",\n \"name\": \"Send\",\n \"transaction\": {\n \"locktime\": 100\n }\n },\n \"mint\": {\n \"data\": {\n \"bytecode\": {\n \"m_token_type\": \"0x01\",\n \"m_token_id\": \"0x0000000000000000'0000000000000000'0000000000000000'0000000000000000'\",\n \"m_mint_baton_vout\": \"0x00\",\n \"m_additional_token_quantity\": \"0x0000000000000000\"\n }\n },\n \"description\": \"Mint\",\n \"name\": \"Mint\",\n \"transaction\": {\n \"locktime\": 100\n }\n }\n },\n \"scripts\": {\n \"genesis_unlock\": {\n \"fails\": [\n \"genesis\"\n ],\n \"name\": \"Genesis Unlock\",\n \"script\": \"// unlock script is required, so we leave it empty\",\n \"unlocks\": \"genesis_lock\"\n },\n \"send_unlock\": {\n \"fails\": [\n \"send\"\n ],\n \"name\": \"Send Unlock\",\n \"script\": \"\",\n \"unlocks\": \"send_lock\"\n },\n \"mint_unlock\": {\n \"fails\": [\n \"mint\"\n ],\n \"name\": \"Mint Unlock\",\n \"script\": \"\",\n \"unlocks\": \"mint_lock\"\n },\n \"genesis_lock\": {\n \"lockingType\": \"standard\",\n \"name\": \"Genesis\",\n \"script\": \"OP_RETURN <'SLP'0x00> g_token_type <'GENESIS'> g_token_ticker g_token_name g_token_document_url g_token_document_hash g_decimals g_mint_baton_vout g_initial_token_mint_quantity\"\n },\n \"send_lock\": {\n \"lockingType\": \"standard\",\n \"name\": \"Send\",\n \"script\": \"OP_RETURN <'SLP'0x00> s_token_type <'SEND'> <s_token_id> s_token_output_quantities\"\n },\n \"mint_lock\": {\n \"lockingType\": \"standard\",\n \"name\": \"Mint\",\n \"script\": \"OP_RETURN <'SLP'0x00> m_token_type <'MINT'> <m_token_id> m_mint_baton_vout m_additional_token_quantity\"\n }\n },\n \"supported\": [\n \"BCH_2020_05\"\n ],\n \"version\": 0\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/slp/SlpLibAuth.ts?");
1248
-
1249
- /***/ }),
1250
-
1251
- /***/ "./src/slp/SlpProvider.ts":
1252
- /*!********************************!*\
1253
- !*** ./src/slp/SlpProvider.ts ***!
1254
- \********************************/
1255
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1256
-
1257
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"_convertBalanceBigNumbers\": () => (/* binding */ _convertBalanceBigNumbers),\n/* harmony export */ \"_convertSlpTokenInfo\": () => (/* binding */ _convertSlpTokenInfo),\n/* harmony export */ \"_convertUtxoBigNumbers\": () => (/* binding */ _convertUtxoBigNumbers),\n/* harmony export */ \"_emptyTokenBalance\": () => (/* binding */ _emptyTokenBalance)\n/* harmony export */ });\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bignumber.js */ \"../../node_modules/bignumber.js/bignumber.js\");\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(bignumber_js__WEBPACK_IMPORTED_MODULE_0__);\n\nfunction _convertBalanceBigNumbers(balances) {\n balances.forEach((val) => (val.value = new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(val.value)));\n return balances;\n}\nfunction _convertUtxoBigNumbers(utxos) {\n utxos.forEach((val) => (val.value = new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(val.value)));\n return utxos;\n}\nfunction _convertSlpTokenInfo(tokenInfo) {\n if (!tokenInfo)\n return tokenInfo;\n for (const key in tokenInfo) {\n if (tokenInfo[key] === null) {\n tokenInfo[key] = \"\";\n }\n }\n tokenInfo.initialAmount = new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(tokenInfo.initialAmount);\n return tokenInfo;\n}\nfunction _emptyTokenBalance(tokenId) {\n return {\n value: new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(0),\n ticker: \"\",\n name: \"\",\n tokenId: tokenId,\n };\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/slp/SlpProvider.ts?");
1258
-
1259
- /***/ }),
1260
-
1261
- /***/ "./src/slp/index.ts":
1262
- /*!**************************!*\
1263
- !*** ./src/slp/index.ts ***!
1264
- \**************************/
1265
- /***/ ((module, __webpack_exports__, __webpack_require__) => {
1266
-
1267
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BigNumber\": () => (/* reexport default from dynamic */ bignumber_js__WEBPACK_IMPORTED_MODULE_2___default.a),\n/* harmony export */ \"GsppProvider\": () => (/* reexport safe */ _GsppProvider_js__WEBPACK_IMPORTED_MODULE_1__.GsppProvider),\n/* harmony export */ \"SlpDbProvider\": () => (/* reexport safe */ _SlpDbProvider_js__WEBPACK_IMPORTED_MODULE_0__.SlpDbProvider),\n/* harmony export */ \"SlpTokenType\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_3__.SlpTokenType)\n/* harmony export */ });\n/* harmony import */ var _SlpDbProvider_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SlpDbProvider.js */ \"./src/slp/SlpDbProvider.ts\");\n/* harmony import */ var _GsppProvider_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./GsppProvider.js */ \"./src/slp/GsppProvider.ts\");\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! bignumber.js */ \"../../node_modules/bignumber.js/bignumber.js\");\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(bignumber_js__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./interface.js */ \"./src/slp/interface.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_SlpDbProvider_js__WEBPACK_IMPORTED_MODULE_0__, _GsppProvider_js__WEBPACK_IMPORTED_MODULE_1__]);\n([_SlpDbProvider_js__WEBPACK_IMPORTED_MODULE_0__, _GsppProvider_js__WEBPACK_IMPORTED_MODULE_1__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/slp/index.ts?");
1268
-
1269
- /***/ }),
1270
-
1271
- /***/ "./src/slp/interface.ts":
1272
- /*!******************************!*\
1273
- !*** ./src/slp/interface.ts ***!
1274
- \******************************/
1275
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1276
-
1277
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"SlpTokenType\": () => (/* binding */ SlpTokenType)\n/* harmony export */ });\nvar SlpTokenType;\n(function (SlpTokenType) {\n SlpTokenType[SlpTokenType[\"Type1\"] = 1] = \"Type1\";\n SlpTokenType[SlpTokenType[\"NftParent\"] = 129] = \"NftParent\";\n SlpTokenType[SlpTokenType[\"NftChild\"] = 65] = \"NftChild\";\n})(SlpTokenType || (SlpTokenType = {}));\n\n\n//# sourceURL=webpack://mainnet-js/./src/slp/interface.ts?");
1278
-
1279
- /***/ }),
1280
-
1281
1081
  /***/ "./src/test/axios.ts":
1282
1082
  /*!***************************!*\
1283
1083
  !*** ./src/test/axios.ts ***!
@@ -1304,7 +1104,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
1304
1104
  \********************************/
1305
1105
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1306
1106
 
1307
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"buildEncodedTransaction\": () => (/* binding */ buildEncodedTransaction),\n/* harmony export */ \"getFeeAmount\": () => (/* binding */ getFeeAmount),\n/* harmony export */ \"getFeeAmountSimple\": () => (/* binding */ getFeeAmountSimple),\n/* harmony export */ \"getSuitableUtxos\": () => (/* binding */ getSuitableUtxos),\n/* harmony export */ \"signUnsignedTransaction\": () => (/* binding */ signUnsignedTransaction)\n/* harmony export */ });\n/* unused harmony exports buildP2pkhNonHdTransaction, prepareInputs, prepareOutputs, prepareOpReturnOutput, prepareTokenOutputs */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/schema/authentication-template.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/standard/p2pkh.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/compiler-bch/compiler-bch.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/transaction/generate-transaction.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/vm/instruction-sets/bch/2023/bch-2023-tokens.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./allocateFee.js */ \"./src/transaction/allocateFee.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n// Build a transaction for a p2pkh transaction for a non HD wallet\nasync function buildP2pkhNonHdTransaction({ inputs, outputs, signingKey, sourceAddress, fee = 0, discardChange = false, slpOutputs = [], feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__.FeePaidByEnum.change, changeAddress = \"\", }) {\n if (!signingKey) {\n throw new Error(\"Missing signing key when building transaction\");\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.importAuthenticationTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.authenticationTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = await (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.authenticationTemplateToCompilerBCH)(template);\n const inputAmount = await (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_4__.sumUtxoValue)(inputs);\n const sendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__.sumSendRequestAmounts)(outputs);\n const changeAmount = BigInt(inputAmount) - BigInt(sendAmount) - BigInt(fee);\n outputs = (0,_allocateFee_js__WEBPACK_IMPORTED_MODULE_6__.allocateFee)(outputs, fee, feePaidBy, changeAmount);\n const lockedOutputs = await prepareOutputs(outputs);\n if (!changeAddress) {\n changeAddress = sourceAddress;\n }\n if (discardChange !== true) {\n if (changeAmount > _constant_js__WEBPACK_IMPORTED_MODULE_7__.DUST_UTXO_THRESHOLD) {\n const changeLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.cashAddressToLockingBytecode)(changeAddress);\n if (typeof changeLockingBytecode === \"string\") {\n throw Error(changeLockingBytecode);\n }\n lockedOutputs.push({\n lockingBytecode: changeLockingBytecode.bytecode,\n valueSatoshis: BigInt(changeAmount),\n });\n }\n }\n const { preparedInputs, sourceOutputs } = prepareInputs({\n inputs,\n compiler,\n signingKey,\n sourceAddress,\n });\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.generateTransaction)({\n inputs: preparedInputs,\n locktime: 0,\n outputs: [...slpOutputs, ...lockedOutputs],\n version: 2,\n });\n if (!result.success) {\n throw Error(\"Error building transaction with fee\");\n }\n const tokenValidationResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.verifyTransactionTokens)(result.transaction, sourceOutputs);\n if (tokenValidationResult !== true && fee > 0) {\n throw tokenValidationResult;\n }\n return { transaction: result.transaction, sourceOutputs: sourceOutputs };\n}\nfunction prepareInputs({ inputs, compiler, signingKey, sourceAddress, }) {\n const preparedInputs = [];\n const sourceOutputs = [];\n for (const i of inputs) {\n const utxoTxnValue = i.satoshis;\n const utxoIndex = i.vout;\n // slice will create a clone of the array\n const utxoOutpointTransactionHash = new Uint8Array(i.txid.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));\n // reverse the cloned copy\n // utxoOutpointTransactionHash.reverse();\n if (!utxoOutpointTransactionHash || utxoIndex === undefined) {\n throw new Error(\"Missing unspent outpoint when building transaction\");\n }\n const libAuthToken = i.token && {\n amount: BigInt(i.token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.hexToBin)(i.token.tokenId),\n nft: i.token.capability !== undefined || i.token.commitment !== undefined\n ? {\n capability: i.token.capability,\n commitment: i.token.commitment !== undefined &&\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.hexToBin)(i.token.commitment),\n }\n : undefined,\n };\n const key = signingKey?.length ? signingKey : Uint8Array.from(Array(32));\n const newInput = {\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: key } },\n },\n valueSatoshis: BigInt(utxoTxnValue),\n script: \"unlock\",\n token: libAuthToken,\n },\n };\n preparedInputs.push(newInput);\n const lockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.cashAddressToLockingBytecode)(sourceAddress);\n if (typeof lockingBytecode === \"string\") {\n throw lockingBytecode;\n }\n sourceOutputs.push({\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: Uint8Array.from([]),\n // additional info for sourceOutputs\n lockingBytecode: lockingBytecode.bytecode,\n valueSatoshis: BigInt(utxoTxnValue),\n token: libAuthToken,\n });\n }\n return { preparedInputs, sourceOutputs };\n}\n/**\n * prepareOutputs - create outputs for a transaction from a list of send requests\n *\n * a wrapper function\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function prepareOutputs(outputs) {\n const lockedOutputs = [];\n for (const output of outputs) {\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest) {\n lockedOutputs.push(prepareTokenOutputs(output));\n continue;\n }\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.OpReturnData) {\n lockedOutputs.push(prepareOpReturnOutput(output));\n continue;\n }\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.cashAddressToLockingBytecode)(output.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const sendAmount = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__.amountInSatoshi)(output.value, output.unit);\n if (sendAmount % 1 !== 0) {\n throw Error(`Cannot send ${sendAmount} satoshis, (fractional sats do not exist, yet), please use an integer number.`);\n }\n const lockedOutput = {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(sendAmount),\n };\n lockedOutputs.push(lockedOutput);\n }\n return lockedOutputs;\n}\n/**\n * prepareOpReturnOutput - create an output for OP_RETURN data\n *\n * @returns A promise to a list of unspent outputs\n */\nfunction prepareOpReturnOutput(request) {\n return {\n lockingBytecode: request.buffer,\n valueSatoshis: BigInt(0),\n };\n}\n/**\n * prepareOpReturnOutput - create an output for token data\n *\n * @returns A libauth Output\n */\nfunction prepareTokenOutputs(request) {\n const token = request;\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.cashAddressToLockingBytecode)(request.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const libAuthToken = {\n amount: BigInt(token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.hexToBin)(token.tokenId),\n nft: token.capability !== undefined || token.commitment !== undefined\n ? {\n capability: token.capability,\n commitment: token.commitment !== undefined && (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.hexToBin)(token.commitment),\n }\n : undefined,\n };\n return {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(request.value || 1000),\n token: libAuthToken,\n };\n}\n/**\n * getSuitableUtxos - Filter a list of unspent transaction outputs to the minimum needed to complete a transaction\n *\n * a intermediate function\n *\n * @param unspentOutputs An unfiltered list of available unspent transaction outputs\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function getSuitableUtxos(inputs, amountRequired, bestHeight, feePaidBy, requests, ensureUtxos = [], tokenOperation = \"send\") {\n const suitableUtxos = [...ensureUtxos];\n let amountAvailable = BigInt(0);\n const tokenRequests = requests.filter((val) => val instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest);\n const availableInputs = inputs.slice();\n // find matching utxos for token transfers\n if (tokenOperation === \"send\") {\n for (const request of tokenRequests) {\n const tokenInputs = availableInputs.filter((val) => val.token?.tokenId === request.tokenId);\n const sameCommitmentTokens = [...suitableUtxos, ...tokenInputs].filter((val) => val.token?.capability === request.capability &&\n val.token?.commitment === request.commitment);\n if (sameCommitmentTokens.length) {\n const input = sameCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n if (request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_14__.NFTCapability.minting ||\n request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_14__.NFTCapability.mutable) {\n const changeCommitmentTokens = [\n ...suitableUtxos,\n ...tokenInputs,\n ].filter((val) => val.token?.capability === request.capability);\n if (changeCommitmentTokens.length) {\n const input = changeCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n }\n // handle splitting the hybrid (FT+NFT) token into its parts\n if (request.capability === undefined &&\n request.commitment === undefined &&\n [...suitableUtxos, ...tokenInputs]\n .map((val) => val.token?.tokenId)\n .includes(request.tokenId)) {\n continue;\n }\n throw Error(`No suitable token utxos available to send token with id \"${request.tokenId}\", capability \"${request.capability}\", commitment \"${request.commitment}\"`);\n }\n }\n // find plain bch outputs\n for (const u of availableInputs) {\n if (u.token) {\n continue;\n }\n if (u.coinbase && u.height && bestHeight) {\n const age = bestHeight - u.height;\n if (age > 100) {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n }\n else {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n // if amountRequired is not given, assume it is a max spend request, skip this condition\n if (amountRequired && amountAvailable > amountRequired) {\n break;\n }\n }\n const addEnsured = (suitableUtxos) => {\n return [...ensureUtxos, ...suitableUtxos].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n };\n // if the fee is split with a feePaidBy option, skip checking change.\n if (feePaidBy && feePaidBy != _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__.FeePaidByEnum.change) {\n return addEnsured(suitableUtxos);\n }\n // If the amount needed is met, or no amount is given, return\n if (typeof amountRequired === \"undefined\") {\n return addEnsured(suitableUtxos);\n }\n else if (amountAvailable < amountRequired) {\n const e = Error(`Amount required was not met, ${amountRequired} satoshis needed, ${amountAvailable} satoshis available`);\n e[\"data\"] = {\n required: amountRequired,\n available: amountAvailable,\n };\n throw e;\n }\n else {\n return addEnsured(suitableUtxos);\n }\n}\n// model-based imprecise and fast fee estimation\nasync function getFeeAmountSimple({ utxos, sendRequests, relayFeePerByteInSatoshi, slpOutputs, discardChange, }) {\n const inputSizeP2pkh = 148;\n const outputSizeP2pkh = 34;\n const inputTotalSize = utxos.reduce((prev, curr) => prev +\n (curr.token\n ? inputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (curr.token.commitment?.length ?? 0) / 2) +\n (curr.token.amount ? 9 : 0)\n : inputSizeP2pkh), 0);\n const outputSize = (sendRequest) => {\n if (sendRequest.hasOwnProperty(\"unit\")) {\n return outputSizeP2pkh;\n }\n else if (sendRequest.hasOwnProperty(\"tokenId\")) {\n const tokenRequest = sendRequest;\n return (outputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (tokenRequest.commitment?.length ?? 0) / 2) +\n (tokenRequest.amount ? 9 : 0));\n }\n else if (sendRequest.hasOwnProperty(\"buffer\")) {\n return 9 + sendRequest.buffer.length;\n }\n return 0;\n };\n const outputTotalSize = sendRequests.reduce((prev, curr) => prev + outputSize(curr), 0) +\n (discardChange ? 0 : outputSizeP2pkh);\n const slpTotalSize = slpOutputs.reduce((prev, curr) => prev + curr.lockingBytecode.length, 0);\n return ((inputTotalSize + outputTotalSize + slpTotalSize + 16) *\n relayFeePerByteInSatoshi);\n}\n// precise fee estimation\nasync function getFeeAmount({ utxos, sendRequests, privateKey, sourceAddress, relayFeePerByteInSatoshi, slpOutputs, feePaidBy, discardChange, }) {\n // build transaction\n if (utxos) {\n // Build the transaction to get the approximate size\n const { encodedTransaction: draftTransaction } = await buildEncodedTransaction({\n inputs: utxos,\n outputs: sendRequests,\n signingKey: privateKey,\n sourceAddress,\n fee: 0,\n discardChange: discardChange ?? false,\n slpOutputs,\n feePaidBy,\n changeAddress: \"\",\n });\n return draftTransaction.length * relayFeePerByteInSatoshi + 1;\n }\n else {\n throw Error(\"The available inputs in the wallet cannot satisfy this send request\");\n }\n}\n// Build encoded transaction\nasync function buildEncodedTransaction({ inputs, outputs, signingKey, sourceAddress, fee = 0, discardChange = false, slpOutputs = [], feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__.FeePaidByEnum.change, changeAddress = \"\", buildUnsigned = false, }) {\n const { transaction, sourceOutputs } = await buildP2pkhNonHdTransaction({\n inputs,\n outputs,\n signingKey,\n sourceAddress,\n fee,\n discardChange,\n slpOutputs,\n feePaidBy,\n changeAddress,\n });\n if (buildUnsigned === true) {\n transaction.inputs.forEach((input) => (input.unlockingBytecode = Uint8Array.from([])));\n }\n return { encodedTransaction: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.encodeTransaction)(transaction), sourceOutputs };\n}\nasync function signUnsignedTransaction(transaction, sourceOutputs, signingKey) {\n if (typeof transaction === \"string\") {\n transaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.hexToBin)(transaction);\n }\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.decodeTransaction)(transaction);\n if (typeof decoded === \"string\") {\n throw decoded;\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.importAuthenticationTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.authenticationTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.authenticationTemplateToCompilerBCH)(template);\n const transactionTemplate = { ...decoded };\n for (const [index, input] of decoded.inputs.entries()) {\n const sourceOutput = sourceOutputs[index];\n transactionTemplate.inputs[index] = {\n ...input,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: signingKey } },\n },\n valueSatoshis: sourceOutput.valueSatoshis,\n script: \"unlock\",\n token: sourceOutput.token,\n },\n };\n }\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.generateTransaction)(transactionTemplate);\n if (!result.success) {\n throw result.errors;\n }\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.encodeTransaction)(result.transaction);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/transaction/Wif.ts?");
1107
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"buildEncodedTransaction\": () => (/* binding */ buildEncodedTransaction),\n/* harmony export */ \"getFeeAmount\": () => (/* binding */ getFeeAmount),\n/* harmony export */ \"getFeeAmountSimple\": () => (/* binding */ getFeeAmountSimple),\n/* harmony export */ \"getSuitableUtxos\": () => (/* binding */ getSuitableUtxos),\n/* harmony export */ \"signUnsignedTransaction\": () => (/* binding */ signUnsignedTransaction)\n/* harmony export */ });\n/* unused harmony exports buildP2pkhNonHdTransaction, prepareInputs, prepareOutputs, prepareOpReturnOutput, prepareTokenOutputs */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/schema/authentication-template.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/standard/p2pkh.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/compiler-bch/compiler-bch.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/transaction/generate-transaction.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/vm/instruction-sets/bch/2023/bch-2023-tokens.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./allocateFee.js */ \"./src/transaction/allocateFee.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n// Build a transaction for a p2pkh transaction for a non HD wallet\nasync function buildP2pkhNonHdTransaction({ inputs, outputs, signingKey, sourceAddress, fee = 0, discardChange = false, feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__.FeePaidByEnum.change, changeAddress = \"\", }) {\n if (!signingKey) {\n throw new Error(\"Missing signing key when building transaction\");\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.importAuthenticationTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.authenticationTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = await (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.authenticationTemplateToCompilerBCH)(template);\n const inputAmount = await (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_4__.sumUtxoValue)(inputs);\n const sendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__.sumSendRequestAmounts)(outputs);\n const changeAmount = BigInt(inputAmount) - BigInt(sendAmount) - BigInt(fee);\n outputs = (0,_allocateFee_js__WEBPACK_IMPORTED_MODULE_6__.allocateFee)(outputs, fee, feePaidBy, changeAmount);\n const lockedOutputs = await prepareOutputs(outputs);\n if (!changeAddress) {\n changeAddress = sourceAddress;\n }\n if (discardChange !== true) {\n if (changeAmount > _constant_js__WEBPACK_IMPORTED_MODULE_7__.DUST_UTXO_THRESHOLD) {\n const changeLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.cashAddressToLockingBytecode)(changeAddress);\n if (typeof changeLockingBytecode === \"string\") {\n throw Error(changeLockingBytecode);\n }\n lockedOutputs.push({\n lockingBytecode: changeLockingBytecode.bytecode,\n valueSatoshis: BigInt(changeAmount),\n });\n }\n }\n const { preparedInputs, sourceOutputs } = prepareInputs({\n inputs,\n compiler,\n signingKey,\n sourceAddress,\n });\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.generateTransaction)({\n inputs: preparedInputs,\n locktime: 0,\n outputs: lockedOutputs,\n version: 2,\n });\n if (!result.success) {\n throw Error(\"Error building transaction with fee\");\n }\n const tokenValidationResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.verifyTransactionTokens)(result.transaction, sourceOutputs);\n if (tokenValidationResult !== true && fee > 0) {\n throw tokenValidationResult;\n }\n return { transaction: result.transaction, sourceOutputs: sourceOutputs };\n}\nfunction prepareInputs({ inputs, compiler, signingKey, sourceAddress, }) {\n const preparedInputs = [];\n const sourceOutputs = [];\n for (const i of inputs) {\n const utxoTxnValue = i.satoshis;\n const utxoIndex = i.vout;\n // slice will create a clone of the array\n const utxoOutpointTransactionHash = new Uint8Array(i.txid.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));\n // reverse the cloned copy\n // utxoOutpointTransactionHash.reverse();\n if (!utxoOutpointTransactionHash || utxoIndex === undefined) {\n throw new Error(\"Missing unspent outpoint when building transaction\");\n }\n const libAuthToken = i.token && {\n amount: BigInt(i.token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.hexToBin)(i.token.tokenId),\n nft: i.token.capability !== undefined || i.token.commitment !== undefined\n ? {\n capability: i.token.capability,\n commitment: i.token.commitment !== undefined &&\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.hexToBin)(i.token.commitment),\n }\n : undefined,\n };\n const key = signingKey?.length ? signingKey : Uint8Array.from(Array(32));\n const newInput = {\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: key } },\n },\n valueSatoshis: BigInt(utxoTxnValue),\n script: \"unlock\",\n token: libAuthToken,\n },\n };\n preparedInputs.push(newInput);\n const lockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.cashAddressToLockingBytecode)(sourceAddress);\n if (typeof lockingBytecode === \"string\") {\n throw lockingBytecode;\n }\n sourceOutputs.push({\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: Uint8Array.from([]),\n // additional info for sourceOutputs\n lockingBytecode: lockingBytecode.bytecode,\n valueSatoshis: BigInt(utxoTxnValue),\n token: libAuthToken,\n });\n }\n return { preparedInputs, sourceOutputs };\n}\n/**\n * prepareOutputs - create outputs for a transaction from a list of send requests\n *\n * a wrapper function\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function prepareOutputs(outputs) {\n const lockedOutputs = [];\n for (const output of outputs) {\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest) {\n lockedOutputs.push(prepareTokenOutputs(output));\n continue;\n }\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.OpReturnData) {\n lockedOutputs.push(prepareOpReturnOutput(output));\n continue;\n }\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.cashAddressToLockingBytecode)(output.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const sendAmount = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__.amountInSatoshi)(output.value, output.unit);\n if (sendAmount % 1 !== 0) {\n throw Error(`Cannot send ${sendAmount} satoshis, (fractional sats do not exist, yet), please use an integer number.`);\n }\n const lockedOutput = {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(sendAmount),\n };\n lockedOutputs.push(lockedOutput);\n }\n return lockedOutputs;\n}\n/**\n * prepareOpReturnOutput - create an output for OP_RETURN data\n *\n * @returns A promise to a list of unspent outputs\n */\nfunction prepareOpReturnOutput(request) {\n return {\n lockingBytecode: request.buffer,\n valueSatoshis: BigInt(0),\n };\n}\n/**\n * prepareOpReturnOutput - create an output for token data\n *\n * @returns A libauth Output\n */\nfunction prepareTokenOutputs(request) {\n const token = request;\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.cashAddressToLockingBytecode)(request.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const libAuthToken = {\n amount: BigInt(token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.hexToBin)(token.tokenId),\n nft: token.capability !== undefined || token.commitment !== undefined\n ? {\n capability: token.capability,\n commitment: token.commitment !== undefined && (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.hexToBin)(token.commitment),\n }\n : undefined,\n };\n return {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(request.value || 1000),\n token: libAuthToken,\n };\n}\n/**\n * getSuitableUtxos - Filter a list of unspent transaction outputs to the minimum needed to complete a transaction\n *\n * a intermediate function\n *\n * @param unspentOutputs An unfiltered list of available unspent transaction outputs\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function getSuitableUtxos(inputs, amountRequired, bestHeight, feePaidBy, requests, ensureUtxos = [], tokenOperation = \"send\") {\n const suitableUtxos = [...ensureUtxos];\n let amountAvailable = BigInt(0);\n const tokenRequests = requests.filter((val) => val instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest);\n const availableInputs = inputs.slice();\n // find matching utxos for token transfers\n if (tokenOperation === \"send\") {\n for (const request of tokenRequests) {\n const tokenInputs = availableInputs.filter((val) => val.token?.tokenId === request.tokenId);\n const sameCommitmentTokens = [...suitableUtxos, ...tokenInputs].filter((val) => val.token?.capability === request.capability &&\n val.token?.commitment === request.commitment);\n if (sameCommitmentTokens.length) {\n const input = sameCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n if (request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_14__.NFTCapability.minting ||\n request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_14__.NFTCapability.mutable) {\n const changeCommitmentTokens = [\n ...suitableUtxos,\n ...tokenInputs,\n ].filter((val) => val.token?.capability === request.capability);\n if (changeCommitmentTokens.length) {\n const input = changeCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n }\n // handle splitting the hybrid (FT+NFT) token into its parts\n if (request.capability === undefined &&\n request.commitment === undefined &&\n [...suitableUtxos, ...tokenInputs]\n .map((val) => val.token?.tokenId)\n .includes(request.tokenId)) {\n continue;\n }\n throw Error(`No suitable token utxos available to send token with id \"${request.tokenId}\", capability \"${request.capability}\", commitment \"${request.commitment}\"`);\n }\n }\n // find plain bch outputs\n for (const u of availableInputs) {\n if (u.token) {\n continue;\n }\n if (u.coinbase && u.height && bestHeight) {\n const age = bestHeight - u.height;\n if (age > 100) {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n }\n else {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n // if amountRequired is not given, assume it is a max spend request, skip this condition\n if (amountRequired && amountAvailable > amountRequired) {\n break;\n }\n }\n const addEnsured = (suitableUtxos) => {\n return [...ensureUtxos, ...suitableUtxos].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n };\n // if the fee is split with a feePaidBy option, skip checking change.\n if (feePaidBy && feePaidBy != _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__.FeePaidByEnum.change) {\n return addEnsured(suitableUtxos);\n }\n // If the amount needed is met, or no amount is given, return\n if (typeof amountRequired === \"undefined\") {\n return addEnsured(suitableUtxos);\n }\n else if (amountAvailable < amountRequired) {\n const e = Error(`Amount required was not met, ${amountRequired} satoshis needed, ${amountAvailable} satoshis available`);\n e[\"data\"] = {\n required: amountRequired,\n available: amountAvailable,\n };\n throw e;\n }\n else {\n return addEnsured(suitableUtxos);\n }\n}\n// model-based imprecise and fast fee estimation\nasync function getFeeAmountSimple({ utxos, sendRequests, relayFeePerByteInSatoshi, discardChange, }) {\n const inputSizeP2pkh = 148;\n const outputSizeP2pkh = 34;\n const inputTotalSize = utxos.reduce((prev, curr) => prev +\n (curr.token\n ? inputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (curr.token.commitment?.length ?? 0) / 2) +\n (curr.token.amount ? 9 : 0)\n : inputSizeP2pkh), 0);\n const outputSize = (sendRequest) => {\n if (sendRequest.hasOwnProperty(\"unit\")) {\n return outputSizeP2pkh;\n }\n else if (sendRequest.hasOwnProperty(\"tokenId\")) {\n const tokenRequest = sendRequest;\n return (outputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (tokenRequest.commitment?.length ?? 0) / 2) +\n (tokenRequest.amount ? 9 : 0));\n }\n else if (sendRequest.hasOwnProperty(\"buffer\")) {\n return 9 + sendRequest.buffer.length;\n }\n return 0;\n };\n const outputTotalSize = sendRequests.reduce((prev, curr) => prev + outputSize(curr), 0) +\n (discardChange ? 0 : outputSizeP2pkh);\n return (inputTotalSize + outputTotalSize + 16) * relayFeePerByteInSatoshi;\n}\n// precise fee estimation\nasync function getFeeAmount({ utxos, sendRequests, privateKey, sourceAddress, relayFeePerByteInSatoshi, feePaidBy, discardChange, }) {\n // build transaction\n if (utxos) {\n // Build the transaction to get the approximate size\n const { encodedTransaction: draftTransaction } = await buildEncodedTransaction({\n inputs: utxos,\n outputs: sendRequests,\n signingKey: privateKey,\n sourceAddress,\n fee: 0,\n discardChange: discardChange ?? false,\n feePaidBy,\n changeAddress: \"\",\n });\n return draftTransaction.length * relayFeePerByteInSatoshi + 1;\n }\n else {\n throw Error(\"The available inputs in the wallet cannot satisfy this send request\");\n }\n}\n// Build encoded transaction\nasync function buildEncodedTransaction({ inputs, outputs, signingKey, sourceAddress, fee = 0, discardChange = false, feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__.FeePaidByEnum.change, changeAddress = \"\", buildUnsigned = false, }) {\n const { transaction, sourceOutputs } = await buildP2pkhNonHdTransaction({\n inputs,\n outputs,\n signingKey,\n sourceAddress,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n });\n if (buildUnsigned === true) {\n transaction.inputs.forEach((input) => (input.unlockingBytecode = Uint8Array.from([])));\n }\n return { encodedTransaction: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.encodeTransaction)(transaction), sourceOutputs };\n}\nasync function signUnsignedTransaction(transaction, sourceOutputs, signingKey) {\n if (typeof transaction === \"string\") {\n transaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.hexToBin)(transaction);\n }\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.decodeTransaction)(transaction);\n if (typeof decoded === \"string\") {\n throw decoded;\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.importAuthenticationTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.authenticationTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.authenticationTemplateToCompilerBCH)(template);\n const transactionTemplate = { ...decoded };\n for (const [index, input] of decoded.inputs.entries()) {\n const sourceOutput = sourceOutputs[index];\n transactionTemplate.inputs[index] = {\n ...input,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: signingKey } },\n },\n valueSatoshis: sourceOutput.valueSatoshis,\n script: \"unlock\",\n token: sourceOutput.token,\n },\n };\n }\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.generateTransaction)(transactionTemplate);\n if (!result.success) {\n throw result.errors;\n }\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.encodeTransaction)(result.transaction);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/transaction/Wif.ts?");
1308
1108
 
1309
1109
  /***/ }),
1310
1110
 
@@ -1358,16 +1158,6 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1358
1158
 
1359
1159
  /***/ }),
1360
1160
 
1361
- /***/ "./src/util/bchaddr.ts":
1362
- /*!*****************************!*\
1363
- !*** ./src/util/bchaddr.ts ***!
1364
- \*****************************/
1365
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1366
-
1367
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"isCashAddress\": () => (/* reexport safe */ bchaddrjs_slp__WEBPACK_IMPORTED_MODULE_0__.isCashAddress),\n/* harmony export */ \"isSlpAddress\": () => (/* reexport safe */ bchaddrjs_slp__WEBPACK_IMPORTED_MODULE_0__.isSlpAddress),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ bchaddrjs_slp__WEBPACK_IMPORTED_MODULE_0__.isValidAddress),\n/* harmony export */ \"toCashAddress\": () => (/* reexport safe */ bchaddrjs_slp__WEBPACK_IMPORTED_MODULE_0__.toCashAddress),\n/* harmony export */ \"toSlpAddress\": () => (/* reexport safe */ bchaddrjs_slp__WEBPACK_IMPORTED_MODULE_0__.toSlpAddress)\n/* harmony export */ });\n/* harmony import */ var bchaddrjs_slp__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bchaddrjs-slp */ \"../../node_modules/bchaddrjs-slp/src/bchaddr.js\");\n/* harmony import */ var bchaddrjs_slp__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(bchaddrjs_slp__WEBPACK_IMPORTED_MODULE_0__);\n\n// import bchaddr from \"bchaddrjs-slp\";\n// export { isValidAddress, isCashAddress, isSlpAddress } from \"bchaddrjs-slp\";\n// export function toCashAddress(address: string) {\n// if ([\"bchreg\", \"slpreg\"].some(val => address.includes(val))) {\n// return bchaddr.toRegtestAddress(bchaddr.toCashAddress(address));\n// }\n// return bchaddr.toCashAddress(address);\n// }\n// export function toSlpAddress(address: string) {\n// if ([\"bchreg\", \"slpreg\"].some(val => address.includes(val))) {\n// return bchaddr.toSlpRegtestAddress(address);\n// }\n// return bchaddr.toSlpAddress(address);\n// }\n\n\n//# sourceURL=webpack://mainnet-js/./src/util/bchaddr.ts?");
1368
-
1369
- /***/ }),
1370
-
1371
1161
  /***/ "./src/util/browserNotSupported.ts":
1372
1162
  /*!*****************************************!*\
1373
1163
  !*** ./src/util/browserNotSupported.ts ***!
@@ -1424,7 +1214,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
1424
1214
  \************************************/
1425
1215
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1426
1216
 
1427
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"checkTokenaddr\": () => (/* binding */ checkTokenaddr),\n/* harmony export */ \"deriveCashaddr\": () => (/* binding */ deriveCashaddr),\n/* harmony export */ \"deriveTokenaddr\": () => (/* binding */ deriveTokenaddr),\n/* harmony export */ \"isTokenaddr\": () => (/* binding */ isTokenaddr),\n/* harmony export */ \"toCashaddr\": () => (/* binding */ toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* binding */ toTokenaddr)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _hash160_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hash160.js */ \"./src/util/hash160.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _hash160_js__WEBPACK_IMPORTED_MODULE_1__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _hash160_js__WEBPACK_IMPORTED_MODULE_1__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\nfunction deriveCashaddr(privateKey, networkPrefix) {\n let publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.secp256k1.derivePublicKeyCompressed(privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n let pkh = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(publicKey);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(networkPrefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkh, pkh);\n}\nfunction deriveTokenaddr(key, networkPrefix) {\n let publicKeyHash;\n // private key\n if (key.length === 32) {\n let publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.secp256k1.derivePublicKeyCompressed(key);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(publicKeyCompressed);\n }\n else if (key.length === 65) {\n // uncompressed public key\n let publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.secp256k1.compressPublicKey(key);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(publicKeyCompressed);\n }\n else if (key.length === 33) {\n // compressed public key\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(key);\n }\n else if (key.length === 20) {\n // public key hash\n publicKeyHash = key;\n }\n else {\n throw new Error(\"Unsupported type of key\");\n }\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(networkPrefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkhWithTokens, publicKeyHash);\n}\nfunction toCashaddr(tokenaddr) {\n let result;\n // If the address has a prefix decode it as is\n if (tokenaddr.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormat)(tokenaddr);\n }\n // otherwise, derive the network from the tokenaddr without prefix\n else {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormatWithoutPrefix)(tokenaddr);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(result.prefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkh, result.payload);\n}\nfunction toTokenaddr(cashaddr) {\n let result;\n // If the address has a prefix decode it as is\n if (cashaddr.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormat)(cashaddr);\n }\n // otherwise, derive the network from the cashaddr without prefix\n else {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormatWithoutPrefix)(cashaddr);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(result.prefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkhWithTokens, result.payload);\n}\nfunction isTokenaddr(address) {\n let result;\n // If the address has a prefix decode it as is\n if (address.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormat)(address);\n }\n else {\n // otherwise, derive the network from the address without prefix\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormatWithoutPrefix)(address);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n const info = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressVersionByte)(result.version);\n if (typeof info === \"string\")\n throw new Error(info);\n const type = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.cashAddressTypeBitsToType[info.typeBits];\n if (type === undefined) {\n throw Error(\"Wrong cashaddress type\");\n }\n return ([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkhWithTokens, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2shWithTokens].indexOf(type) !== -1);\n}\nfunction checkTokenaddr(cashaddr, enforce) {\n if (enforce && !isTokenaddr(cashaddr)) {\n throw new Error(\"Error trying to send to a non-tokenaware cash address\");\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/deriveCashaddr.ts?");
1217
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"checkTokenaddr\": () => (/* binding */ checkTokenaddr),\n/* harmony export */ \"deriveCashaddr\": () => (/* binding */ deriveCashaddr),\n/* harmony export */ \"deriveTokenaddr\": () => (/* binding */ deriveTokenaddr),\n/* harmony export */ \"isTokenaddr\": () => (/* binding */ isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* binding */ isValidAddress),\n/* harmony export */ \"toCashaddr\": () => (/* binding */ toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* binding */ toTokenaddr)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _hash160_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./hash160.js */ \"./src/util/hash160.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__, _hash160_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__, _hash160_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\nfunction isValidAddress(cashaddr) {\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeCashAddress)(cashaddr);\n if (typeof result === \"string\") {\n return false;\n }\n return true;\n}\nfunction deriveCashaddr(privateKey, networkPrefix) {\n let publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.secp256k1.derivePublicKeyCompressed(privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n let pkh = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_2__.hash160)(publicKey);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.encodeCashAddress)(networkPrefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.CashAddressType.p2pkh, pkh);\n}\nfunction deriveTokenaddr(key, networkPrefix) {\n let publicKeyHash;\n // private key\n if (key.length === 32) {\n let publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.secp256k1.derivePublicKeyCompressed(key);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_2__.hash160)(publicKeyCompressed);\n }\n else if (key.length === 65) {\n // uncompressed public key\n let publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.secp256k1.compressPublicKey(key);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_2__.hash160)(publicKeyCompressed);\n }\n else if (key.length === 33) {\n // compressed public key\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_2__.hash160)(key);\n }\n else if (key.length === 20) {\n // public key hash\n publicKeyHash = key;\n }\n else {\n throw new Error(\"Unsupported type of key\");\n }\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.encodeCashAddress)(networkPrefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.CashAddressType.p2pkhWithTokens, publicKeyHash);\n}\nfunction toCashaddr(tokenaddr) {\n let result;\n // If the address has a prefix decode it as is\n if (tokenaddr.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeCashAddressFormat)(tokenaddr);\n }\n // otherwise, derive the network from the tokenaddr without prefix\n else {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeCashAddressFormatWithoutPrefix)(tokenaddr);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.encodeCashAddress)(result.prefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.CashAddressType.p2pkh, result.payload);\n}\nfunction toTokenaddr(cashaddr) {\n let result;\n // If the address has a prefix decode it as is\n if (cashaddr.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeCashAddressFormat)(cashaddr);\n }\n // otherwise, derive the network from the cashaddr without prefix\n else {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeCashAddressFormatWithoutPrefix)(cashaddr);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.encodeCashAddress)(result.prefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.CashAddressType.p2pkhWithTokens, result.payload);\n}\nfunction isTokenaddr(address) {\n let result;\n // If the address has a prefix decode it as is\n if (address.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeCashAddressFormat)(address);\n }\n else {\n // otherwise, derive the network from the address without prefix\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeCashAddressFormatWithoutPrefix)(address);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n const info = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeCashAddressVersionByte)(result.version);\n if (typeof info === \"string\")\n throw new Error(info);\n const type = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.cashAddressTypeBitsToType[info.typeBits];\n if (type === undefined) {\n throw Error(\"Wrong cashaddress type\");\n }\n return ([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.CashAddressType.p2pkhWithTokens, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.CashAddressType.p2shWithTokens].indexOf(type) !== -1);\n}\nfunction checkTokenaddr(cashaddr, enforce) {\n if (enforce && !isTokenaddr(cashaddr)) {\n throw new Error(\"Error trying to send to a non-tokenaware cash address\");\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/deriveCashaddr.ts?");
1428
1218
 
1429
1219
  /***/ }),
1430
1220
 
@@ -1448,16 +1238,6 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1448
1238
 
1449
1239
  /***/ }),
1450
1240
 
1451
- /***/ "./src/util/eventsource.ts":
1452
- /*!*********************************!*\
1453
- !*** ./src/util/eventsource.ts ***!
1454
- \*********************************/
1455
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1456
-
1457
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var eventsource__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! eventsource */ \"?ec4c\");\n/* harmony import */ var eventsource__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(eventsource__WEBPACK_IMPORTED_MODULE_0__);\n\n\nlet EventSource;\nif ((0,_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_1__.getRuntimePlatform)() != \"node\") {\n EventSource = globalThis.EventSource;\n}\nelse {\n EventSource = (eventsource__WEBPACK_IMPORTED_MODULE_0___default());\n}\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (EventSource);\n\n\n//# sourceURL=webpack://mainnet-js/./src/util/eventsource.ts?");
1458
-
1459
- /***/ }),
1460
-
1461
1241
  /***/ "./src/util/floor.ts":
1462
1242
  /*!***************************!*\
1463
1243
  !*** ./src/util/floor.ts ***!
@@ -1524,7 +1304,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1524
1304
  \***************************/
1525
1305
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1526
1306
 
1527
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BalanceResponse\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__.BalanceResponse),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.RuntimePlatform),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convert),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convertObject),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _delay_js__WEBPACK_IMPORTED_MODULE_8__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__.derivedNetwork),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getRandomInt\": () => (/* reexport safe */ _randomInt_js__WEBPACK_IMPORTED_MODULE_19__.getRandomInt),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__.getUsdRate),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _hash160_js__WEBPACK_IMPORTED_MODULE_15__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.isTokenaddr),\n/* harmony export */ \"randomValues\": () => (/* reexport module object */ _randomValues_js__WEBPACK_IMPORTED_MODULE_21__),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__.sanitizeUnit),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.sha256),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_22__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.utf8ToBin)\n/* harmony export */ });\n/* harmony import */ var _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _base64_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64.js */ \"./src/util/base64.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _convert_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./convert.js */ \"./src/util/convert.ts\");\n/* harmony import */ var _delay_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./deriveNetwork.js */ \"./src/util/deriveNetwork.ts\");\n/* harmony import */ var _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/getAddrsByXpubKey.js */ \"./src/util/getAddrsByXpubKey.ts\");\n/* harmony import */ var _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./getUsdRate.js */ \"./src/util/getUsdRate.ts\");\n/* harmony import */ var _hash160_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./hash160.js */ \"./src/util/hash160.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./sanitizeAddress.js */ \"./src/util/sanitizeAddress.ts\");\n/* harmony import */ var _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _randomInt_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./randomInt.js */ \"./src/util/randomInt.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _randomValues_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./randomValues.js */ \"./src/util/randomValues.ts\");\n/* harmony import */ var _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__]);\n([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/index.ts?");
1307
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BalanceResponse\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__.BalanceResponse),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.RuntimePlatform),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convert),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convertObject),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _delay_js__WEBPACK_IMPORTED_MODULE_8__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__.derivedNetwork),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getRandomInt\": () => (/* reexport safe */ _randomInt_js__WEBPACK_IMPORTED_MODULE_19__.getRandomInt),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__.getUsdRate),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _hash160_js__WEBPACK_IMPORTED_MODULE_15__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.isValidAddress),\n/* harmony export */ \"randomValues\": () => (/* reexport module object */ _randomValues_js__WEBPACK_IMPORTED_MODULE_21__),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__.sanitizeUnit),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.sha256),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_22__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.utf8ToBin)\n/* harmony export */ });\n/* harmony import */ var _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _base64_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64.js */ \"./src/util/base64.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _convert_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./convert.js */ \"./src/util/convert.ts\");\n/* harmony import */ var _delay_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./deriveNetwork.js */ \"./src/util/deriveNetwork.ts\");\n/* harmony import */ var _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/getAddrsByXpubKey.js */ \"./src/util/getAddrsByXpubKey.ts\");\n/* harmony import */ var _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./getUsdRate.js */ \"./src/util/getUsdRate.ts\");\n/* harmony import */ var _hash160_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./hash160.js */ \"./src/util/hash160.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./sanitizeAddress.js */ \"./src/util/sanitizeAddress.ts\");\n/* harmony import */ var _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _randomInt_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./randomInt.js */ \"./src/util/randomInt.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _randomValues_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./randomValues.js */ \"./src/util/randomValues.ts\");\n/* harmony import */ var _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__]);\n([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_23__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/index.ts?");
1528
1308
 
1529
1309
  /***/ }),
1530
1310
 
@@ -1624,7 +1404,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1624
1404
  \****************************/
1625
1405
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1626
1406
 
1627
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BaseWallet\": () => (/* binding */ BaseWallet),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId)\n/* harmony export */ });\n/* harmony import */ var _db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../db/getStorageProvider.js */ \"./src/db/getStorageProvider.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_enum_js__WEBPACK_IMPORTED_MODULE_0__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_enum_js__WEBPACK_IMPORTED_MODULE_0__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param {string} name name of the wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n this.derivationPath = \"m/44'/0'/0'/0/0\";\n this.parentDerivationPath = \"m/44'/0'/0'\";\n this.name = name;\n this.network = network;\n this.walletType = walletType;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet ? false : true;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet) {\n throw Error(\"getNetworkProvider called on base wallet\");\n }\n /**\n * getDepositAddress - get a wallet deposit address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositAddress|/wallet/deposit_address} for REST endpoint\n *\n * @returns The deposit address as a string\n */\n getDepositAddress() {\n return this.address;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * a high-level function\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositQr|/wallet/deposit_qr} for REST endpoint\n *\n * @returns The qrcode for the address\n */\n getDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__.qrAddress)(this.getDepositAddress());\n }\n // Get mnemonic and derivation path for wallet\n getSeed() {\n if (!this.mnemonic) {\n throw Error(\"Wallet mnemonic seed phrase not set\");\n }\n if (!this.derivationPath) {\n throw Error(\"Wallet derivation path not set\");\n }\n return {\n seed: this.mnemonic,\n derivationPath: this.derivationPath,\n parentDerivationPath: this.parentDerivationPath,\n };\n }\n /**\n * fromId - create a wallet from encoded walletId string\n *\n * @param walletId walletId options to steer the creation process\n *\n * @returns wallet instantiated accordingly to the walletId rules\n */\n static async fromId(walletId) {\n return new this().fromId(walletId);\n }\n /**\n * fromSeed - create a wallet using the seed phrase and derivation path\n *\n * unless specified the derivation path m/44'/245'/0'/0/0 will be userd\n * this derivation path is standard for Electron Cash SLP and other SLP enabled wallets\n *\n * @param seed BIP39 12 word seed phrase\n * @param derivationPath BIP44 HD wallet derivation path to get a single the private key from hierarchy\n *\n * @returns instantiated wallet\n */\n static async fromSeed(seed, derivationPath) {\n return new this().fromSeed(seed, derivationPath);\n }\n /**\n * newRandom - create a random wallet\n *\n * if `name` parameter is specified, the wallet will also be persisted to DB\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async newRandom(name = \"\", dbName) {\n return new this().newRandom(name, dbName);\n }\n /**\n * watchOnly - create a watch-only wallet\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress, token aware cashaddress or slpaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async watchOnly(address) {\n return new this().watchOnly(address);\n }\n /**\n * named - create a named wallet\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n * @param force force recreate wallet in the database if a record already exist\n *\n * @returns instantiated wallet\n */\n static async named(name, dbName, force) {\n return new this().named(name, dbName, force);\n }\n /**\n * replaceNamed - replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async replaceNamed(name, walletId, dbName) {\n return new this().replaceNamed(name, walletId, dbName);\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n static async namedExists(name, dbName) {\n return new this().namedExists(name, dbName);\n }\n //#endregion Constructors\n //#region Protected implementations\n /**\n * generate creates a new wallet\n * @throws {Error} if called on BaseWallet\n */\n generate() {\n throw Error(\"generate called on base wallet\");\n }\n /**\n * fromId - creates a wallet from serialized string\n *\n * @throws {Error} if called on BaseWallet\n */\n fromId(walletId) {\n let [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n switch (walletType) {\n case \"watch\":\n if (arg2) {\n // watch:testnet:bchtest:qq1234567\n return this.watchOnly(`${arg1}:${arg2}`);\n }\n // watch:testnet:qq1234567\n return this.watchOnly(`${arg1}`);\n case \"named\":\n if (arg2) {\n // named:testnet:wallet_1:my_database\n return this.named(arg1, arg2);\n }\n else {\n // named:testnet:wallet_1\n return this.named(arg1);\n }\n case \"seed\":\n if (arg2) {\n // seed:testnet:table later ... stove kitten pluck:m/44'/0'/0'/0/0\n return this.fromSeed(arg1, arg2);\n }\n // seed:testnet:table later ... stove kitten pluck\n return this.fromSeed(arg1);\n default:\n throw Error(`Unknown wallet type '${walletType}'`);\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(\n // @ts-ignore\n mnemonic, \n // @ts-ignore\n derivationPath) {\n throw Error(\"fromSeed called on base wallet\");\n }\n /**\n * newRandom (internal) if the wallet is named, get or create it; otherwise create a random\n * unnamed wallet\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n */\n async newRandom(name, dbName) {\n if (name.length > 0) {\n return this.named(name, dbName);\n }\n else {\n return this.generate();\n }\n }\n // @ts-ignore\n async watchOnly(address) {\n throw Error(\"fromSeed called on base wallet\");\n }\n /**\n * named (internal) get a named wallet from the database or create a new one.\n * Note: this function should behave identically if\n *\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n * @param {boolean} forceNew attempt to overwrite an existing wallet\n *\n * @throws {Error} if forceNew is true and the wallet already exists\n * @returns a promise to a named wallet\n */\n async named(name, dbName, forceNew = false) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : this.network;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n if (savedWalletRecord) {\n await db.close();\n if (forceNew) {\n throw Error(`A wallet with the name ${name} already exists in ${dbName}`);\n }\n let recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n let wallet = await this.generate();\n await db.addWallet(wallet.name, wallet.toDbString());\n await db.close();\n return wallet;\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * replaceNamed - Replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n async replaceNamed(name, walletId, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : this.network;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await this.fromId(walletId);\n if (savedWalletRecord) {\n await db.updateWallet(name, walletId);\n }\n else {\n await db.addWallet(name, walletId);\n }\n await db.close();\n return this;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n async namedExists(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n dbName = dbName ? dbName : this.network;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n return savedWalletRecord !== undefined;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n //#endregion Protected implementations\n //#region Serialization\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Watch) {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n return \"\";\n }\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n if (this.name) {\n return `named:${this.network}:${this.name}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Watch) {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n return \"\";\n }\n //#endregion Serialization\n //#region Funds\n // @ts-ignore\n async getBalance(rawUnit) {\n throw Error(\"sendMax called on base wallet\");\n }\n // @ts-ignore\n async getMaxAmountToSend(params) {\n throw Error(\"getMaxAmountToSend called on base wallet\");\n }\n // @ts-ignore\n async send(requests, options) {\n throw Error(\"send called on base wallet\");\n }\n // @ts-ignore\n async sendMax(address, options) {\n throw Error(\"sendMax called on base wallet\");\n }\n}\n/**\n * _checkContextSafety (internal) if running in nodejs, will disable saving\n * mainnet wallets on public servers if ALLOW_MAINNET_USER_WALLETS is set to false\n * @param {BaseWallet} wallet a wallet\n */\nconst _checkContextSafety = function (wallet) {\n if ((0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet) {\n throw Error(`Refusing to save wallet in an open public database, remove ALLOW_MAINNET_USER_WALLETS=\"false\", if this service is secure and private`);\n }\n }\n }\n};\n/**\n * getNamedWalletId - get the full wallet id from the database\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\nasync function getNamedWalletId(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n dbName = dbName ? dbName : dbName;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n if (savedWalletRecord !== undefined) {\n return savedWalletRecord.wallet;\n }\n else {\n throw Error(`No record was found for ${name} in db: ${dbName}`);\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
1407
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BaseWallet\": () => (/* binding */ BaseWallet),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId)\n/* harmony export */ });\n/* harmony import */ var _db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../db/getStorageProvider.js */ \"./src/db/getStorageProvider.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_enum_js__WEBPACK_IMPORTED_MODULE_0__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_enum_js__WEBPACK_IMPORTED_MODULE_0__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param {string} name name of the wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n this.derivationPath = \"m/44'/0'/0'/0/0\";\n this.parentDerivationPath = \"m/44'/0'/0'\";\n this.name = name;\n this.network = network;\n this.walletType = walletType;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet ? false : true;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet) {\n throw Error(\"getNetworkProvider called on base wallet\");\n }\n /**\n * getDepositAddress - get a wallet deposit address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositAddress|/wallet/deposit_address} for REST endpoint\n *\n * @returns The deposit address as a string\n */\n getDepositAddress() {\n return this.address;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * a high-level function\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositQr|/wallet/deposit_qr} for REST endpoint\n *\n * @returns The qrcode for the address\n */\n getDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__.qrAddress)(this.getDepositAddress());\n }\n // Get mnemonic and derivation path for wallet\n getSeed() {\n if (!this.mnemonic) {\n throw Error(\"Wallet mnemonic seed phrase not set\");\n }\n if (!this.derivationPath) {\n throw Error(\"Wallet derivation path not set\");\n }\n return {\n seed: this.mnemonic,\n derivationPath: this.derivationPath,\n parentDerivationPath: this.parentDerivationPath,\n };\n }\n /**\n * fromId - create a wallet from encoded walletId string\n *\n * @param walletId walletId options to steer the creation process\n *\n * @returns wallet instantiated accordingly to the walletId rules\n */\n static async fromId(walletId) {\n return new this().fromId(walletId);\n }\n /**\n * fromSeed - create a wallet using the seed phrase and derivation path\n *\n * unless specified the derivation path m/44'/245'/0'/0/0 will be userd\n * this derivation path is standard for Electron Cash SLP and other SLP enabled wallets\n *\n * @param seed BIP39 12 word seed phrase\n * @param derivationPath BIP44 HD wallet derivation path to get a single the private key from hierarchy\n *\n * @returns instantiated wallet\n */\n static async fromSeed(seed, derivationPath) {\n return new this().fromSeed(seed, derivationPath);\n }\n /**\n * newRandom - create a random wallet\n *\n * if `name` parameter is specified, the wallet will also be persisted to DB\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async newRandom(name = \"\", dbName) {\n return new this().newRandom(name, dbName);\n }\n /**\n * watchOnly - create a watch-only wallet\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress, token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async watchOnly(address) {\n return new this().watchOnly(address);\n }\n /**\n * named - create a named wallet\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n * @param force force recreate wallet in the database if a record already exist\n *\n * @returns instantiated wallet\n */\n static async named(name, dbName, force) {\n return new this().named(name, dbName, force);\n }\n /**\n * replaceNamed - replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async replaceNamed(name, walletId, dbName) {\n return new this().replaceNamed(name, walletId, dbName);\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n static async namedExists(name, dbName) {\n return new this().namedExists(name, dbName);\n }\n //#endregion Constructors\n //#region Protected implementations\n /**\n * generate creates a new wallet\n * @throws {Error} if called on BaseWallet\n */\n generate() {\n throw Error(\"generate called on base wallet\");\n }\n /**\n * fromId - creates a wallet from serialized string\n *\n * @throws {Error} if called on BaseWallet\n */\n fromId(walletId) {\n let [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n switch (walletType) {\n case \"watch\":\n if (arg2) {\n // watch:testnet:bchtest:qq1234567\n return this.watchOnly(`${arg1}:${arg2}`);\n }\n // watch:testnet:qq1234567\n return this.watchOnly(`${arg1}`);\n case \"named\":\n if (arg2) {\n // named:testnet:wallet_1:my_database\n return this.named(arg1, arg2);\n }\n else {\n // named:testnet:wallet_1\n return this.named(arg1);\n }\n case \"seed\":\n if (arg2) {\n // seed:testnet:table later ... stove kitten pluck:m/44'/0'/0'/0/0\n return this.fromSeed(arg1, arg2);\n }\n // seed:testnet:table later ... stove kitten pluck\n return this.fromSeed(arg1);\n default:\n throw Error(`Unknown wallet type '${walletType}'`);\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(\n // @ts-ignore\n mnemonic, \n // @ts-ignore\n derivationPath) {\n throw Error(\"fromSeed called on base wallet\");\n }\n /**\n * newRandom (internal) if the wallet is named, get or create it; otherwise create a random\n * unnamed wallet\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n */\n async newRandom(name, dbName) {\n if (name.length > 0) {\n return this.named(name, dbName);\n }\n else {\n return this.generate();\n }\n }\n // @ts-ignore\n async watchOnly(address) {\n throw Error(\"fromSeed called on base wallet\");\n }\n /**\n * named (internal) get a named wallet from the database or create a new one.\n * Note: this function should behave identically if\n *\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n * @param {boolean} forceNew attempt to overwrite an existing wallet\n *\n * @throws {Error} if forceNew is true and the wallet already exists\n * @returns a promise to a named wallet\n */\n async named(name, dbName, forceNew = false) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : this.network;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n if (savedWalletRecord) {\n await db.close();\n if (forceNew) {\n throw Error(`A wallet with the name ${name} already exists in ${dbName}`);\n }\n let recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n let wallet = await this.generate();\n await db.addWallet(wallet.name, wallet.toDbString());\n await db.close();\n return wallet;\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * replaceNamed - Replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n async replaceNamed(name, walletId, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : this.network;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await this.fromId(walletId);\n if (savedWalletRecord) {\n await db.updateWallet(name, walletId);\n }\n else {\n await db.addWallet(name, walletId);\n }\n await db.close();\n return this;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n async namedExists(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n dbName = dbName ? dbName : this.network;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n return savedWalletRecord !== undefined;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n //#endregion Protected implementations\n //#region Serialization\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Watch) {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n return \"\";\n }\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n if (this.name) {\n return `named:${this.network}:${this.name}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Watch) {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n return \"\";\n }\n //#endregion Serialization\n //#region Funds\n // @ts-ignore\n async getBalance(rawUnit) {\n throw Error(\"sendMax called on base wallet\");\n }\n // @ts-ignore\n async getMaxAmountToSend(params) {\n throw Error(\"getMaxAmountToSend called on base wallet\");\n }\n // @ts-ignore\n async send(requests, options) {\n throw Error(\"send called on base wallet\");\n }\n // @ts-ignore\n async sendMax(address, options) {\n throw Error(\"sendMax called on base wallet\");\n }\n}\n/**\n * _checkContextSafety (internal) if running in nodejs, will disable saving\n * mainnet wallets on public servers if ALLOW_MAINNET_USER_WALLETS is set to false\n * @param {BaseWallet} wallet a wallet\n */\nconst _checkContextSafety = function (wallet) {\n if ((0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet) {\n throw Error(`Refusing to save wallet in an open public database, remove ALLOW_MAINNET_USER_WALLETS=\"false\", if this service is secure and private`);\n }\n }\n }\n};\n/**\n * getNamedWalletId - get the full wallet id from the database\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\nasync function getNamedWalletId(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n dbName = dbName ? dbName : dbName;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n if (savedWalletRecord !== undefined) {\n return savedWalletRecord.wallet;\n }\n else {\n throw Error(`No record was found for ${name} in db: ${dbName}`);\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
1628
1408
 
1629
1409
  /***/ }),
1630
1410
 
@@ -1638,23 +1418,13 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1638
1418
 
1639
1419
  /***/ }),
1640
1420
 
1641
- /***/ "./src/wallet/Slp.ts":
1642
- /*!***************************!*\
1643
- !*** ./src/wallet/Slp.ts ***!
1644
- \***************************/
1645
- /***/ ((module, __webpack_exports__, __webpack_require__) => {
1646
-
1647
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestSlp\": () => (/* binding */ RegTestSlp),\n/* harmony export */ \"RegTestWatchSlp\": () => (/* binding */ RegTestWatchSlp),\n/* harmony export */ \"RegTestWifSlp\": () => (/* binding */ RegTestWifSlp),\n/* harmony export */ \"Slp\": () => (/* binding */ Slp),\n/* harmony export */ \"TestNetSlp\": () => (/* binding */ TestNetSlp),\n/* harmony export */ \"TestNetWatchSlp\": () => (/* binding */ TestNetWatchSlp),\n/* harmony export */ \"TestNetWifSlp\": () => (/* binding */ TestNetWifSlp),\n/* harmony export */ \"WatchSlp\": () => (/* binding */ WatchSlp),\n/* harmony export */ \"WifSlp\": () => (/* binding */ WifSlp)\n/* harmony export */ });\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _slp_interface_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../slp/interface.js */ \"./src/slp/interface.ts\");\n/* harmony import */ var _slp_SlpDbProvider_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../slp/SlpDbProvider.js */ \"./src/slp/SlpDbProvider.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bignumber.js */ \"../../node_modules/bignumber.js/bignumber.js\");\n/* harmony import */ var bignumber_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(bignumber_js__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _slp_SlpLibAuth_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../slp/SlpLibAuth.js */ \"./src/slp/SlpLibAuth.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/bchaddr.js */ \"../../node_modules/bchaddrjs-slp/src/bchaddr.js\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _slp_GsppProvider_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../slp/GsppProvider.js */ \"./src/slp/GsppProvider.ts\");\n/* harmony import */ var _util_delay_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_slp_GsppProvider_js__WEBPACK_IMPORTED_MODULE_4__, _slp_SlpDbProvider_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_7__, _slp_SlpLibAuth_js__WEBPACK_IMPORTED_MODULE_9__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_10__, _Util_js__WEBPACK_IMPORTED_MODULE_13__]);\n([_slp_GsppProvider_js__WEBPACK_IMPORTED_MODULE_4__, _slp_SlpDbProvider_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_7__, _slp_SlpLibAuth_js__WEBPACK_IMPORTED_MODULE_9__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_10__, _Util_js__WEBPACK_IMPORTED_MODULE_13__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Class to manage an slp enabled wallet.\n */\nclass Slp {\n /**\n * Initializes an Slp Wallet.\n *\n * @param wallet A non-slp wallet object\n */\n constructor(wallet) {\n // a loookup table of spent inputs to keep track of NFT parent token consumption. related to a bug in SLPDB\n this.spentParentUtxos = [];\n this.slpaddr = (0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_2__.toSlpAddress)(wallet.cashaddr);\n this.wallet = wallet;\n let provider = Slp.defaultProvider;\n if ((0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_3__.getRuntimePlatform)() === _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_3__.RuntimePlatform.node &&\n process.env.SLP_PROVIDER)\n provider = process.env.SLP_PROVIDER;\n if (provider === \"gspp\") {\n this.provider = new _slp_GsppProvider_js__WEBPACK_IMPORTED_MODULE_4__.GsppProvider(this.wallet.network);\n }\n else {\n // provider === \"slpdb\"\n this.provider = new _slp_SlpDbProvider_js__WEBPACK_IMPORTED_MODULE_5__.SlpDbProvider(this.wallet.network);\n }\n }\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__.Wallet;\n }\n /**\n * setProvider - sets the provider to fetch slp data from\n */\n setProvider(provider) {\n return (this.provider = provider);\n }\n /**\n * getDepositAddress - get the slp deposit address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet%2Fslp/slpDepositAddress|/wallet/slp/deposit_address} for REST endpoint\n *\n * @returns The the slp address as a string\n */\n getDepositAddress() {\n return this.slpaddr;\n }\n /**\n * getDepositQr - get an slp address qrcode, encoded for display on the web\n *\n * a high-level function\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet%2Fslp/slpDepositQr|/wallet/slp/deposit_qr} for REST endpoint\n *\n * @returns The qrcode for the slp address\n */\n getDepositQr() {\n const result = (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_7__.qrAddress)(this.slpaddr);\n result.alt = \"A Bitcoin Cash Simple Ledger Protocol QR Code\";\n return result;\n }\n /**\n * getTokenInfo - get data associated with a token\n *\n * a high-level function\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet%2Fslp/slpTokenInfo|/wallet/slp/token_info} for REST endpoint\n *\n * @param tokenId The tokenId to request information about\n *\n * @returns Promise to the slp token info or undefined.\n */\n getTokenInfo(tokenId) {\n return this.provider.SlpTokenInfo(tokenId);\n }\n /**\n * getSlpOutpoints - get a list of SLP unspent outpoints\n *\n * an intermediate function contributing to the output of wallet.getUtxos() and /wallet/utxos for slp enabled wallets\n *\n * @param slpaddr The slpaddr to request slp unspent outpoints for\n *\n * @returns Promise to a list of slp unspent outpoints\n */\n async getSlpOutpoints() {\n return this.provider.SlpOutpoints(this.slpaddr);\n }\n /**\n * getSlpUtxos - get a list of SLP unspent outputs\n *\n * @returns Promise to a list of slp unspent outputs\n */\n async getSlpUtxos() {\n return this.provider.SlpUtxos(this.slpaddr);\n }\n /**\n * getFormattedSlpUtxos - get a list of unspent outputs\n *\n * an intermediate function\n *\n * @returns Promise to a list of slp formatted unspent outputs\n */\n async getFormattedSlpUtxos() {\n const utxos = await this.getSlpUtxos();\n return utxos.map((val) => {\n let utxo = {};\n utxo.ticker = val.ticker;\n utxo.tokenId = val.tokenId;\n utxo.value = val.value.toString();\n utxo.satoshis = val.satoshis;\n utxo.decimals = val.decimals;\n utxo.txId = val.txid;\n utxo.index = val.vout;\n utxo.utxoId = utxo.txId + \":\" + utxo.index;\n utxo.type = val.type;\n return utxo;\n });\n }\n /**\n * getBatonUtxos - get a list of baton unspent outputs\n *\n * an intermediate function\n *\n * @param tokenId The id of the slp token\n *\n * @returns Promise to a list of slp unspent outputs\n */\n async getBatonUtxos(tokenId) {\n return this.provider.SlpBatonUtxos(this.slpaddr, tokenId);\n }\n /**\n * getHistory - get a transaction history for a particular address\n *\n * an intermediate function\n *\n * @param tokenId The id of the slp token\n *\n * @returns Promise to a list of transactions\n */\n async getHistory(tokenId) {\n return this.provider.SlpAddressTransactionHistory(this.slpaddr, tokenId);\n }\n /**\n * getLastTransaction - get a last SLP token transaction of a particular address\n *\n * @param {boolean} [confirmedOnly=false] When confirmedOnly is true, results will be limited to only transactions included in a block.\n *\n * @returns Promise to the transaction hex or error\n */\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n const [lastTx] = history.slice(-1);\n return this.wallet.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n /**\n * getBalance - get a token balance for a particular address\n *\n * a high-level function, see also /wallet/slp/balance REST endpoint\n *\n * @param tokenId The id of the slp token\n *\n * @returns Promise to an SlpTokenBalance\n */\n async getBalance(tokenId) {\n if (!tokenId) {\n throw new Error(`Invalid tokenId ${tokenId}`);\n }\n return this.provider.SlpTokenBalance(this.slpaddr, tokenId);\n }\n /**\n * getAllBalances - get all token balances for a particular address\n *\n * a high-level function, see also /wallet/slp/all_balances REST endpoint\n *\n * @returns Promise to an array of SlpTokenBalance\n */\n async getAllBalances() {\n return this.provider.SlpAllTokenBalances(this.slpaddr);\n }\n /**\n * watchBalance - set up a callback to be called upon wallet's slp balance change\n *\n * can be cancelled by calling the function returned from this one\n *\n * @param callback The callback function to be called each time the balance changes\n * @param tokenId Specific token id to watch\n *\n * @returns A function to cancel the watching\n */\n watchBalance(callback, tokenId) {\n return this.provider.SlpWatchBalance(callback, this.slpaddr, tokenId);\n }\n /**\n * waitForBalance - wait for address balance to be greater than or equal to the target value\n *\n * This call halts the program execution\n *\n * @param value Target balance value\n * @param tokenId Specific token id to watch\n *\n * @returns Actual token balance after reaching or surpassing the target value\n */\n async waitForBalance(value, tokenId) {\n return this.provider.SlpWaitForBalance(value, this.slpaddr, tokenId);\n }\n /**\n * watchBalance - set up a callback to be called upon wallet's slp transactions occurring\n *\n * can be cancelled by calling the function returned from this one\n *\n * @param callback The callback function to be called each time the balance changes\n * @param tokenId Specific token id to watch, optional\n *\n * @returns A function to cancel the watching\n */\n watchTransactions(callback, tokenId) {\n return this.provider.SlpWatchTransactions(callback, this.slpaddr, tokenId);\n }\n /**\n * waitForBalance - wait for the next SLP transaction to occur\n *\n * This call halts the program execution\n *\n * @param tokenId Specific token id to watch, optional\n *\n * @returns Transaction object\n */\n async waitForTransaction(tokenId) {\n return this.provider.SlpWaitForTransaction(this.slpaddr, tokenId);\n }\n /**\n * genesis - create a new Type1 SLP token\n *\n * @param options Token creation options @see SlpGenesisOptions\n *\n * @returns Token Id and new token balance\n */\n async genesis(options) {\n let result = await this._processGenesis(options);\n return {\n tokenId: result,\n balance: await this.getBalance(result),\n };\n }\n /**\n * nftParentGenesis - create a new NFT Parent token\n *\n * @param options Token creation options @see SlpGenesisOptions\n *\n * @returns Token Id and new token balance\n */\n async nftParentGenesis(options) {\n options.type = _slp_interface_js__WEBPACK_IMPORTED_MODULE_8__.SlpTokenType.NftParent;\n let result = await this._processGenesis(options);\n return {\n tokenId: result,\n balance: await this.getBalance(result),\n };\n }\n /**\n * nftParentGenesis - create a new NFT Child token\n *\n * @param parentTokenId Parent token id, at least one is required and will be spent in the child genesis process\n * @param options Token creation options @see SlpGenesisOptions\n *\n * @returns Token Id and new token balance\n */\n async nftChildGenesis(options) {\n if (!options.parentTokenId) {\n throw new Error(`The 'parentTokenId' was not set or invalid ${options.parentTokenId}`);\n }\n let parentUtxos = await this.provider.SlpSpendableUtxos(this.slpaddr, options.parentTokenId);\n parentUtxos = parentUtxos.filter((val) => this.spentParentUtxos.indexOf(`${val.txid}:${val.vout}`) === -1);\n parentUtxos = parentUtxos.sort((a, b) => a.value.comparedTo(b.value));\n if (!parentUtxos.length) {\n throw new Error(`You do not own any NFT parent tokens with id ${options.parentTokenId}`);\n }\n if (parentUtxos[0].type !== _slp_interface_js__WEBPACK_IMPORTED_MODULE_8__.SlpTokenType.NftParent) {\n throw new Error(`The 'parentTokenId' is not of type ${_slp_interface_js__WEBPACK_IMPORTED_MODULE_8__.SlpTokenType.NftParent}`);\n }\n // we are about to spend exactly 1 NFT parent\n // if we do not have it, we have to make one by splitting\n if (parentUtxos[0].value.isGreaterThan(new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(1))) {\n await this.send([\n {\n slpaddr: this.slpaddr,\n tokenId: options.parentTokenId,\n value: new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(1),\n },\n ]);\n return await this.nftChildGenesis(options);\n }\n options.type = _slp_interface_js__WEBPACK_IMPORTED_MODULE_8__.SlpTokenType.NftChild;\n options.endBaton = true;\n options.initialAmount = 1;\n options.decimals = 0;\n let result = await this._processGenesis(options, [parentUtxos[0]]);\n const tx = (await this.wallet.provider.getRawTransactionObject(result));\n tx.vin.forEach((val) => this.spentParentUtxos.push(`${val.txid}:${val.vout}`));\n return {\n tokenId: result,\n balance: await this.getBalance(result),\n };\n }\n /**\n * _processGenesis - prepare the genesis transaction with given parameters\n *\n * a private utility wrapper to pre-process transactions\n *\n * @param options genesis options to controll the process\n *\n * @returns the created tokenId (which is genesis transaction id) and token balance\n */\n async _processGenesis(options, ensureInputs = []) {\n options = this.substituteOptionals(options);\n let slpOutputsResult = await (0,_slp_SlpLibAuth_js__WEBPACK_IMPORTED_MODULE_9__.SlpGetGenesisOutputs)(options);\n let fundingBchUtxos = await this.wallet\n .slpAware(true)\n .getAddressUtxos(this.wallet.cashaddr);\n fundingBchUtxos = [...ensureInputs, ...fundingBchUtxos];\n return this.processSlpTransaction(fundingBchUtxos, slpOutputsResult);\n }\n /**\n * sendMax - send the maximum spendable amount for a token to an slpaddr.\n *\n * a high-level function, see also /wallet/slp/send_max REST endpoint\n *\n * @param slpaddr destination SLP address\n * @param tokenId the id of the token to be spent\n *\n * @returns transaction id and token balance\n */\n async sendMax(slpaddr, tokenId) {\n const balance = await this.getBalance(tokenId);\n const requests = [balance].map((val) => ({\n slpaddr: slpaddr,\n value: val.value,\n ticker: val.ticker,\n tokenId: val.tokenId,\n }));\n return this.send(requests);\n }\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://simpleledger.info/#tx/\",\n testnet: \"https://testnet.simpleledger.info/#tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.wallet.network] + txId;\n }\n /**\n * send - attempt to process a list of slp send requests.\n *\n * a high-level function, see also /wallet/slp/send REST endpoint\n *\n * @param [requests] list of send requests\n *\n * @returns transaction id and token balance\n */\n async send(requests) {\n let [actualTokenId, result] = await this._processSendRequests(requests);\n return {\n txId: result,\n balance: await this.getBalance(actualTokenId),\n explorerUrl: this.explorerUrl(result),\n };\n }\n /**\n * _processSendRequests - given a list of sendRequests, estimate fees, build the transaction and submit it.\n *\n * A private utility wrapper to pre-process transactions\n *\n * Unstable - behavior may change without notice.\n *\n * @param {SlpSendRequest[]} sendRequests\n */\n async _processSendRequests(sendRequests) {\n if (!sendRequests.length) {\n throw Error(\"Empty send requests\");\n }\n if (sendRequests.length > 19) {\n throw Error(\"Too many send requests in one transaction\");\n }\n const uniqueTokenIds = new Set(sendRequests.map((val) => val.tokenId));\n if (uniqueTokenIds.size > 1) {\n throw Error(\"You have two different token types with the same ticker. Pass tokenId parameter\");\n }\n const tokenId = sendRequests[0].tokenId;\n if (!tokenId.match(/^[0-9a-fA-F]{64}$/)) {\n throw new Error(\"Invalid tokenId, must be 64 character long hexadecimal string\");\n }\n const slpUtxos = await this.provider.SlpSpendableUtxos(this.slpaddr, tokenId);\n let slpOutputsResult = await (0,_slp_SlpLibAuth_js__WEBPACK_IMPORTED_MODULE_9__.SlpGetSendOutputs)(this.slpaddr, slpUtxos, sendRequests);\n let fundingBchUtxos = await this.wallet\n .slpAware(true)\n .getAddressUtxos(this.wallet.cashaddr);\n let slpToBchUtxos = slpOutputsResult.FundingSlpUtxos.map((val) => val);\n fundingBchUtxos = [...slpToBchUtxos, ...fundingBchUtxos];\n const actualTokenId = slpUtxos[0].tokenId;\n return [\n actualTokenId,\n await this.processSlpTransaction(fundingBchUtxos, slpOutputsResult, actualTokenId),\n ];\n }\n /**\n * mint - create new tokens to increase the circulation supply.\n *\n * a high-level function, see also /wallet/slp/mint endpoint\n *\n * @param value amount to mint\n * @param tokenId the tokenId of the slp being minted\n * @param endBaton boolean indicating whether the token should continue to be \"mintable\"\n *\n * @returns transaction id and token balance\n */\n async mint(options) {\n let [actualTokenId, result] = await this._processMint(options);\n return {\n txId: result,\n balance: await this.getBalance(actualTokenId),\n };\n }\n /**\n * _processMint - given mint parameters, prepare the transaction\n *\n * a private utility wrapper to pre-process transactions\n *\n * @param value amount to mint\n * @param tokenId the tokenId of the slp being minted\n * @param endBaton boolean indicating whether the token should continue to be \"mintable\"\n *\n * @returns the tokenId and minting transaction id\n */\n async _processMint(options) {\n options = this.substituteOptionals(options);\n options.value = new (bignumber_js__WEBPACK_IMPORTED_MODULE_0___default())(options.value);\n if (options.value.isLessThanOrEqualTo(0) &&\n options.batonReceiverSlpAddr === this.slpaddr) {\n throw Error(\"Mint amount should be greater than zero\");\n }\n const slpBatonUtxos = await this.getBatonUtxos(options.tokenId);\n if (!slpBatonUtxos.length) {\n throw Error(`You do not possess the minting baton for ${options.tokenId}`);\n }\n let slpOutputsResult = await (0,_slp_SlpLibAuth_js__WEBPACK_IMPORTED_MODULE_9__.SlpGetMintOutputs)(options, slpBatonUtxos);\n let bchUtxos = await this.wallet\n .slpAware(true)\n .getAddressUtxos(this.wallet.cashaddr);\n let fundingBchUtxos = bchUtxos;\n let slpToBchUtxos = slpOutputsResult.FundingSlpUtxos.map((val) => val);\n fundingBchUtxos = [...slpToBchUtxos, ...fundingBchUtxos];\n return [\n options.tokenId,\n await this.processSlpTransaction(fundingBchUtxos, slpOutputsResult, options.tokenId),\n ];\n }\n /**\n * processSlpTransaction - process the prepared SLP transaction and submit it to the network\n *\n * @param fundingBchUtxos ensure these BCH utxos to be spent in the process\n * @param slpOutputsResult prepared SLP outputs to be added to transaction\n *\n * @returns the tokenId and minting transaction id\n */\n async processSlpTransaction(fundingBchUtxos, slpOutputsResult, tokenId) {\n if (!this.wallet.privateKey) {\n throw new Error(`Wallet ${this.wallet.name} is missing either a network or private key`);\n }\n if (!fundingBchUtxos.length) {\n throw new Error(\"No bch available to fund this transaction\");\n }\n const bestHeight = await this.wallet.provider.getBlockHeight();\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.wallet.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_10__.getFeeAmount)({\n utxos: fundingBchUtxos,\n sendRequests: slpOutputsResult.BchSendRequests,\n privateKey: this.wallet.privateKey,\n sourceAddress: this.wallet.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: slpOutputsResult.SlpOutputs,\n feePaidBy: _enum_js__WEBPACK_IMPORTED_MODULE_11__.FeePaidByEnum.change,\n });\n const bchSpendAmount = slpOutputsResult.BchSendRequests.map((val) => val.value).reduce((a, b) => a + b, 0);\n let fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_10__.getSuitableUtxos)(fundingBchUtxos, BigInt(bchSpendAmount) + BigInt(feeEstimate), bestHeight, _enum_js__WEBPACK_IMPORTED_MODULE_11__.FeePaidByEnum.change, slpOutputsResult.BchSendRequests);\n if (fundingUtxos.length === 0) {\n throw Error(\"The available inputs couldn't satisfy the request with fees\");\n }\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_10__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: slpOutputsResult.BchSendRequests,\n privateKey: this.wallet.privateKey,\n sourceAddress: this.wallet.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: slpOutputsResult.SlpOutputs,\n feePaidBy: _enum_js__WEBPACK_IMPORTED_MODULE_11__.FeePaidByEnum.change,\n });\n const { encodedTransaction } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_10__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: slpOutputsResult.BchSendRequests,\n signingKey: this.wallet.privateKey,\n sourceAddress: this.wallet.cashaddr,\n fee,\n discardChange: false,\n slpOutputs: slpOutputsResult.SlpOutputs,\n });\n return this._submitTransaction(encodedTransaction, tokenId);\n }\n /**\n * _submitTransaction - transform binary transaction to hex and submit it to the network provider\n *\n * a private utility wrapper submit raw transactions\n *\n * @param transaction raw transaction\n *\n * @returns the transaction id of the broadcasted transaction\n */\n async _submitTransaction(transaction, tokenId) {\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.binToHex)(transaction);\n const slpPromise = new Promise(async (resolve) => {\n const txHash = await _Util_js__WEBPACK_IMPORTED_MODULE_13__.Util.getTransactionHash(rawTransaction);\n const cancelWatchFn = this.provider.SlpWatchTransactions(async (tx) => {\n if (tx.tx_hash === txHash) {\n cancelWatchFn();\n resolve(txHash);\n }\n }, undefined, tokenId || txHash);\n });\n const bchPromise = this.wallet.provider.sendRawTransaction(rawTransaction, true);\n const [_, txHash] = await Promise.all([slpPromise, bchPromise]);\n // allow for indexer processing, delay value is a bit arbitrary\n await (0,_util_delay_js__WEBPACK_IMPORTED_MODULE_14__.delay)(100);\n return txHash;\n }\n /**\n * substituteOptionals - substitute optional fields with default values\n *\n * will ensure that baton and token receiver are intialized as SLP address of this wallet if absent\n * will ensure that baton will not be ended if endBaton is undefined\n * a private utility wrapper substitute optionals\n *\n * @param options genesis or mint options to substitute values int\n *\n * @returns options with relevant values substituted/initialized\n */\n substituteOptionals(options) {\n if (!options.batonReceiverSlpAddr) {\n options.batonReceiverSlpAddr = this.slpaddr;\n }\n if (!options.tokenReceiverSlpAddr) {\n options.tokenReceiverSlpAddr = this.slpaddr;\n }\n if (options.endBaton === undefined) {\n options.endBaton = false;\n }\n return options;\n }\n //#region Convenience methods to initialize Slp aware BCH wallet.\n /**\n * fromId - create an SLP aware wallet from encoded walletId string\n *\n * @param walletId walletId options to steer the creation process\n *\n * @returns wallet instantiated accordingly to the walletId rules\n */\n static async fromId(walletId) {\n const wallet = await this.walletType.fromId(walletId);\n wallet._slpAware = true;\n return wallet;\n }\n /**\n * named - create an SLP aware named wallet\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n * @param force force recreate wallet in the database if a record already exist\n *\n * @returns instantiated wallet\n */\n static async named(name, dbName, force) {\n const wallet = await this.walletType.named(name, dbName, force);\n wallet.derivationPath = \"m/44'/245'/0'/0/0\";\n wallet._slpAware = true;\n return wallet;\n }\n /**\n * fromSeed - create an SLP aware wallet using the seed phrase and derivation path\n *\n * unless specified the derivation path m/44'/245'/0'/0/0 will be userd\n * this derivation path is standard for Electron Cash SLP and other SLP enabled wallets\n *\n * @param seed BIP39 12 word seed phrase\n * @param derivationPath BIP44 HD wallet derivation path to get a single the private key from hierarchy\n *\n * @returns instantiated wallet\n */\n static async fromSeed(seed, derivationPath = \"m/44'/245'/0'/0/0\") {\n const wallet = await this.walletType.fromSeed(seed, derivationPath);\n wallet._slpAware = true;\n return wallet;\n }\n /**\n * newRandom - create an SLP aware random wallet\n *\n * if `name` parameter is specified, the wallet will also be persisted to DB\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async newRandom(name = \"\", dbName) {\n const wallet = await this.walletType.newRandom(name, dbName);\n wallet.derivationPath = \"m/44'/245'/0'/0/0\";\n wallet._slpAware = true;\n return wallet;\n }\n /**\n * fromWIF - create an SLP aware wallet using the private key supplied in `Wallet Import Format`\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromWIF(wif) {\n const wallet = await this.walletType.fromWIF(wif);\n wallet.derivationPath = \"m/44'/245'/0'/0/0\";\n wallet._slpAware = true;\n return wallet;\n }\n /**\n * watchOnly - create an SLP aware watch-only wallet\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress or slpaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async watchOnly(address) {\n const wallet = await this.walletType.watchOnly((0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_2__.toCashAddress)(address));\n wallet.derivationPath = \"m/44'/245'/0'/0/0\";\n wallet._slpAware = true;\n return wallet;\n }\n /**\n * fromCashaddr - create an SLP aware watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromCashaddr(address) {\n const wallet = await this.walletType.fromCashaddr(address);\n wallet.derivationPath = \"m/44'/245'/0'/0/0\";\n wallet._slpAware = true;\n return wallet;\n }\n /**\n * fromSlpaddr - create an SLP aware watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address slpaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromSlpaddr(address) {\n const wallet = await this.walletType.fromSlpaddr(address);\n wallet.derivationPath = \"m/44'/245'/0'/0/0\";\n wallet._slpAware = true;\n return wallet;\n }\n}\nSlp.defaultProvider = \"slpdb\";\n//#region Specific wallet classes\n/**\n * Class to manage an slp enabled testnet wallet.\n */\nclass TestNetSlp extends Slp {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWallet;\n }\n}\n/**\n * Class to manage an slp enabled regtest wallet.\n */\nclass RegTestSlp extends Slp {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWallet;\n }\n}\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifSlp extends Slp {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__.WifWallet;\n }\n}\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifSlp extends Slp {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWifWallet;\n }\n}\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifSlp extends Slp {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWifWallet;\n }\n}\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchSlp extends Slp {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__.WatchWallet;\n }\n}\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchSlp extends Slp {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWatchWallet;\n }\n}\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchSlp extends Slp {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWatchWallet;\n }\n}\n//#endregion\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Slp.ts?");
1648
-
1649
- /***/ }),
1650
-
1651
1421
  /***/ "./src/wallet/Util.ts":
1652
1422
  /*!****************************!*\
1653
1423
  !*** ./src/wallet/Util.ts ***!
1654
1424
  \****************************/
1655
1425
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1656
1426
 
1657
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestUtil\": () => (/* binding */ RegTestUtil),\n/* harmony export */ \"RegTestWatchUtil\": () => (/* binding */ RegTestWatchUtil),\n/* harmony export */ \"RegTestWifUtil\": () => (/* binding */ RegTestWifUtil),\n/* harmony export */ \"TestNetUtil\": () => (/* binding */ TestNetUtil),\n/* harmony export */ \"TestNetWatchUtil\": () => (/* binding */ TestNetWatchUtil),\n/* harmony export */ \"TestNetWifUtil\": () => (/* binding */ TestNetWifUtil),\n/* harmony export */ \"Util\": () => (/* binding */ Util),\n/* harmony export */ \"WatchUtil\": () => (/* binding */ WatchUtil),\n/* harmony export */ \"WifUtil\": () => (/* binding */ WifUtil)\n/* harmony export */ });\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_1__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__]);\n([_wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_1__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n/**\n * Class with various wallet utilities.\n */\nclass Util {\n /**\n * Initializes a wallet Util class.\n *\n * @param wallet A wallet object\n */\n constructor(wallet) {\n this.wallet = wallet;\n }\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.Wallet;\n }\n async getTransactionHash(rawTransactionHex) {\n return (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_1__.getTransactionHash)(rawTransactionHex);\n }\n static async getTransactionHash(rawTransactionHex) {\n return (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_1__.getTransactionHash)(rawTransactionHex);\n }\n async decodeTransaction(transactionHashOrHex, loadInputValues = false) {\n let transactionHex;\n let transactionBin;\n let txHash;\n // raw transaction\n if (transactionHashOrHex.length > 64) {\n txHash = await this.getTransactionHash(transactionHashOrHex);\n transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.hexToBin)(transactionHashOrHex);\n transactionHex = transactionHashOrHex;\n }\n else {\n // tx hash, look up the raw transaction\n txHash = transactionHashOrHex;\n transactionHex = await this.wallet.provider.getRawTransaction(txHash);\n transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.hexToBin)(transactionHex);\n }\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.decodeTransaction)(transactionBin);\n if (typeof result === \"string\") {\n throw Error(result);\n }\n const transaction = this.mapToElectrumRawTransaction(result, txHash, transactionHex);\n if (loadInputValues) {\n // get unique transaction hashes\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.decodeTransaction(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n transaction.vin.forEach((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n input.address = output.scriptPubKey.addresses[0];\n input.value = output.value;\n input.tokenData = output.tokenData;\n });\n }\n return transaction;\n }\n mapToElectrumRawTransaction(transaction, txHash, txHex) {\n let result = {};\n result.vin = transaction.inputs.map((input) => {\n return {\n scriptSig: {\n hex: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToHex)(input.unlockingBytecode),\n },\n sequence: input.sequenceNumber,\n txid: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToHex)(input.outpointTransactionHash),\n vout: input.outpointIndex,\n };\n });\n result.vout = transaction.outputs.map((output, index) => {\n return {\n n: index,\n scriptPubKey: {\n addresses: [\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.lockingBytecodeToCashAddress)(output.lockingBytecode, this.wallet.networkPrefix).toString(),\n ],\n hex: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToHex)(output.lockingBytecode),\n },\n value: Number(output.valueSatoshis) / _chain_js__WEBPACK_IMPORTED_MODULE_5__.bchParam.subUnits,\n };\n });\n result.locktime = transaction.locktime;\n result.version = transaction.version;\n result.hash = txHash;\n result.hex = txHex;\n result.txid = txHash;\n result.size = txHex.length / 2;\n return result;\n }\n static async decodeTransaction(transactionHashOrHex, loadInputValues = false) {\n return new this.walletType().util.decodeTransaction(transactionHashOrHex, loadInputValues);\n }\n}\n//#region Specific wallet classes\n/**\n * Class to manage an slp enabled testnet wallet.\n */\nclass TestNetUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWallet;\n }\n}\n/**\n * Class to manage an slp enabled regtest wallet.\n */\nclass RegTestUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWallet;\n }\n}\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.WifWallet;\n }\n}\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWifWallet;\n }\n}\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWifWallet;\n }\n}\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.WatchWallet;\n }\n}\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWatchWallet;\n }\n}\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWatchWallet;\n }\n}\n//#endregion\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Util.ts?");
1427
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestUtil\": () => (/* binding */ RegTestUtil),\n/* harmony export */ \"RegTestWatchUtil\": () => (/* binding */ RegTestWatchUtil),\n/* harmony export */ \"RegTestWifUtil\": () => (/* binding */ RegTestWifUtil),\n/* harmony export */ \"TestNetUtil\": () => (/* binding */ TestNetUtil),\n/* harmony export */ \"TestNetWatchUtil\": () => (/* binding */ TestNetWatchUtil),\n/* harmony export */ \"TestNetWifUtil\": () => (/* binding */ TestNetWifUtil),\n/* harmony export */ \"Util\": () => (/* binding */ Util),\n/* harmony export */ \"WatchUtil\": () => (/* binding */ WatchUtil),\n/* harmony export */ \"WifUtil\": () => (/* binding */ WifUtil)\n/* harmony export */ });\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_1__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__]);\n([_wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_1__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n/**\n * Class with various wallet utilities.\n */\nclass Util {\n /**\n * Initializes a wallet Util class.\n *\n * @param wallet A wallet object\n */\n constructor(wallet) {\n this.wallet = wallet;\n }\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.Wallet;\n }\n async getTransactionHash(rawTransactionHex) {\n return (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_1__.getTransactionHash)(rawTransactionHex);\n }\n static async getTransactionHash(rawTransactionHex) {\n return (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_1__.getTransactionHash)(rawTransactionHex);\n }\n async decodeTransaction(transactionHashOrHex, loadInputValues = false) {\n let transactionHex;\n let transactionBin;\n let txHash;\n // raw transaction\n if (transactionHashOrHex.length > 64) {\n txHash = await this.getTransactionHash(transactionHashOrHex);\n transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.hexToBin)(transactionHashOrHex);\n transactionHex = transactionHashOrHex;\n }\n else {\n // tx hash, look up the raw transaction\n txHash = transactionHashOrHex;\n transactionHex = await this.wallet.provider.getRawTransaction(txHash);\n transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.hexToBin)(transactionHex);\n }\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.decodeTransaction)(transactionBin);\n if (typeof result === \"string\") {\n throw Error(result);\n }\n const transaction = this.mapToElectrumRawTransaction(result, txHash, transactionHex);\n if (loadInputValues) {\n // get unique transaction hashes\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.decodeTransaction(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n transaction.vin.forEach((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n input.address = output.scriptPubKey.addresses[0];\n input.value = output.value;\n input.tokenData = output.tokenData;\n });\n }\n return transaction;\n }\n mapToElectrumRawTransaction(transaction, txHash, txHex) {\n let result = {};\n result.vin = transaction.inputs.map((input) => {\n return {\n scriptSig: {\n hex: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToHex)(input.unlockingBytecode),\n },\n sequence: input.sequenceNumber,\n txid: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToHex)(input.outpointTransactionHash),\n vout: input.outpointIndex,\n };\n });\n result.vout = transaction.outputs.map((output, index) => {\n return {\n n: index,\n scriptPubKey: {\n addresses: [\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.lockingBytecodeToCashAddress)(output.lockingBytecode, this.wallet.networkPrefix).toString(),\n ],\n hex: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToHex)(output.lockingBytecode),\n },\n value: Number(output.valueSatoshis) / _chain_js__WEBPACK_IMPORTED_MODULE_5__.bchParam.subUnits,\n };\n });\n result.locktime = transaction.locktime;\n result.version = transaction.version;\n result.hash = txHash;\n result.hex = txHex;\n result.txid = txHash;\n result.size = txHex.length / 2;\n return result;\n }\n static async decodeTransaction(transactionHashOrHex, loadInputValues = false) {\n return new this.walletType().util.decodeTransaction(transactionHashOrHex, loadInputValues);\n }\n}\n//#region Specific wallet classes\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWallet;\n }\n}\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWallet;\n }\n}\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.WifWallet;\n }\n}\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWifWallet;\n }\n}\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWifWallet;\n }\n}\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.WatchWallet;\n }\n}\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWatchWallet;\n }\n}\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchUtil extends Util {\n static get walletType() {\n return _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWatchWallet;\n }\n}\n//#endregion\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Util.ts?");
1658
1428
 
1659
1429
  /***/ }),
1660
1430
 
@@ -1664,7 +1434,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1664
1434
  \***************************/
1665
1435
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1666
1436
 
1667
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestWallet\": () => (/* binding */ RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var bip39__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bip39 */ \"../../node_modules/bip39/src/index.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../util/asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _Slp_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Slp.js */ \"./src/wallet/Slp.ts\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/bchaddr.js */ \"../../node_modules/bchaddrjs-slp/src/bchaddr.js\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_14__);\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../network/index.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _Bcmr_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Slp_js__WEBPACK_IMPORTED_MODULE_7__, _Util_js__WEBPACK_IMPORTED_MODULE_8__, _network_index_js__WEBPACK_IMPORTED_MODULE_10__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_11__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_13__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_18__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__, _model_js__WEBPACK_IMPORTED_MODULE_21__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_22__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_23__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_24__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_28__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_29__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_30__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_31__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_32__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_33__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_34__, _message_index_js__WEBPACK_IMPORTED_MODULE_36__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Slp_js__WEBPACK_IMPORTED_MODULE_7__, _Util_js__WEBPACK_IMPORTED_MODULE_8__, _network_index_js__WEBPACK_IMPORTED_MODULE_10__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_11__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_13__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_18__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__, _model_js__WEBPACK_IMPORTED_MODULE_21__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_22__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_23__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_24__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_28__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_29__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_30__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_31__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_32__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_33__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_34__, _message_index_js__WEBPACK_IMPORTED_MODULE_36__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n// Stable\n\n// Unstable?\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//#endregion Imports\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Base_js__WEBPACK_IMPORTED_MODULE_3__.BaseWallet {\n //#endregion\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n super(name, network, walletType);\n this.derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_6__.Config.DefaultParentDerivationPath + \"/0/0\";\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_6__.Config.DefaultParentDerivationPath;\n this._slpAware = false; // a flag which activates utxo checking against an external slp indexer\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.fromId = async (walletId) => {\n let [walletType, networkGiven, arg1] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n if (walletType === \"wif\") {\n return this.fromWIF(arg1);\n }\n return super.fromId(walletId);\n };\n this.networkPrefix = _enum_js__WEBPACK_IMPORTED_MODULE_4__.prefixFromNetworkMap[this.network];\n }\n //#region Accessors\n // interface to slp functions. see Slp.ts\n get slp() {\n if (!this._slp) {\n this._slp = new _Slp_js__WEBPACK_IMPORTED_MODULE_7__.Slp(this);\n this._slpAware = true;\n }\n return this._slp;\n }\n // interface to slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_7__.Slp;\n }\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_8__.Util(this);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_8__.Util;\n }\n slpAware(value = true) {\n this._slpAware = value;\n return this;\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_9__.Network.MAINNET) {\n return (0,_network_index_js__WEBPACK_IMPORTED_MODULE_10__.getNetworkProvider)(network);\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n return this.tokenaddr;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * @returns The qrcode for the token aware address\n */\n getTokenDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_11__.qrAddress)(this.getTokenDepositAddress());\n }\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n // Return wallet info\n getInfo() {\n return {\n cashaddr: this.cashaddr,\n tokenaddr: this.tokenaddr,\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic ? this.getSeed().seed : undefined,\n derivationPath: this.mnemonic ? this.getSeed().derivationPath : undefined,\n parentDerivationPath: this.mnemonic\n ? this.getSeed().parentDerivationPath\n : undefined,\n parentXPubKey: this.parentXPubKey ? this.parentXPubKey : undefined,\n publicKey: this.publicKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.binToHex)(this.privateKey) : undefined,\n privateKeyWif: this.privateKeyWif,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n // returns the public key hash for an address\n getPublicKey(hex = false) {\n if (this.publicKey) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.binToHex)(this.publicKey) : this.publicKey;\n }\n else {\n throw Error(\"The public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyCompressed(hex = false) {\n if (this.publicKeyCompressed) {\n return hex\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.binToHex)(this.publicKeyCompressed)\n : this.publicKeyCompressed;\n }\n else {\n throw Error(\"The compressed public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n if (this.publicKeyHash) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\n }\n else {\n throw Error(\"The public key hash for this wallet is not known. If this wallet was created from the constructor directly, calling the deriveInfo() function may help. \");\n }\n }\n /**\n * fromWIF - create a wallet using the private key supplied in `Wallet Import Format`\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromWIF(wif) {\n return new this().fromWIF(wif);\n }\n /**\n * fromCashaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromCashaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_13__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromTokenaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromTokenaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_13__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromSlpaddr - create an SLP aware watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address slpaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromSlpaddr(address) {\n return this.fromCashaddr((0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_14__.toCashAddress)(address));\n }\n //#endregion Constructors and Statics\n //#region Protected implementations\n async generate() {\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return await this._generateWif();\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n return this;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Hd) {\n throw Error(\"Not implemented\");\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n return await this._generateMnemonic();\n }\n else {\n console.log(this.walletType);\n throw Error(`Could not determine walletType: ${this.walletType}`);\n }\n }\n async _generateWif() {\n if (!this.privateKey) {\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_16__.generateRandomBytes)(32));\n }\n return this.deriveInfo();\n }\n async _generateMnemonic() {\n this.mnemonic = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.generateMnemonic)();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_17__.checkForEmptySeed)(seed);\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_18__.getXPubKey)(seed, this.parentDerivationPath, network);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n return await this.deriveInfo();\n }\n async getXPubKeys(paths) {\n if (this.mnemonic) {\n if (paths) {\n let xPubKeys = await this.deriveHdPaths(paths);\n return [xPubKeys];\n }\n else {\n return await this.deriveHdPaths(_constant_js__WEBPACK_IMPORTED_MODULE_20__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n this.mnemonic = mnemonic.trim().toLowerCase();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_17__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n if (derivationPath) {\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n let path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_18__.getXPubKey)(seed, this.parentDerivationPath, network);\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n await this.deriveInfo();\n return this;\n }\n // Get common xpub paths from zerothChild privateKey\n async deriveHdPaths(hdPaths) {\n if (!this.mnemonic)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_17__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let result = [];\n for (const path of hdPaths) {\n if (path === \"m\") {\n throw Error(\"Storing or sharing of parent public key may lead to loss of funds. Storing or sharing *root* parent public keys is strongly discouraged, although all parent keys have risk. See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#implications\");\n }\n let childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n let node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n let xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n });\n let key = new _model_js__WEBPACK_IMPORTED_MODULE_21__.XPubKey({\n path: path,\n xPubKey: xPubKey,\n });\n result.push(await key.ready());\n }\n return await Promise.all(result).then((result) => {\n return result;\n });\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n let addressComponents = address.split(\":\");\n let addressPrefix, addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_13__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[addressPrefix] != this.network) {\n throw Error(`a ${addressPrefix} address cannot be watched from a ${this.network} Wallet`);\n }\n }\n }\n this.cashaddr = `${addressPrefix}:${addressBase}`;\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_13__.derivePublicKeyHash)(this.cashaddr);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_22__.deriveTokenaddr)(this.publicKeyHash, this.networkPrefix);\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_23__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_24__.decodePrivateKeyWif)(secret);\n if (typeof wifResult === \"string\") {\n throw Error(wifResult);\n }\n let resultData = wifResult;\n this.privateKey = resultData.privateKey;\n this.privateKeyWif = secret;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n await this.deriveInfo();\n return this;\n }\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.newRandom(name, dbName);\n }\n async named(name, dbName, forceNew = false) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.named(name, dbName, forceNew);\n }\n async replaceNamed(name, walletId, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.replaceNamed(name, walletId, dbName);\n }\n async namedExists(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.namedExists(name, dbName);\n }\n //#endregion Protected Implementations\n //#region Serialization\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n const result = super.toString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toString unsupported wallet type\");\n }\n //\n toDbString() {\n const result = super.toDbString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n //\n async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpAware) {\n const [bchUtxos, slpOutpoints] = await Promise.all([\n this.provider.getUtxos(address),\n this.slp.getSlpOutpoints(),\n ]);\n return bchUtxos.filter((bchutxo) => slpOutpoints.findIndex((slpOutpoint) => `${bchutxo.txid}:${bchutxo.vout}` === slpOutpoint) === -1);\n }\n else if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_20__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n if (!this.cashaddr) {\n throw Error(\"Attempted to get utxos without an address\");\n }\n return await this.getAddressUtxos(this.cashaddr);\n }\n // gets wallet balance in sats, bch and usd\n async getBalance(rawUnit, usdPriceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_25__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_26__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, usdPriceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_26__.balanceResponseFromSatoshi)(await this.getBalanceFromProvider(), usdPriceCache);\n }\n }\n // Gets balance by summing value in all utxos in stats\n async getBalanceFromUtxos() {\n const utxos = (await this.getAddressUtxos(this.cashaddr)).filter((val) => val.token === undefined);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_27__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider!.getBalance(this.cashaddr!);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n // watching for any transaction hash of this wallet\n watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = (await this.getBalance());\n callback(balance);\n });\n }\n // sets up a callback to be called upon wallet's BCH or USD balance change\n // if BCH balance does not change, the callback will be triggered every\n // @param `usdPriceRefreshInterval` milliseconds by polling for new BCH USD price\n // Since we want to be most sensitive to usd value change, we do not use the cached exchange rates\n // can be cancelled by calling the function returned from this one\n watchBalanceUsd(callback, usdPriceRefreshInterval = 30000) {\n let usdPrice = -1;\n const _callback = async () => {\n const balance = (await this.getBalance(undefined, false));\n if (usdPrice !== balance.usd) {\n usdPrice = balance.usd;\n callback(balance);\n }\n };\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), _callback);\n const interval = setInterval(_callback, usdPriceRefreshInterval);\n return async () => {\n await watchCancel();\n clearInterval(interval);\n };\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value, rawUnit = _enum_js__WEBPACK_IMPORTED_MODULE_4__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_28__.amountInSatoshi)(value, rawUnit);\n if (balance.sat >= satoshiBalance) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n async getTokenInfo(tokenId) {\n return _Bcmr_js__WEBPACK_IMPORTED_MODULE_29__.BCMR.getTokenInfo(tokenId);\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!this.privateKey && params.options?.buildUnsigned !== true) {\n throw Error(\"Couldn't get network or private key for wallet.\");\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (params.options && params.options.slpAware) {\n this._slpAware = true;\n }\n if (params.options && params.options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (params.options && params.options.feePaidBy) {\n feePaidBy = params.options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n // get inputs\n let utxos;\n if (params.options && params.options.utxoIds) {\n utxos = params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_21__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = (await this.getAddressUtxos(this.cashaddr)).filter((utxo) => !utxo.token);\n }\n // Get current height to assure recently mined coins are not spent.\n const bestHeight = await this.provider.getBlockHeight();\n // simulate outputs using the sender's address\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_21__.SendRequest({\n cashaddr: this.cashaddr,\n value: 100,\n unit: \"sat\",\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_30__.getSuitableUtxos)(utxos, undefined, bestHeight, feePaidBy, sendRequests);\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_30__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_27__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0) {\n result = 0;\n }\n return { value: result, utxos: fundingUtxos };\n }\n async getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n const { value: result } = await this._getMaxAmountToSend(params);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_26__.balanceResponseFromSatoshi)(result);\n }\n /**\n * send Send some amount to an address\n * this function processes the send requests, encodes the transaction, sends it to the network\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n *\n * This is a first class function with REST analog, maintainers should strive to keep backward-compatibility\n *\n */\n async send(requests, options) {\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_21__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_21__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_21__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options) {\n let sendRequests = (0,_util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_31__.asSendRequestObject)(requests);\n if (!this.privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Wallet ${this.name} is missing either a network or private key`);\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (options && options.slpAware) {\n this._slpAware = true;\n }\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options && options.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options && options.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.cashaddr;\n }\n let checkTokenQuantities = true;\n if (options && options.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_21__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n // filter out token utxos if there are no token requests\n if (checkTokenQuantities &&\n !sendRequests.some((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_21__.TokenSendRequest)) {\n utxos = utxos.filter((val) => !val.token);\n }\n const addTokenChangeOutputs = (inputs, outputs) => {\n // allow for implicit token burn if the total amount sent is less than user had\n // allow for token genesis, creating more tokens than we had before (0)\n if (!checkTokenQuantities) {\n return;\n }\n const allTokenInputs = inputs.filter((val) => val.token);\n const allTokenOutputs = outputs.filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_21__.TokenSendRequest);\n const tokenIds = allTokenOutputs\n .map((val) => val.tokenId)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let tokenId of tokenIds) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.tokenId === tokenId);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0);\n const tokenOutputs = allTokenOutputs.filter((val) => val.tokenId === tokenId);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0);\n const diff = inputAmountSum - outputAmountSum;\n if (diff < 0) {\n throw new Error(\"Not enough token amount to send\");\n }\n if (diff >= 0) {\n let available = 0;\n let change = 0;\n const ensureUtxos = [];\n for (const token of tokenInputs.filter((val) => val.token?.amount)) {\n ensureUtxos.push(token);\n available += token.token?.amount;\n if (available >= outputAmountSum) {\n change = available - outputAmountSum;\n break;\n }\n }\n if (ensureUtxos.length) {\n if (!options) {\n options = {};\n }\n options.ensureUtxos = [\n ...(options.ensureUtxos ?? []),\n ...ensureUtxos,\n ].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n }\n if (change > 0) {\n outputs.push(new _model_js__WEBPACK_IMPORTED_MODULE_21__.TokenSendRequest({\n cashaddr: (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_22__.toTokenaddr)(changeAddress) || this.tokenaddr,\n amount: change,\n tokenId: tokenId,\n commitment: tokenOutputs[0].commitment,\n capability: tokenOutputs[0].capability,\n value: tokenOutputs[0].value,\n }));\n }\n }\n }\n };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_32__.sumSendRequestAmounts)(sendRequests);\n if (utxos.length === 0) {\n throw Error(\"There were no Unspent Outputs\");\n }\n if (typeof spendAmount !== \"bigint\") {\n throw Error(\"Couldn't get spend amount when building transaction\");\n }\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_30__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_30__.getSuitableUtxos)(utxos, BigInt(spendAmount) + BigInt(feeEstimate), bestHeight, feePaidBy, sendRequests, options?.ensureUtxos || [], options?.tokenOperation);\n if (fundingUtxos.length === 0) {\n throw Error(\"The available inputs couldn't satisfy the request with fees\");\n }\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_30__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_30__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\n slpOutputs: [],\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n });\n const tokenIds = [\n ...fundingUtxos\n .filter((val) => val.token?.tokenId)\n .map((val) => val.token.tokenId),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_21__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n async signUnsignedTransaction(transaction, sourceOutputs) {\n if (!this.privateKey) {\n throw Error(\"Can not sign a transaction with watch-only wallet.\");\n }\n return (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_30__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory() {\n return await this.provider.getHistory(this.cashaddr);\n }\n // gets transaction history of this wallet\n async getHistory(unit, start, count, collapseChange) {\n return (0,_history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_33__.getAddressHistory)(this.cashaddr, this.provider, unit, start, count, collapseChange);\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash) {\n txHashSeen = true;\n this.provider.unsubscribeFromTransaction(options.txHash, waitForTransactionCallback);\n resolve(makeResponse(options.txHash));\n }\n };\n this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n watchCancel();\n resolve(makeResponse());\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n *\n * @returns a function which will cancel watching upon evaluation\n */\n watchBlocks(callback) {\n return this.provider.watchBlocks(callback);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_34__.secp256k1.derivePublicKeyUncompressed(this.privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n this.publicKey = publicKey;\n const publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_34__.secp256k1.derivePublicKeyCompressed(this.privateKey);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n this.publicKeyCompressed = publicKeyCompressed;\n const networkType = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest ? _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet : this.network;\n this.privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_24__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_23__.checkWifNetwork)(this.privateKeyWif, this.network);\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_22__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_22__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_13__.derivePublicKeyHash)(this.cashaddr);\n return this;\n }\n //#endregion Private implementation details\n //#region Signing\n // Convenience wrapper to sign interface\n async sign(message) {\n return await Wallet.signedMessage.sign(message, this.privateKey);\n }\n // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await Wallet.signedMessage.verify(message, sig, this.cashaddr, publicKey);\n }\n //#endregion Signing\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_21__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n const genesisInputs = utxos.filter((val) => val.vout === 0 && !val.token);\n if (genesisInputs.length === 0) {\n throw new Error(\"No suitable inputs with vout=0 available for new token genesis\");\n }\n const genesisSendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_21__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.tokenaddr,\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000,\n capability: genesisRequest.capability,\n commitment: genesisRequest.commitment,\n tokenId: genesisInputs[0].txid,\n });\n return this.send([genesisSendRequest, ...sendRequests], {\n ...options,\n utxoIds: utxos,\n ensureUtxos: [genesisInputs[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"genesis\",\n });\n }\n /**\n * Mint new NFT cashtokens using an existing minting token\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} tokenId tokenId of an NFT to mint\n * @param {TokenMintRequest | TokenMintRequest[]} mintRequests mint requests with new token properties and recipients\n * @param {NFTCapability?} mintRequest.capability capability of new NFT\n * @param {string?} mintRequest.commitment NFT commitment message\n * @param {string?} mintRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} mintRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {boolean?} deductTokenAmount if minting token contains fungible amount, deduct from it by amount of minted tokens\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenMint(tokenId, mintRequests, deductTokenAmount = false, options) {\n if (tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${tokenId}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const nftUtxos = utxos.filter((val) => val.token?.tokenId === tokenId &&\n val.token?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_9__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified tokenId\");\n }\n const newAmount = deductTokenAmount && nftUtxos[0].token.amount > 0\n ? nftUtxos[0].token.amount - mintRequests.length\n : nftUtxos[0].token.amount;\n const safeNewAmount = Math.max(0, newAmount);\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_21__.TokenSendRequest({\n cashaddr: this.tokenaddr,\n tokenId: tokenId,\n capability: nftUtxos[0].token.capability,\n commitment: nftUtxos[0].token.commitment,\n amount: safeNewAmount,\n value: nftUtxos[0].satoshis,\n });\n return this.send([\n mintingInput,\n ...mintRequests.map((val) => new _model_js__WEBPACK_IMPORTED_MODULE_21__.TokenSendRequest({\n cashaddr: val.cashaddr || this.tokenaddr,\n amount: 0,\n tokenId: tokenId,\n value: val.value,\n capability: val.capability,\n commitment: val.commitment,\n })),\n ], {\n ...options,\n ensureUtxos: [nftUtxos[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"mint\",\n });\n }\n /**\n * Perform an explicit token burning by spending a token utxo to an OP_RETURN\n *\n * Behaves differently for fungible and non-fungible tokens:\n * * NFTs are always \"destroyed\"\n * * FTs' amount is reduced by the amount specified, if 0 FT amount is left and no NFT present, the token is \"destroyed\"\n *\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} burnRequest.tokenId tokenId of a token to burn\n * @param {NFTCapability} burnRequest.capability capability of the NFT token to select, optional\n * @param {string?} burnRequest.commitment commitment of the NFT token to select, optional\n * @param {number?} burnRequest.amount amount of fungible tokens to burn, optional\n * @param {string?} burnRequest.cashaddr address to return token and satoshi change to\n * @param {string?} message optional message to include in OP_RETURN\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenBurn(burnRequest, message, options) {\n if (burnRequest.tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${burnRequest.tokenId}`);\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const tokenUtxos = utxos.filter((val) => val.token?.tokenId === burnRequest.tokenId &&\n val.token?.capability === burnRequest.capability &&\n val.token?.commitment === burnRequest.commitment);\n if (!tokenUtxos.length) {\n throw new Error(\"You do not have suitable token UTXOs to perform burn\");\n }\n const totalFungibleAmount = tokenUtxos.reduce((prev, cur) => prev + (cur.token?.amount || 0), 0);\n const fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0;\n const hasNFT = burnRequest.capability || burnRequest.commitment;\n let utxoIds = [];\n let changeSendRequests;\n if (hasNFT) {\n // does not have FT tokens, let us destroy the token completely\n if (totalFungibleAmount === 0) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // if there are FT, reduce their amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_21__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n capability: burnRequest.capability,\n commitment: burnRequest.commitment,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last fughible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // reduce the FT amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_21__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_21__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `tokenId` provided\n * @param {string?} tokenId tokenId (category) to filter utxos by, if not set will return utxos from all tokens\n * @returns {UtxoI[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getAddressUtxos(this.address);\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} fungible token balance\n */\n async getTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.amount);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_27__.sumTokenAmounts)(utxos, tokenId);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particula tokenId\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all tokens in this wallet\n */\n async getAllTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.amount);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += utxo.token.amount;\n }\n return result;\n }\n /**\n * getAllNftTokenBalances Gets all non-fungible token (NFT) balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += 1;\n }\n return result;\n }\n}\nWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.mainnet;\nWallet.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_36__.SignedMessage();\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet);\n }\n // will receive 10000 testnet satoshi, rate limits apply\n async getTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_testnet_bch`, { cashaddr: this.cashaddr });\n const data = response.data;\n return data.txId;\n }\n catch (e) {\n // console.log(e);\n // console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // be nice and return them back\n async returnTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_addresses`);\n const data = response.data;\n return await this.slpAware().sendMax(data.bchtest);\n }\n catch (e) {\n console.log(e);\n console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // will receive 10 testnet tokens, rate limits apply\n async getTestnetSlp(tokenId) {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_testnet_slp`, { slpaddr: this.slp.slpaddr, tokenId: tokenId });\n const data = response.data;\n return data.txId;\n }\n catch (e) {\n //console.log(e);\n //console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // be nice and return them back\n async returnTestnetSlp(tokenId) {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_addresses`);\n const data = response.data;\n return await this.slp.sendMax(data.slptest, tokenId);\n }\n catch (e) {\n console.log(e);\n console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_7__.TestNetSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_8__.TestNetUtil;\n }\n}\nTestNetWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWallet.faucetServer = \"https://rest-unstable.mainnet.cash\";\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_7__.RegTestSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_8__.RegTestUtil;\n }\n}\nRegTestWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_7__.WifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_8__.WifUtil;\n }\n}\nWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.mainnet;\nWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWifUtil;\n }\n}\nTestNetWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWifUtil;\n }\n}\nRegTestWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\nRegTestWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_7__.WatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_8__.WatchUtil;\n }\n}\nWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.mainnet;\nWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWatchUtil;\n }\n}\nTestNetWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWatchUtil;\n }\n}\nRegTestWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\nRegTestWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
1437
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestWallet\": () => (/* binding */ RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var bip39__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bip39 */ \"../../node_modules/bip39/src/index.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../util/asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../network/index.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Util_js__WEBPACK_IMPORTED_MODULE_7__, _network_index_js__WEBPACK_IMPORTED_MODULE_9__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_15__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_16__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__, _model_js__WEBPACK_IMPORTED_MODULE_19__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_28__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_29__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_30__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_31__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_32__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Util_js__WEBPACK_IMPORTED_MODULE_7__, _network_index_js__WEBPACK_IMPORTED_MODULE_9__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_15__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_16__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__, _model_js__WEBPACK_IMPORTED_MODULE_19__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_28__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_29__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_30__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_31__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_32__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n// Stable\n\n// Unstable?\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//#endregion Imports\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Base_js__WEBPACK_IMPORTED_MODULE_3__.BaseWallet {\n //#endregion\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n super(name, network, walletType);\n this.derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_6__.Config.DefaultParentDerivationPath + \"/0/0\";\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_6__.Config.DefaultParentDerivationPath;\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.fromId = async (walletId) => {\n let [walletType, networkGiven, arg1] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n if (walletType === \"wif\") {\n return this.fromWIF(arg1);\n }\n return super.fromId(walletId);\n };\n this.networkPrefix = _enum_js__WEBPACK_IMPORTED_MODULE_4__.prefixFromNetworkMap[this.network];\n }\n //#region Accessors\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_7__.Util(this);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.Util;\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_8__.Network.MAINNET) {\n return (0,_network_index_js__WEBPACK_IMPORTED_MODULE_9__.getNetworkProvider)(network);\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n return this.tokenaddr;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * @returns The qrcode for the token aware address\n */\n getTokenDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__.qrAddress)(this.getTokenDepositAddress());\n }\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n // Return wallet info\n getInfo() {\n return {\n cashaddr: this.cashaddr,\n tokenaddr: this.tokenaddr,\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic ? this.getSeed().seed : undefined,\n derivationPath: this.mnemonic ? this.getSeed().derivationPath : undefined,\n parentDerivationPath: this.mnemonic\n ? this.getSeed().parentDerivationPath\n : undefined,\n parentXPubKey: this.parentXPubKey ? this.parentXPubKey : undefined,\n publicKey: this.publicKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.privateKey) : undefined,\n privateKeyWif: this.privateKeyWif,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n // returns the public key hash for an address\n getPublicKey(hex = false) {\n if (this.publicKey) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKey) : this.publicKey;\n }\n else {\n throw Error(\"The public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyCompressed(hex = false) {\n if (this.publicKeyCompressed) {\n return hex\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyCompressed)\n : this.publicKeyCompressed;\n }\n else {\n throw Error(\"The compressed public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n if (this.publicKeyHash) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\n }\n else {\n throw Error(\"The public key hash for this wallet is not known. If this wallet was created from the constructor directly, calling the deriveInfo() function may help. \");\n }\n }\n /**\n * fromWIF - create a wallet using the private key supplied in `Wallet Import Format`\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromWIF(wif) {\n return new this().fromWIF(wif);\n }\n /**\n * fromCashaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromCashaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromTokenaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromTokenaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n //#endregion Constructors and Statics\n //#region Protected implementations\n async generate() {\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return await this._generateWif();\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n return this;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Hd) {\n throw Error(\"Not implemented\");\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n return await this._generateMnemonic();\n }\n else {\n console.log(this.walletType);\n throw Error(`Could not determine walletType: ${this.walletType}`);\n }\n }\n async _generateWif() {\n if (!this.privateKey) {\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_14__.generateRandomBytes)(32));\n }\n return this.deriveInfo();\n }\n async _generateMnemonic() {\n this.mnemonic = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.generateMnemonic)();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_15__.checkForEmptySeed)(seed);\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_16__.getXPubKey)(seed, this.parentDerivationPath, network);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n return await this.deriveInfo();\n }\n async getXPubKeys(paths) {\n if (this.mnemonic) {\n if (paths) {\n let xPubKeys = await this.deriveHdPaths(paths);\n return [xPubKeys];\n }\n else {\n return await this.deriveHdPaths(_constant_js__WEBPACK_IMPORTED_MODULE_18__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n this.mnemonic = mnemonic.trim().toLowerCase();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_15__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n if (derivationPath) {\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n let path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_16__.getXPubKey)(seed, this.parentDerivationPath, network);\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n await this.deriveInfo();\n return this;\n }\n // Get common xpub paths from zerothChild privateKey\n async deriveHdPaths(hdPaths) {\n if (!this.mnemonic)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_15__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let result = [];\n for (const path of hdPaths) {\n if (path === \"m\") {\n throw Error(\"Storing or sharing of parent public key may lead to loss of funds. Storing or sharing *root* parent public keys is strongly discouraged, although all parent keys have risk. See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#implications\");\n }\n let childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n let node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n let xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n });\n let key = new _model_js__WEBPACK_IMPORTED_MODULE_19__.XPubKey({\n path: path,\n xPubKey: xPubKey,\n });\n result.push(await key.ready());\n }\n return await Promise.all(result).then((result) => {\n return result;\n });\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n let addressComponents = address.split(\":\");\n let addressPrefix, addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[addressPrefix] != this.network) {\n throw Error(`a ${addressPrefix} address cannot be watched from a ${this.network} Wallet`);\n }\n }\n }\n this.cashaddr = `${addressPrefix}:${addressBase}`;\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePublicKeyHash)(this.cashaddr);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveTokenaddr)(this.publicKeyHash, this.networkPrefix);\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__.decodePrivateKeyWif)(secret);\n if (typeof wifResult === \"string\") {\n throw Error(wifResult);\n }\n let resultData = wifResult;\n this.privateKey = resultData.privateKey;\n this.privateKeyWif = secret;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n await this.deriveInfo();\n return this;\n }\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.newRandom(name, dbName);\n }\n async named(name, dbName, forceNew = false) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.named(name, dbName, forceNew);\n }\n async replaceNamed(name, walletId, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.replaceNamed(name, walletId, dbName);\n }\n async namedExists(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.namedExists(name, dbName);\n }\n //#endregion Protected Implementations\n //#region Serialization\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n const result = super.toString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toString unsupported wallet type\");\n }\n //\n toDbString() {\n const result = super.toDbString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n //\n async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_18__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n if (!this.cashaddr) {\n throw Error(\"Attempted to get utxos without an address\");\n }\n return await this.getAddressUtxos(this.cashaddr);\n }\n // gets wallet balance in sats, bch and usd\n async getBalance(rawUnit, usdPriceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_23__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, usdPriceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.balanceResponseFromSatoshi)(await this.getBalanceFromProvider(), usdPriceCache);\n }\n }\n // Gets balance by summing value in all utxos in stats\n async getBalanceFromUtxos() {\n const utxos = (await this.getAddressUtxos(this.cashaddr)).filter((val) => val.token === undefined);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider!.getBalance(this.cashaddr!);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n // watching for any transaction hash of this wallet\n watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = (await this.getBalance());\n callback(balance);\n });\n }\n // sets up a callback to be called upon wallet's BCH or USD balance change\n // if BCH balance does not change, the callback will be triggered every\n // @param `usdPriceRefreshInterval` milliseconds by polling for new BCH USD price\n // Since we want to be most sensitive to usd value change, we do not use the cached exchange rates\n // can be cancelled by calling the function returned from this one\n watchBalanceUsd(callback, usdPriceRefreshInterval = 30000) {\n let usdPrice = -1;\n const _callback = async () => {\n const balance = (await this.getBalance(undefined, false));\n if (usdPrice !== balance.usd) {\n usdPrice = balance.usd;\n callback(balance);\n }\n };\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), _callback);\n const interval = setInterval(_callback, usdPriceRefreshInterval);\n return async () => {\n await watchCancel();\n clearInterval(interval);\n };\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value, rawUnit = _enum_js__WEBPACK_IMPORTED_MODULE_4__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__.amountInSatoshi)(value, rawUnit);\n if (balance.sat >= satoshiBalance) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n async getTokenInfo(tokenId) {\n return _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__.BCMR.getTokenInfo(tokenId);\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!this.privateKey && params.options?.buildUnsigned !== true) {\n throw Error(\"Couldn't get network or private key for wallet.\");\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (params.options && params.options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (params.options && params.options.feePaidBy) {\n feePaidBy = params.options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n // get inputs\n let utxos;\n if (params.options && params.options.utxoIds) {\n utxos = params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_19__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = (await this.getAddressUtxos(this.cashaddr)).filter((utxo) => !utxo.token);\n }\n // Get current height to assure recently mined coins are not spent.\n const bestHeight = await this.provider.getBlockHeight();\n // simulate outputs using the sender's address\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_19__.SendRequest({\n cashaddr: this.cashaddr,\n value: 100,\n unit: \"sat\",\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_28__.getSuitableUtxos)(utxos, undefined, bestHeight, feePaidBy, sendRequests);\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_28__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0) {\n result = 0;\n }\n return { value: result, utxos: fundingUtxos };\n }\n async getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n const { value: result } = await this._getMaxAmountToSend(params);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.balanceResponseFromSatoshi)(result);\n }\n /**\n * send Send some amount to an address\n * this function processes the send requests, encodes the transaction, sends it to the network\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n *\n * This is a first class function with REST analog, maintainers should strive to keep backward-compatibility\n *\n */\n async send(requests, options) {\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_19__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_19__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_19__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options) {\n let sendRequests = (0,_util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_29__.asSendRequestObject)(requests);\n if (!this.privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Wallet ${this.name} is missing either a network or private key`);\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options && options.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options && options.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.cashaddr;\n }\n let checkTokenQuantities = true;\n if (options && options.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_19__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n // filter out token utxos if there are no token requests\n if (checkTokenQuantities &&\n !sendRequests.some((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_19__.TokenSendRequest)) {\n utxos = utxos.filter((val) => !val.token);\n }\n const addTokenChangeOutputs = (inputs, outputs) => {\n // allow for implicit token burn if the total amount sent is less than user had\n // allow for token genesis, creating more tokens than we had before (0)\n if (!checkTokenQuantities) {\n return;\n }\n const allTokenInputs = inputs.filter((val) => val.token);\n const allTokenOutputs = outputs.filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_19__.TokenSendRequest);\n const tokenIds = allTokenOutputs\n .map((val) => val.tokenId)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let tokenId of tokenIds) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.tokenId === tokenId);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0);\n const tokenOutputs = allTokenOutputs.filter((val) => val.tokenId === tokenId);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0);\n const diff = inputAmountSum - outputAmountSum;\n if (diff < 0) {\n throw new Error(\"Not enough token amount to send\");\n }\n if (diff >= 0) {\n let available = 0;\n let change = 0;\n const ensureUtxos = [];\n for (const token of tokenInputs.filter((val) => val.token?.amount)) {\n ensureUtxos.push(token);\n available += token.token?.amount;\n if (available >= outputAmountSum) {\n change = available - outputAmountSum;\n break;\n }\n }\n if (ensureUtxos.length) {\n if (!options) {\n options = {};\n }\n options.ensureUtxos = [\n ...(options.ensureUtxos ?? []),\n ...ensureUtxos,\n ].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n }\n if (change > 0) {\n outputs.push(new _model_js__WEBPACK_IMPORTED_MODULE_19__.TokenSendRequest({\n cashaddr: (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.toTokenaddr)(changeAddress) || this.tokenaddr,\n amount: change,\n tokenId: tokenId,\n commitment: tokenOutputs[0].commitment,\n capability: tokenOutputs[0].capability,\n value: tokenOutputs[0].value,\n }));\n }\n }\n }\n };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_30__.sumSendRequestAmounts)(sendRequests);\n if (utxos.length === 0) {\n throw Error(\"There were no Unspent Outputs\");\n }\n if (typeof spendAmount !== \"bigint\") {\n throw Error(\"Couldn't get spend amount when building transaction\");\n }\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_28__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_28__.getSuitableUtxos)(utxos, BigInt(spendAmount) + BigInt(feeEstimate), bestHeight, feePaidBy, sendRequests, options?.ensureUtxos || [], options?.tokenOperation);\n if (fundingUtxos.length === 0) {\n throw Error(\"The available inputs couldn't satisfy the request with fees\");\n }\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_28__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_28__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n });\n const tokenIds = [\n ...fundingUtxos\n .filter((val) => val.token?.tokenId)\n .map((val) => val.token.tokenId),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_19__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n async signUnsignedTransaction(transaction, sourceOutputs) {\n if (!this.privateKey) {\n throw Error(\"Can not sign a transaction with watch-only wallet.\");\n }\n return (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_28__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory() {\n return await this.provider.getHistory(this.cashaddr);\n }\n // gets transaction history of this wallet\n async getHistory(unit, start, count, collapseChange) {\n return (0,_history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_31__.getAddressHistory)(this.cashaddr, this.provider, unit, start, count, collapseChange);\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash) {\n txHashSeen = true;\n this.provider.unsubscribeFromTransaction(options.txHash, waitForTransactionCallback);\n resolve(makeResponse(options.txHash));\n }\n };\n this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n watchCancel();\n resolve(makeResponse());\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n *\n * @returns a function which will cancel watching upon evaluation\n */\n watchBlocks(callback) {\n return this.provider.watchBlocks(callback);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_32__.secp256k1.derivePublicKeyUncompressed(this.privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n this.publicKey = publicKey;\n const publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_32__.secp256k1.derivePublicKeyCompressed(this.privateKey);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n this.publicKeyCompressed = publicKeyCompressed;\n const networkType = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest ? _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet : this.network;\n this.privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__.checkWifNetwork)(this.privateKeyWif, this.network);\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePublicKeyHash)(this.cashaddr);\n return this;\n }\n //#endregion Private implementation details\n //#region Signing\n // Convenience wrapper to sign interface\n async sign(message) {\n return await Wallet.signedMessage.sign(message, this.privateKey);\n }\n // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await Wallet.signedMessage.verify(message, sig, this.cashaddr, publicKey);\n }\n //#endregion Signing\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_19__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n const genesisInputs = utxos.filter((val) => val.vout === 0 && !val.token);\n if (genesisInputs.length === 0) {\n throw new Error(\"No suitable inputs with vout=0 available for new token genesis\");\n }\n const genesisSendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_19__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.tokenaddr,\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000,\n capability: genesisRequest.capability,\n commitment: genesisRequest.commitment,\n tokenId: genesisInputs[0].txid,\n });\n return this.send([genesisSendRequest, ...sendRequests], {\n ...options,\n utxoIds: utxos,\n ensureUtxos: [genesisInputs[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"genesis\",\n });\n }\n /**\n * Mint new NFT cashtokens using an existing minting token\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} tokenId tokenId of an NFT to mint\n * @param {TokenMintRequest | TokenMintRequest[]} mintRequests mint requests with new token properties and recipients\n * @param {NFTCapability?} mintRequest.capability capability of new NFT\n * @param {string?} mintRequest.commitment NFT commitment message\n * @param {string?} mintRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} mintRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {boolean?} deductTokenAmount if minting token contains fungible amount, deduct from it by amount of minted tokens\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenMint(tokenId, mintRequests, deductTokenAmount = false, options) {\n if (tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${tokenId}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const nftUtxos = utxos.filter((val) => val.token?.tokenId === tokenId &&\n val.token?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_8__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified tokenId\");\n }\n const newAmount = deductTokenAmount && nftUtxos[0].token.amount > 0\n ? nftUtxos[0].token.amount - mintRequests.length\n : nftUtxos[0].token.amount;\n const safeNewAmount = Math.max(0, newAmount);\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_19__.TokenSendRequest({\n cashaddr: this.tokenaddr,\n tokenId: tokenId,\n capability: nftUtxos[0].token.capability,\n commitment: nftUtxos[0].token.commitment,\n amount: safeNewAmount,\n value: nftUtxos[0].satoshis,\n });\n return this.send([\n mintingInput,\n ...mintRequests.map((val) => new _model_js__WEBPACK_IMPORTED_MODULE_19__.TokenSendRequest({\n cashaddr: val.cashaddr || this.tokenaddr,\n amount: 0,\n tokenId: tokenId,\n value: val.value,\n capability: val.capability,\n commitment: val.commitment,\n })),\n ], {\n ...options,\n ensureUtxos: [nftUtxos[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"mint\",\n });\n }\n /**\n * Perform an explicit token burning by spending a token utxo to an OP_RETURN\n *\n * Behaves differently for fungible and non-fungible tokens:\n * * NFTs are always \"destroyed\"\n * * FTs' amount is reduced by the amount specified, if 0 FT amount is left and no NFT present, the token is \"destroyed\"\n *\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} burnRequest.tokenId tokenId of a token to burn\n * @param {NFTCapability} burnRequest.capability capability of the NFT token to select, optional\n * @param {string?} burnRequest.commitment commitment of the NFT token to select, optional\n * @param {number?} burnRequest.amount amount of fungible tokens to burn, optional\n * @param {string?} burnRequest.cashaddr address to return token and satoshi change to\n * @param {string?} message optional message to include in OP_RETURN\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenBurn(burnRequest, message, options) {\n if (burnRequest.tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${burnRequest.tokenId}`);\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const tokenUtxos = utxos.filter((val) => val.token?.tokenId === burnRequest.tokenId &&\n val.token?.capability === burnRequest.capability &&\n val.token?.commitment === burnRequest.commitment);\n if (!tokenUtxos.length) {\n throw new Error(\"You do not have suitable token UTXOs to perform burn\");\n }\n const totalFungibleAmount = tokenUtxos.reduce((prev, cur) => prev + (cur.token?.amount || 0), 0);\n const fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0;\n const hasNFT = burnRequest.capability || burnRequest.commitment;\n let utxoIds = [];\n let changeSendRequests;\n if (hasNFT) {\n // does not have FT tokens, let us destroy the token completely\n if (totalFungibleAmount === 0) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // if there are FT, reduce their amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_19__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n capability: burnRequest.capability,\n commitment: burnRequest.commitment,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last fughible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // reduce the FT amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_19__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_19__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `tokenId` provided\n * @param {string?} tokenId tokenId (category) to filter utxos by, if not set will return utxos from all tokens\n * @returns {UtxoI[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getAddressUtxos(this.address);\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} fungible token balance\n */\n async getTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.amount);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.sumTokenAmounts)(utxos, tokenId);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particula tokenId\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all tokens in this wallet\n */\n async getAllTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.amount);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += utxo.token.amount;\n }\n return result;\n }\n /**\n * getAllNftTokenBalances Gets all non-fungible token (NFT) balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += 1;\n }\n return result;\n }\n}\nWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.CashAddressNetworkPrefix.mainnet;\nWallet.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_34__.SignedMessage();\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet);\n }\n // will receive 10000 testnet satoshi, rate limits apply\n async getTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_testnet_bch`, { cashaddr: this.cashaddr });\n const data = response.data;\n return data.txId;\n }\n catch (e) {\n // console.log(e);\n // console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // be nice and return them back\n async returnTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_addresses`);\n const data = response.data;\n return await this.sendMax(data.bchtest);\n }\n catch (e) {\n console.log(e);\n console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetUtil;\n }\n}\nTestNetWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.CashAddressNetworkPrefix.testnet;\nTestNetWallet.faucetServer = \"https://rest-unstable.mainnet.cash\";\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestUtil;\n }\n}\nRegTestWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.CashAddressNetworkPrefix.regtest;\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.WifUtil;\n }\n}\nWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.CashAddressNetworkPrefix.mainnet;\nWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWifUtil;\n }\n}\nTestNetWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.CashAddressNetworkPrefix.testnet;\nTestNetWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWifUtil;\n }\n}\nRegTestWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.CashAddressNetworkPrefix.regtest;\nRegTestWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.WatchUtil;\n }\n}\nWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.CashAddressNetworkPrefix.mainnet;\nWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWatchUtil;\n }\n}\nTestNetWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.CashAddressNetworkPrefix.testnet;\nTestNetWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWatchUtil;\n }\n}\nRegTestWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.CashAddressNetworkPrefix.regtest;\nRegTestWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
1668
1438
 
1669
1439
  /***/ }),
1670
1440
 
@@ -1674,7 +1444,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1674
1444
  \************************************/
1675
1445
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1676
1446
 
1677
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"createSlpWallet\": () => (/* binding */ createSlpWallet),\n/* harmony export */ \"createSlpWalletResponse\": () => (/* binding */ createSlpWalletResponse),\n/* harmony export */ \"createWallet\": () => (/* binding */ createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* binding */ createWalletResponse),\n/* harmony export */ \"namedWallet\": () => (/* binding */ namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* binding */ namedWalletExists),\n/* harmony export */ \"replaceNamedWallet\": () => (/* binding */ replaceNamedWallet),\n/* harmony export */ \"walletClassMap\": () => (/* binding */ walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* binding */ walletFromId)\n/* harmony export */ });\n/* harmony import */ var _Wif_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Wif_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _Base_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_Wif_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _Base_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n// Convenience map to access classes by types and network\nconst walletClassMap = {\n wif: {\n mainnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.WifWallet;\n },\n testnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWifWallet;\n },\n regtest: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWifWallet;\n },\n },\n seed: {\n mainnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.Wallet;\n },\n testnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWallet;\n },\n regtest: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWallet;\n },\n },\n watch: {\n mainnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.WatchWallet;\n },\n testnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWatchWallet;\n },\n regtest: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWatchWallet;\n },\n },\n};\n/**\n * Check wallet type and network of a requested wallet for mismatches against retrieved from DB\n */\nfunction checkWalletTypeAndNetwork(wallet, walletType, networkType) {\n if (wallet.network != networkType) {\n throw Error(`A wallet already exists with name ${wallet.name}, but with network ${wallet.network} not ${networkType}, per request`);\n }\n if (wallet.walletType != walletType) {\n throw Error(`A wallet already exists with name ${wallet.name}, but with type ${wallet.walletType} not ${walletType}, per request`);\n }\n}\n/**\n * Check if wallet exists\n * @param body A wallet request object\n * @returns A promise to the check result\n */\nasync function namedWalletExists(body) {\n const walletType = body.type ? body.type : \"seed\";\n const networkType = body.network ? body.network : \"mainnet\";\n const name = body.name;\n return await walletClassMap[walletType][networkType]().namedExists(name);\n}\n/**\n * Get or create a named wallet\n * @param name user friendly wallet alias\n * @param walletType wallet type\n * @param networkType wallet network type\n * @returns A promise to a new wallet object\n */\nasync function namedWallet(name, walletType, networkType) {\n // Named wallets are saved in the database\n if (!name) {\n throw Error(`Wallet name is required for this operation`);\n }\n let wallet;\n const dbName = _enum_js__WEBPACK_IMPORTED_MODULE_1__.prefixFromNetworkMap[networkType];\n if (walletClassMap[walletType] !== undefined) {\n wallet = await walletClassMap[walletType][networkType]().named(name);\n checkWalletTypeAndNetwork(wallet, walletType, networkType);\n }\n else {\n let walletId = await (0,_Base_js__WEBPACK_IMPORTED_MODULE_2__.getNamedWalletId)(name, dbName);\n if (walletId !== undefined) {\n wallet = await walletFromId(walletId);\n wallet.name = name;\n }\n else {\n throw Error(\"A named wallet, without wallet type, was passed but there was no corresponding record for the named wallet in the database.\");\n }\n }\n return wallet;\n}\n/**\n * Replace or create a named wallet with a walletId\n * @param body A wallet request object\n * @returns A promise to a new wallet object\n */\nasync function replaceNamedWallet(body) {\n let wallet;\n const walletType = body.type ? body.type : \"seed\";\n const networkType = body.network ? body.network : \"mainnet\";\n const name = body.name;\n const walletId = body.walletId;\n // Named wallets are saved in the database\n if (!name || !walletId) {\n throw Error(`Wallet name and walletId are required for this operation`);\n }\n wallet = await walletClassMap[walletType][networkType]().replaceNamed(name, walletId);\n return wallet;\n}\n/**\n * Create a new wallet\n * @param body A wallet request object\n * @returns A promise to a new wallet object\n */\nasync function createWallet(body) {\n let wallet;\n let walletType = body.type ? body.type : \"seed\";\n let networkType = body.network ? body.network : \"mainnet\";\n // Named wallets are saved in the database\n if (body.name && body.name.length > 0) {\n wallet = await namedWallet(body.name, walletType, networkType);\n return wallet;\n }\n // This handles unsaved/unnamed wallets\n else {\n let walletClass = walletClassMap[walletType][networkType]();\n wallet = await new walletClass();\n wallet.walletType = walletType;\n return wallet.generate();\n }\n}\n/**\n * Create a new SLP aware wallet\n * @param body A wallet request object\n * @returns A promise to a new wallet object\n */\nasync function createSlpWallet(body) {\n let wallet;\n let walletType = body.type ? body.type : \"seed\";\n let networkType = body.network ? body.network : \"mainnet\";\n // Named wallets are saved in the database\n if (body.name && body.name.length > 0) {\n wallet = await walletClassMap[walletType][networkType]().slp.named(body.name);\n if (wallet.network != networkType) {\n throw Error(`A wallet already exists with name ${body.name}, but with network ${wallet.network} not ${body.network}, per request`);\n }\n if (wallet.walletType != walletType) {\n throw Error(`A wallet already exists with name ${body.name}, but with type ${wallet.walletType} not ${body.type}, per request`);\n }\n return wallet;\n }\n // This handles unsaved/unnamed wallets\n else {\n wallet = await walletClassMap[walletType][networkType]().slp.newRandom();\n wallet.walletType = walletType;\n return wallet;\n }\n}\n/**\n * Create a new wallet\n * @param walletRequest A wallet request object\n * @returns A new wallet object\n */\nasync function createWalletResponse(walletRequest) {\n let wallet = await createWallet(walletRequest);\n if (wallet) {\n return asJsonResponse(wallet);\n }\n else {\n throw Error(\"Error creating wallet\");\n }\n}\n/**\n * Create a new SLP aware wallet\n * @param walletRequest A wallet request object\n * @returns A new wallet object\n */\nasync function createSlpWalletResponse(walletRequest) {\n let wallet = await createSlpWallet(walletRequest);\n if (wallet) {\n return asJsonResponse(wallet);\n }\n else {\n throw Error(\"Error creating wallet\");\n }\n}\n/**\n * asJsonResponse return a wallet as json\n * @param wallet A wallet object\n * @returns A json wallet response\n */\nfunction asJsonResponse(wallet) {\n if (wallet.mnemonic) {\n return {\n name: wallet.name,\n cashaddr: wallet.cashaddr,\n slpaddr: wallet.slp.slpaddr,\n walletId: wallet.toString(),\n ...wallet.getSeed(),\n network: wallet.network,\n };\n }\n else {\n return {\n name: wallet.name,\n cashaddr: wallet.cashaddr,\n slpaddr: wallet.slp.slpaddr,\n walletId: wallet.toString(),\n wif: wallet.privateKeyWif,\n network: wallet.network,\n };\n }\n}\n/**\n * walletFromId - get a wallet from a serialized wallet\n * @param {string} walletId A serialized wallet object\n * @returns A wallet\n */\nasync function walletFromId(walletId) {\n let [walletType, network, name] = walletId.split(\":\");\n if (walletType === \"named\") {\n return await namedWallet(name, walletType, network);\n }\n let walletRequest = {\n name: \"\",\n network: network,\n type: walletType,\n };\n let wallet = await createWallet(walletRequest);\n await wallet.fromId(walletId);\n return wallet;\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/createWallet.ts?");
1447
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"createWallet\": () => (/* binding */ createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* binding */ createWalletResponse),\n/* harmony export */ \"namedWallet\": () => (/* binding */ namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* binding */ namedWalletExists),\n/* harmony export */ \"replaceNamedWallet\": () => (/* binding */ replaceNamedWallet),\n/* harmony export */ \"walletClassMap\": () => (/* binding */ walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* binding */ walletFromId)\n/* harmony export */ });\n/* harmony import */ var _Wif_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Wif_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _Base_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_Wif_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _Base_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n// Convenience map to access classes by types and network\nconst walletClassMap = {\n wif: {\n mainnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.WifWallet;\n },\n testnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWifWallet;\n },\n regtest: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWifWallet;\n },\n },\n seed: {\n mainnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.Wallet;\n },\n testnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWallet;\n },\n regtest: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWallet;\n },\n },\n watch: {\n mainnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.WatchWallet;\n },\n testnet: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.TestNetWatchWallet;\n },\n regtest: () => {\n return _Wif_js__WEBPACK_IMPORTED_MODULE_0__.RegTestWatchWallet;\n },\n },\n};\n/**\n * Check wallet type and network of a requested wallet for mismatches against retrieved from DB\n */\nfunction checkWalletTypeAndNetwork(wallet, walletType, networkType) {\n if (wallet.network != networkType) {\n throw Error(`A wallet already exists with name ${wallet.name}, but with network ${wallet.network} not ${networkType}, per request`);\n }\n if (wallet.walletType != walletType) {\n throw Error(`A wallet already exists with name ${wallet.name}, but with type ${wallet.walletType} not ${walletType}, per request`);\n }\n}\n/**\n * Check if wallet exists\n * @param body A wallet request object\n * @returns A promise to the check result\n */\nasync function namedWalletExists(body) {\n const walletType = body.type ? body.type : \"seed\";\n const networkType = body.network ? body.network : \"mainnet\";\n const name = body.name;\n return await walletClassMap[walletType][networkType]().namedExists(name);\n}\n/**\n * Get or create a named wallet\n * @param name user friendly wallet alias\n * @param walletType wallet type\n * @param networkType wallet network type\n * @returns A promise to a new wallet object\n */\nasync function namedWallet(name, walletType, networkType) {\n // Named wallets are saved in the database\n if (!name) {\n throw Error(`Wallet name is required for this operation`);\n }\n let wallet;\n const dbName = _enum_js__WEBPACK_IMPORTED_MODULE_1__.prefixFromNetworkMap[networkType];\n if (walletClassMap[walletType] !== undefined) {\n wallet = await walletClassMap[walletType][networkType]().named(name);\n checkWalletTypeAndNetwork(wallet, walletType, networkType);\n }\n else {\n let walletId = await (0,_Base_js__WEBPACK_IMPORTED_MODULE_2__.getNamedWalletId)(name, dbName);\n if (walletId !== undefined) {\n wallet = await walletFromId(walletId);\n wallet.name = name;\n }\n else {\n throw Error(\"A named wallet, without wallet type, was passed but there was no corresponding record for the named wallet in the database.\");\n }\n }\n return wallet;\n}\n/**\n * Replace or create a named wallet with a walletId\n * @param body A wallet request object\n * @returns A promise to a new wallet object\n */\nasync function replaceNamedWallet(body) {\n let wallet;\n const walletType = body.type ? body.type : \"seed\";\n const networkType = body.network ? body.network : \"mainnet\";\n const name = body.name;\n const walletId = body.walletId;\n // Named wallets are saved in the database\n if (!name || !walletId) {\n throw Error(`Wallet name and walletId are required for this operation`);\n }\n wallet = await walletClassMap[walletType][networkType]().replaceNamed(name, walletId);\n return wallet;\n}\n/**\n * Create a new wallet\n * @param body A wallet request object\n * @returns A promise to a new wallet object\n */\nasync function createWallet(body) {\n let wallet;\n let walletType = body.type ? body.type : \"seed\";\n let networkType = body.network ? body.network : \"mainnet\";\n // Named wallets are saved in the database\n if (body.name && body.name.length > 0) {\n wallet = await namedWallet(body.name, walletType, networkType);\n return wallet;\n }\n // This handles unsaved/unnamed wallets\n else {\n let walletClass = walletClassMap[walletType][networkType]();\n wallet = await new walletClass();\n wallet.walletType = walletType;\n return wallet.generate();\n }\n}\n/**\n * Create a new wallet\n * @param walletRequest A wallet request object\n * @returns A new wallet object\n */\nasync function createWalletResponse(walletRequest) {\n let wallet = await createWallet(walletRequest);\n if (wallet) {\n return asJsonResponse(wallet);\n }\n else {\n throw Error(\"Error creating wallet\");\n }\n}\n/**\n * asJsonResponse return a wallet as json\n * @param wallet A wallet object\n * @returns A json wallet response\n */\nfunction asJsonResponse(wallet) {\n if (wallet.mnemonic) {\n return {\n name: wallet.name,\n cashaddr: wallet.cashaddr,\n walletId: wallet.toString(),\n ...wallet.getSeed(),\n network: wallet.network,\n };\n }\n else {\n return {\n name: wallet.name,\n cashaddr: wallet.cashaddr,\n walletId: wallet.toString(),\n wif: wallet.privateKeyWif,\n network: wallet.network,\n };\n }\n}\n/**\n * walletFromId - get a wallet from a serialized wallet\n * @param {string} walletId A serialized wallet object\n * @returns A wallet\n */\nasync function walletFromId(walletId) {\n let [walletType, network, name] = walletId.split(\":\");\n if (walletType === \"named\") {\n return await namedWallet(name, walletType, network);\n }\n let walletRequest = {\n name: \"\",\n network: network,\n type: walletType,\n };\n let wallet = await createWallet(walletRequest);\n await wallet.fromId(walletId);\n return wallet;\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/createWallet.ts?");
1678
1448
 
1679
1449
  /***/ }),
1680
1450
 
@@ -1698,56 +1468,6 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1698
1468
 
1699
1469
  /***/ }),
1700
1470
 
1701
- /***/ "./src/webhook/Webhook.ts":
1702
- /*!********************************!*\
1703
- !*** ./src/webhook/Webhook.ts ***!
1704
- \********************************/
1705
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1706
-
1707
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"Webhook\": () => (/* binding */ Webhook),\n/* harmony export */ \"WebhookRecurrence\": () => (/* binding */ WebhookRecurrence),\n/* harmony export */ \"WebhookType\": () => (/* binding */ WebhookType)\n/* harmony export */ });\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\nvar _a;\n\nvar WebhookType;\n(function (WebhookType) {\n WebhookType[\"transactionIn\"] = \"transaction:in\";\n WebhookType[\"transactionOut\"] = \"transaction:out\";\n WebhookType[\"transactionInOut\"] = \"transaction:in,out\";\n WebhookType[\"balance\"] = \"balance\";\n WebhookType[\"slpTransactionIn\"] = \"slptransaction:in\";\n WebhookType[\"slpTransactionOut\"] = \"slptransaction:out\";\n WebhookType[\"slpTransactionInOut\"] = \"slptransaction:in,out\";\n WebhookType[\"slpBalance\"] = \"slpbalance\";\n})(WebhookType || (WebhookType = {}));\nvar WebhookRecurrence;\n(function (WebhookRecurrence) {\n WebhookRecurrence[\"once\"] = \"once\";\n WebhookRecurrence[\"recurrent\"] = \"recurrent\";\n})(WebhookRecurrence || (WebhookRecurrence = {}));\nclass Webhook {\n constructor(hook) {\n Object.assign(this, hook);\n }\n // abstract, empty implementation\n async start() { }\n // abstract, empty implementation\n async stop() { }\n async destroy() {\n if (this.id) {\n await this.db.deleteWebhook(this.id);\n }\n }\n async post(data) {\n try {\n await axios__WEBPACK_IMPORTED_MODULE_0___default().post(this.url, data);\n // console.debug(\"Posted webhook\", this.url, data);\n return true;\n }\n catch (e) {\n if (e.message && e.message.status === 200) {\n return true;\n }\n // console.debug(\"Failed to post webhook\", this.url, e);\n return false;\n }\n }\n}\n//#region debug\nWebhook.debug = (_a = class {\n static setupAxiosMocks() {\n axios__WEBPACK_IMPORTED_MODULE_0___default().interceptors.request.use((config) => {\n const url = config.url;\n if (!url.startsWith(\"http://example.com\")) {\n return config;\n }\n let response;\n if (url === \"http://example.com/fail\") {\n response = { status: 503 };\n }\n else {\n response = { status: 200 };\n }\n if (url in this.responses) {\n this.responses[url].push(response);\n }\n else {\n this.responses[url] = [response];\n }\n // cancel actual http request\n return {\n ...config,\n cancelToken: new (axios__WEBPACK_IMPORTED_MODULE_0___default().CancelToken)((cancel) => cancel(response)),\n };\n });\n }\n static reset() {\n this.responses = {};\n }\n },\n _a.responses = {},\n _a);\n\n\n//# sourceURL=webpack://mainnet-js/./src/webhook/Webhook.ts?");
1708
-
1709
- /***/ }),
1710
-
1711
- /***/ "./src/webhook/WebhookBch.ts":
1712
- /*!***********************************!*\
1713
- !*** ./src/webhook/WebhookBch.ts ***!
1714
- \***********************************/
1715
- /***/ ((module, __webpack_exports__, __webpack_require__) => {
1716
-
1717
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"WebhookBch\": () => (/* binding */ WebhookBch)\n/* harmony export */ });\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _Webhook_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Webhook.js */ \"./src/webhook/Webhook.ts\");\n/* harmony import */ var _WebhookWorker_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./WebhookWorker.js */ \"./src/webhook/WebhookWorker.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_Wif_js__WEBPACK_IMPORTED_MODULE_1__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_wallet_Wif_js__WEBPACK_IMPORTED_MODULE_1__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\nclass WebhookBch extends _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.Webhook {\n constructor(hook) {\n super(hook);\n this.seenStatuses = [];\n Object.assign(this, hook);\n }\n async stop() {\n await this.wallet.provider.unsubscribeFromAddress(this.cashaddr, this.callback);\n }\n async start() {\n const webhookCallback = async (data) => {\n let status = \"\";\n if (typeof data === \"string\") {\n // subscription acknowledgement notification with current status\n status = data;\n // we should skip fetching transactions for freshly registered hooks upon acknowledements\n if (this.status === \"\") {\n return;\n }\n }\n else if (data instanceof Array) {\n status = data[1];\n if (data[0] !== this.cashaddr) {\n // console.warn(\"Address missmatch, skipping\", data[0], this.cashaddr);\n return;\n }\n }\n else {\n return;\n }\n if (status != this.status && this.seenStatuses.indexOf(status) === -1) {\n this.seenStatuses.push(status);\n await this.handler(status);\n }\n };\n this.callback = webhookCallback;\n this.wallet = await _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_1__.Wallet.fromCashaddr(this.cashaddr);\n await this.wallet.provider.subscribeToAddress(this.cashaddr, this.callback);\n }\n async handler(status) {\n // console.debug(\"Dispatching action for a webhook\", this);\n // get transactions\n const history = await this.wallet.provider.getHistory(this.cashaddr);\n // figure out which transactions to send to the hook\n let txs = [];\n if (status === \"\") {\n // send the last transaction only if no tracking was done\n txs = history.slice(-1);\n }\n else {\n // reverse history for faster search\n const revHistory = history.reverse();\n // update height of transactions, which are now confirmed\n this.tx_seen = this.tx_seen.map((seenTx) => {\n if (seenTx.height <= 0) {\n const histTx = revHistory.find((val) => val.tx_hash === seenTx.tx_hash);\n if (histTx) {\n seenTx.height = histTx.height;\n }\n }\n return seenTx;\n });\n const seenHashes = this.tx_seen.map((val) => val.tx_hash);\n txs = history.filter((val) => (val.height >= this.last_height || val.height <= 0) &&\n !seenHashes.includes(val.tx_hash));\n }\n let shouldUpdateStatus = true;\n for (const tx of txs) {\n // watching transactions\n let result = false;\n if (this.type.indexOf(\"transaction:\") >= 0) {\n // console.debug(\"Getting raw tx\", tx.tx_hash);\n const rawTx = await this.wallet.provider.getRawTransactionObject(tx.tx_hash);\n const parentTxs = await Promise.all(rawTx.vin.map((t) => this.wallet.provider.getRawTransactionObject(t.txid)));\n // console.debug(\"Got raw tx\", JSON.stringify(rawTx, null, 2));\n const haveAddressInOutputs = rawTx.vout.some((val) => val.scriptPubKey.addresses.includes(this.cashaddr));\n const haveAddressInParentOutputs = parentTxs.some((parent) => parent.vout.some((val) => val.scriptPubKey.addresses.includes(this.cashaddr)));\n const wantsIn = this.type.indexOf(\"in\") >= 0;\n const wantsOut = this.type.indexOf(\"out\") >= 0;\n const txDirection = haveAddressInParentOutputs && haveAddressInOutputs\n ? _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.transactionInOut\n : haveAddressInParentOutputs\n ? _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.transactionOut\n : _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.transactionIn;\n if (wantsIn && haveAddressInOutputs) {\n result = await this.post({\n direction: txDirection,\n data: rawTx,\n });\n }\n else if (wantsOut && haveAddressInParentOutputs) {\n result = await this.post({\n direction: txDirection,\n data: rawTx,\n });\n }\n else {\n // not interested in this transaction\n continue;\n }\n }\n else if (this.type === _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.balance) {\n // watching address balance\n const balanceSat = await this.wallet.provider.getBalance(this.cashaddr);\n const balanceObject = await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_2__.balanceResponseFromSatoshi)(balanceSat);\n result = await this.post(balanceObject);\n }\n if (result) {\n this.tx_seen.push(tx);\n await this.db.setWebhookSeenTxLastHeight(this.id, this.tx_seen, this.last_height);\n }\n else {\n // console.debug(\"Failed to execute webhook\", hook);\n shouldUpdateStatus = false;\n }\n }\n // successful run\n if (shouldUpdateStatus) {\n if (this.recurrence === _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookRecurrence.once) {\n // we have to notify the worker about end of life\n await (await _WebhookWorker_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"].instance()).stopHook(this);\n await this.destroy();\n return;\n }\n this.status = status;\n await this.db.setWebhookStatus(this.id, status);\n // update last_height and truncate tx_seen\n const maxHeight = Math.max(...this.tx_seen.map((val) => val.height));\n if (maxHeight >= this.last_height) {\n this.last_height = maxHeight;\n this.tx_seen = this.tx_seen.filter((val) => val.height === maxHeight || val.height <= 0);\n await this.db.setWebhookSeenTxLastHeight(this.id, this.tx_seen, this.last_height);\n }\n }\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/webhook/WebhookBch.ts?");
1718
-
1719
- /***/ }),
1720
-
1721
- /***/ "./src/webhook/WebhookSlp.ts":
1722
- /*!***********************************!*\
1723
- !*** ./src/webhook/WebhookSlp.ts ***!
1724
- \***********************************/
1725
- /***/ ((module, __webpack_exports__, __webpack_require__) => {
1726
-
1727
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"WebhookSlp\": () => (/* binding */ WebhookSlp)\n/* harmony export */ });\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/bchaddr.js */ \"../../node_modules/bchaddrjs-slp/src/bchaddr.js\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _Webhook_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Webhook.js */ \"./src/webhook/Webhook.ts\");\n/* harmony import */ var _WebhookWorker_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./WebhookWorker.js */ \"./src/webhook/WebhookWorker.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_Wif_js__WEBPACK_IMPORTED_MODULE_3__]);\n_wallet_Wif_js__WEBPACK_IMPORTED_MODULE_3__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\nclass WebhookSlp extends _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.Webhook {\n constructor(hook) {\n super(hook);\n Object.assign(this, hook);\n this.cashaddr = (0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_1__.toSlpAddress)(this.cashaddr);\n }\n async start() {\n const webhookCallback = async (rawTx) => {\n let result = false;\n if (\"_id\" in rawTx.details) {\n result = await this.slpDbHandler(rawTx);\n }\n else {\n result = await this.gsppHandler(rawTx);\n }\n if (result && this.recurrence === _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookRecurrence.once) {\n // we have to notify the worker about end of life\n await (await _WebhookWorker_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].instance()).stopHook(this);\n await this.destroy();\n }\n };\n this.callback = webhookCallback;\n this.wallet = await _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_3__.Wallet.fromSlpaddr(this.cashaddr);\n this.cancelFn = this.wallet.slp.watchTransactions(webhookCallback, this.tokenId);\n }\n async slpDbHandler(rawTx) {\n let result = false;\n const txDirection = this.type;\n const details = rawTx.details;\n if (this.type === _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.slpTransactionInOut) {\n result = await this.post({\n direction: txDirection,\n data: rawTx,\n });\n }\n else if (this.type === _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.slpTransactionIn &&\n details.out.findIndex((val) => val.e.a === this.cashaddr) > -1) {\n result = await this.post({\n direction: txDirection,\n data: rawTx,\n });\n }\n else if (this.type === _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.slpTransactionOut &&\n details.in.findIndex((val) => val.e.a === this.cashaddr) > -1) {\n result = await this.post({\n direction: txDirection,\n data: rawTx,\n });\n }\n else if (this.type === _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.slpBalance) {\n const balance = this.wallet.slp.getBalance(this.tokenId);\n result = await this.post({\n direction: txDirection,\n data: balance,\n });\n }\n return result;\n }\n async gsppHandler(rawTx) {\n let result = false;\n const txDirection = this.type;\n const details = rawTx.details;\n if (this.type === _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.slpTransactionInOut) {\n result = await this.post({\n direction: txDirection,\n data: rawTx,\n });\n }\n else if (this.type === _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.slpTransactionIn &&\n details.outputs.findIndex((val) => val === this.cashaddr) > -1) {\n result = await this.post({\n direction: txDirection,\n data: rawTx,\n });\n }\n else if (this.type === _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.slpTransactionOut &&\n details.inputs.findIndex((val) => val === this.cashaddr) > -1) {\n result = await this.post({\n direction: txDirection,\n data: rawTx,\n });\n }\n else if (this.type === _Webhook_js__WEBPACK_IMPORTED_MODULE_0__.WebhookType.slpBalance) {\n const balance = this.wallet.slp.getBalance(this.tokenId);\n result = await this.post({\n direction: txDirection,\n data: balance,\n });\n }\n return result;\n }\n async stop() {\n await this.cancelFn();\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/webhook/WebhookSlp.ts?");
1728
-
1729
- /***/ }),
1730
-
1731
- /***/ "./src/webhook/WebhookWorker.ts":
1732
- /*!**************************************!*\
1733
- !*** ./src/webhook/WebhookWorker.ts ***!
1734
- \**************************************/
1735
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1736
-
1737
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ WebhookWorker)\n/* harmony export */ });\n/* harmony import */ var _db_SqlProvider_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../db/SqlProvider.js */ \"./src/db/SqlProvider.ts\");\n\nclass WebhookWorker {\n constructor() {\n this.activeHooks = new Map();\n this.callbacks = new Map();\n this.checkInterval = undefined;\n this.db = new _db_SqlProvider_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"]();\n }\n static async instance() {\n if (!WebhookWorker._instance) {\n WebhookWorker._instance = new WebhookWorker();\n await WebhookWorker._instance.init();\n }\n return WebhookWorker._instance;\n }\n async init() {\n await this.db.init();\n await this.evictOldHooks();\n await this.pickupHooks(true);\n if (!this.checkInterval) {\n this.checkInterval = setInterval(async () => {\n await this.evictOldHooks();\n await this.pickupHooks(true);\n }, 5 * 60 * 1000);\n }\n }\n async destroy() {\n await this.stopAll();\n if (this.checkInterval) {\n clearInterval(this.checkInterval);\n this.checkInterval = undefined;\n }\n }\n async pickupHooks(start = false) {\n const hooks = await this.db.getWebhooks();\n for (const hook of hooks) {\n if (!this.activeHooks.has(hook.id)) {\n this.activeHooks.set(hook.id, hook);\n if (start) {\n await hook.start();\n }\n }\n }\n }\n async evictOldHooks() {\n const now = new Date();\n const dbHooks = await this.db.getWebhooks();\n for (const hook of dbHooks) {\n if (now >= hook.expires_at) {\n // console.debug(\"Evicting expired hook with id\", hook.id, new Date(), hook.expires_at);\n if (this.activeHooks.has(hook.id)) {\n await this.stopHook(hook);\n }\n await this.db.deleteWebhook(hook.id);\n }\n }\n }\n async registerWebhook(params, start = true) {\n const webhook = await this.db.addWebhook(params);\n if (start) {\n this.activeHooks.set(webhook.id, webhook);\n await webhook.start();\n }\n return webhook.id;\n }\n async getWebhook(id) {\n if (this.activeHooks.has(id)) {\n return this.activeHooks.get(id);\n }\n return await this.db.getWebhook(id);\n }\n async deleteWebhook(id) {\n if (this.activeHooks.has(id)) {\n await this.stopHook(this.activeHooks.get(id));\n }\n await this.db.deleteWebhook(id);\n }\n async deleteAllWebhooks() {\n await this.stopAll();\n await this.db.clearWebhooks();\n }\n async stopAll() {\n for (const [, hook] of this.activeHooks) {\n await this.stopHook(hook);\n }\n }\n async stopHook(hook) {\n if (this.activeHooks.has(hook.id)) {\n await hook.stop();\n this.activeHooks.delete(hook.id);\n }\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/webhook/WebhookWorker.ts?");
1738
-
1739
- /***/ }),
1740
-
1741
- /***/ "./src/webhook/index.ts":
1742
- /*!******************************!*\
1743
- !*** ./src/webhook/index.ts ***!
1744
- \******************************/
1745
- /***/ ((module, __webpack_exports__, __webpack_require__) => {
1746
-
1747
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"Webhook\": () => (/* reexport safe */ _Webhook_js__WEBPACK_IMPORTED_MODULE_1__.Webhook),\n/* harmony export */ \"WebhookBch\": () => (/* reexport safe */ _WebhookBch_js__WEBPACK_IMPORTED_MODULE_2__.WebhookBch),\n/* harmony export */ \"WebhookRecurrence\": () => (/* reexport safe */ _Webhook_js__WEBPACK_IMPORTED_MODULE_1__.WebhookRecurrence),\n/* harmony export */ \"WebhookSlp\": () => (/* reexport safe */ _WebhookSlp_js__WEBPACK_IMPORTED_MODULE_3__.WebhookSlp),\n/* harmony export */ \"WebhookType\": () => (/* reexport safe */ _Webhook_js__WEBPACK_IMPORTED_MODULE_1__.WebhookType),\n/* harmony export */ \"WebhookWorker\": () => (/* reexport safe */ _WebhookWorker_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"])\n/* harmony export */ });\n/* harmony import */ var _WebhookWorker_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./WebhookWorker.js */ \"./src/webhook/WebhookWorker.ts\");\n/* harmony import */ var _Webhook_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Webhook.js */ \"./src/webhook/Webhook.ts\");\n/* harmony import */ var _WebhookBch_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./WebhookBch.js */ \"./src/webhook/WebhookBch.ts\");\n/* harmony import */ var _WebhookSlp_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./WebhookSlp.js */ \"./src/webhook/WebhookSlp.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_WebhookBch_js__WEBPACK_IMPORTED_MODULE_2__, _WebhookSlp_js__WEBPACK_IMPORTED_MODULE_3__]);\n([_WebhookBch_js__WEBPACK_IMPORTED_MODULE_2__, _WebhookSlp_js__WEBPACK_IMPORTED_MODULE_3__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/webhook/index.ts?");
1748
-
1749
- /***/ }),
1750
-
1751
1471
  /***/ "../../node_modules/util-deprecate/browser.js":
1752
1472
  /*!****************************************************!*\
1753
1473
  !*** ../../node_modules/util-deprecate/browser.js ***!
@@ -1808,33 +1528,13 @@ eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/util_(ignored)?");
1808
1528
 
1809
1529
  /***/ }),
1810
1530
 
1811
- /***/ "?a3a2":
1812
- /*!************************************!*\
1813
- !*** parse-database-url (ignored) ***!
1814
- \************************************/
1815
- /***/ (() => {
1816
-
1817
- eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/parse-database-url_(ignored)?");
1818
-
1819
- /***/ }),
1820
-
1821
- /***/ "?0b82":
1822
- /*!********************!*\
1823
- !*** pg (ignored) ***!
1824
- \********************/
1825
- /***/ (() => {
1826
-
1827
- eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/pg_(ignored)?");
1828
-
1829
- /***/ }),
1830
-
1831
- /***/ "?28a0":
1832
- /*!***************************!*\
1833
- !*** pg-format (ignored) ***!
1834
- \***************************/
1531
+ /***/ "?7652":
1532
+ /*!**********************************!*\
1533
+ !*** ./SqlProvider.js (ignored) ***!
1534
+ \**********************************/
1835
1535
  /***/ (() => {
1836
1536
 
1837
- eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/pg-format_(ignored)?");
1537
+ eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/./SqlProvider.js_(ignored)?");
1838
1538
 
1839
1539
  /***/ }),
1840
1540
 
@@ -1858,13 +1558,13 @@ eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/crypto_(ignored)?");
1858
1558
 
1859
1559
  /***/ }),
1860
1560
 
1861
- /***/ "?ec4c":
1862
- /*!*****************************!*\
1863
- !*** eventsource (ignored) ***!
1864
- \*****************************/
1561
+ /***/ "?6f8b":
1562
+ /*!************************************!*\
1563
+ !*** ./webhook/index.js (ignored) ***!
1564
+ \************************************/
1865
1565
  /***/ (() => {
1866
1566
 
1867
- eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/eventsource_(ignored)?");
1567
+ eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/./webhook/index.js_(ignored)?");
1868
1568
 
1869
1569
  /***/ }),
1870
1570
 
@@ -2194,7 +1894,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
2194
1894
  \**********************************************************************/
2195
1895
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2196
1896
 
2197
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"bigIntToBinUint256BEClamped\": () => (/* binding */ bigIntToBinUint256BEClamped),\n/* harmony export */ \"bigIntToBinUint64LE\": () => (/* binding */ bigIntToBinUint64LE),\n/* harmony export */ \"bigIntToCompactSize\": () => (/* binding */ bigIntToCompactSize),\n/* harmony export */ \"binToBigIntUint256BE\": () => (/* binding */ binToBigIntUint256BE),\n/* harmony export */ \"binToBigIntUint64LE\": () => (/* binding */ binToBigIntUint64LE),\n/* harmony export */ \"binToNumberUint16LE\": () => (/* binding */ binToNumberUint16LE),\n/* harmony export */ \"binToNumberUint32LE\": () => (/* binding */ binToNumberUint32LE),\n/* harmony export */ \"binToValueSatoshis\": () => (/* binding */ binToValueSatoshis),\n/* harmony export */ \"int32UnsignedToSigned\": () => (/* binding */ int32UnsignedToSigned),\n/* harmony export */ \"numberToBinUint16LE\": () => (/* binding */ numberToBinUint16LE),\n/* harmony export */ \"numberToBinUint32BE\": () => (/* binding */ numberToBinUint32BE),\n/* harmony export */ \"numberToBinUint32LE\": () => (/* binding */ numberToBinUint32LE),\n/* harmony export */ \"readCompactSizeMinimal\": () => (/* binding */ readCompactSizeMinimal),\n/* harmony export */ \"valueSatoshisToBin\": () => (/* binding */ valueSatoshisToBin)\n/* harmony export */ });\n/* unused harmony exports numberToBinUintLE, binToFixedLength, numberToBinUint16LEClamped, numberToBinUint32LEClamped, numberToBinInt16LE, numberToBinInt32LE, binToNumberInt16LE, binToNumberInt32LE, numberToBinUint16BE, bigIntToBinUintLE, bigIntToBinUint64LEClamped, numberToBinInt32TwosCompliment, binToNumberUintLE, binToBigIntUintBE, binToBigIntUintLE, compactSizePrefixToSize, CompactSizeError, readCompactSize, compactSizeToBigInt, int32SignedToUnsigned */\n/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./error.js */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n\n/**\n * Encode a positive integer as a little-endian Uint8Array. For values exceeding\n * `Number.MAX_SAFE_INTEGER` (`9007199254740991`), use `bigIntToBinUintLE`.\n * Negative values will return the same result as `0`.\n *\n * @param value - the number to encode\n */\nconst numberToBinUintLE = (value) => {\n const baseUint8Array = 256;\n const result = [];\n // eslint-disable-next-line functional/no-let\n let remaining = value;\n // eslint-disable-next-line functional/no-loop-statement\n while (remaining >= baseUint8Array) {\n // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data\n result.push(remaining % baseUint8Array);\n // eslint-disable-next-line functional/no-expression-statement\n remaining = Math.floor(remaining / baseUint8Array);\n }\n // eslint-disable-next-line functional/no-conditional-statement, functional/no-expression-statement, functional/immutable-data\n if (remaining > 0)\n result.push(remaining);\n return Uint8Array.from(result);\n};\n/**\n * Fill a new Uint8Array of a specific byte-length with the contents of a given\n * Uint8Array, truncating or padding the Uint8Array with zeros.\n *\n * @param bin - the Uint8Array to resize\n * @param bytes - the desired byte-length\n */\nconst binToFixedLength = (bin, bytes) => {\n const fixedBytes = new Uint8Array(bytes);\n const maxValue = 255;\n // eslint-disable-next-line functional/no-expression-statement\n bin.length > bytes ? fixedBytes.fill(maxValue) : fixedBytes.set(bin);\n return fixedBytes;\n};\n/**\n * Encode a positive integer as a 2-byte Uint16LE Uint8Array, clamping the\n * results – values exceeding `0xffff` (`65535`) return the same result as\n * `0xffff`, negative values will return the same result as `0`.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint16LEClamped = (value) => {\n const uint16 = 2;\n return binToFixedLength(numberToBinUintLE(value), uint16);\n};\n/**\n * Encode a positive integer as a 4-byte Uint32LE Uint8Array, clamping the\n * results – values exceeding `0xffffffff` (`4294967295`) return the same result\n * as `0xffffffff`, negative values will return the same result as `0`.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint32LEClamped = (value) => {\n const uint32 = 4;\n return binToFixedLength(numberToBinUintLE(value), uint32);\n};\n/**\n * Encode a positive integer as a 2-byte Uint16LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0` to `0xffff` (`65535`). If applicable, applications should handle such\n * cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint16LE = (value) => {\n const uint16Length = 2;\n const bin = new Uint8Array(uint16Length);\n const writeAsLittleEndian = true;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setUint16(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Encode an integer as a 2-byte Int16LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0x0000` to `0xffff` (`65535`). If applicable, applications should handle\n * such cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinInt16LE = (value) => {\n const int16Length = 2;\n const bin = new Uint8Array(int16Length);\n const writeAsLittleEndian = true;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setInt16(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Encode an integer as a 4-byte Uint32LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0x00000000` to `0xffffffff` (`4294967295`). If applicable, applications\n * should handle such cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinInt32LE = (value) => {\n const int32Length = 4;\n const bin = new Uint8Array(int32Length);\n const writeAsLittleEndian = true;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setInt32(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Decode a 2-byte Int16LE Uint8Array into a number.\n *\n * Throws if `bin` is shorter than 2 bytes.\n *\n * @param bin - the Uint8Array to decode\n */\nconst binToNumberInt16LE = (bin) => {\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n const readAsLittleEndian = true;\n return view.getInt16(0, readAsLittleEndian);\n};\n/**\n * Decode a 4-byte Int32LE Uint8Array into a number.\n *\n * Throws if `bin` is shorter than 4 bytes.\n *\n * @param bin - the Uint8Array to decode\n */\nconst binToNumberInt32LE = (bin) => {\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n const readAsLittleEndian = true;\n return view.getInt32(0, readAsLittleEndian);\n};\n/**\n * Encode a positive integer as a 2-byte Uint16LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0` to `0xffff` (`65535`). If applicable, applications should handle such\n * cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint16BE = (value) => {\n const uint16Length = 2;\n const bin = new Uint8Array(uint16Length);\n const writeAsLittleEndian = false;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setUint16(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Encode a positive number as a 4-byte Uint32LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0` to `0xffffffff` (`4294967295`). If applicable, applications should handle\n * such cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint32LE = (value) => {\n const uint32Length = 4;\n const bin = new Uint8Array(uint32Length);\n const writeAsLittleEndian = true;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setUint32(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Encode a positive number as a 4-byte Uint32BE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0` to `0xffffffff` (`4294967295`). If applicable, applications should handle\n * such cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint32BE = (value) => {\n const uint32Length = 4;\n const bin = new Uint8Array(uint32Length);\n const writeAsLittleEndian = false;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setUint32(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Encode a positive BigInt as little-endian Uint8Array. Negative values will\n * return the same result as `0`.\n *\n * @param value - the number to encode\n */\nconst bigIntToBinUintLE = (value) => {\n const baseUint8Array = 256;\n const base = BigInt(baseUint8Array);\n const result = [];\n // eslint-disable-next-line functional/no-let\n let remaining = value;\n // eslint-disable-next-line functional/no-loop-statement\n while (remaining >= base) {\n // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data\n result.push(Number(remaining % base));\n // eslint-disable-next-line functional/no-expression-statement\n remaining /= base;\n }\n // eslint-disable-next-line functional/no-conditional-statement, functional/no-expression-statement, functional/immutable-data\n if (remaining > 0n)\n result.push(Number(remaining));\n return Uint8Array.from(result.length > 0 ? result : [0]);\n};\n/**\n * Encode a positive BigInt as an 8-byte Uint64LE Uint8Array, clamping the\n * results – values exceeding `0xffff_ffff_ffff_ffff` (`18446744073709551615`)\n * return the same result as `0xffff_ffff_ffff_ffff`, negative values return the\n * same result as `0`.\n *\n * @param value - the number to encode\n */\nconst bigIntToBinUint64LEClamped = (value) => {\n const uint64 = 8;\n return binToFixedLength(bigIntToBinUintLE(value), uint64);\n};\n/**\n * Encode a positive BigInt as an 8-byte Uint64LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0` to `0xffff_ffff_ffff_ffff` (`18446744073709551615`).\n *\n * @param value - the number to encode\n */\nconst bigIntToBinUint64LE = (value) => {\n const uint64LengthInBits = 64;\n const valueAsUint64 = BigInt.asUintN(uint64LengthInBits, value);\n const fixedLengthBin = bigIntToBinUint64LEClamped(valueAsUint64);\n return fixedLengthBin;\n};\n/**\n * Encode an integer as a 4-byte, little-endian Uint8Array using the number's\n * two's compliment representation (the format used by JavaScript's bitwise\n * operators).\n *\n * @remarks\n * The C++ bitcoin implementations sometimes represent short vectors using\n * signed 32-bit integers (e.g. `sighashType`). This method can be used to test\n * compatibility with those implementations.\n *\n * @param value - the number to encode\n */\nconst numberToBinInt32TwosCompliment = (value) => {\n const bytes = 4;\n const bitsInAByte = 8;\n const bin = new Uint8Array(bytes);\n // eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus\n for (let index = 0; index < bytes; index++) {\n // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data\n bin[index] = value;\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, no-param-reassign\n value >>>= bitsInAByte;\n }\n return bin;\n};\n/**\n * Decode a little-endian Uint8Array of any length into a number. For numbers\n * larger than `Number.MAX_SAFE_INTEGER` (`9007199254740991`), use\n * `binToBigIntUintLE`.\n *\n * The `bytes` parameter can be set to constrain the expected length (default:\n * `bin.length`). This method throws if `bin.length` is not equal to `bytes`.\n *\n * @privateRemarks\n * We avoid a bitwise strategy here because JavaScript uses 32-bit signed\n * integers for bitwise math, so larger numbers are converted incorrectly. E.g.\n * `2147483648 << 8` is `0`, while `2147483648n << 8n` is `549755813888n`.\n *\n * @param bin - the Uint8Array to decode\n * @param bytes - the number of bytes to read (default: `bin.length`)\n */\nconst binToNumberUintLE = (bin, bytes = bin.length) => {\n const base = 2;\n const bitsInAByte = 8;\n if (bin.length !== bytes) {\n // eslint-disable-next-line functional/no-throw-statement\n throw new TypeError(`Bin length must be ${bytes}.`);\n }\n return new Uint8Array(bin.buffer, bin.byteOffset, bin.length).reduce((accumulated, byte, i) => accumulated + byte * base ** (bitsInAByte * i), 0);\n};\n/**\n * Decode a 2-byte Uint16LE Uint8Array into a number.\n *\n * Throws if `bin` is shorter than 2 bytes.\n *\n * @param bin - the Uint8Array to decode\n */\nconst binToNumberUint16LE = (bin) => {\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n const readAsLittleEndian = true;\n return view.getUint16(0, readAsLittleEndian);\n};\n/**\n * Decode a 4-byte Uint32LE Uint8Array into a number.\n *\n * Throws if `bin` is shorter than 4 bytes.\n *\n * @param bin - the Uint8Array to decode\n */\nconst binToNumberUint32LE = (bin) => {\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n const readAsLittleEndian = true;\n return view.getUint32(0, readAsLittleEndian);\n};\n/**\n * Decode a big-endian Uint8Array of any length into a BigInt. If starting from\n * a hex value, consider using the BigInt constructor instead:\n * ```\n * BigInt(`0x${hex}`)\n * ```\n *\n * The `bytes` parameter can be set to constrain the expected length (default:\n * `bin.length`). This method throws if `bin.length` is not equal to `bytes`.\n *\n * @param bin - the Uint8Array to decode\n * @param bytes - the number of bytes to read (default: `bin.length`)\n */\nconst binToBigIntUintBE = (bin, bytes = bin.length) => {\n const bitsInAByte = 8;\n const shift = BigInt(bitsInAByte);\n if (bin.length !== bytes) {\n // eslint-disable-next-line functional/no-throw-statement\n throw new TypeError(`Bin length must be ${bytes}.`);\n }\n return new Uint8Array(bin.buffer, bin.byteOffset, bin.length).reduce(\n // eslint-disable-next-line no-bitwise\n (accumulated, byte) => (accumulated << shift) | BigInt(byte), 0n);\n};\n/**\n * Decode an unsigned, 32-byte big-endian Uint8Array into a BigInt. This can be\n * used to decode Uint8Array-encoded cryptographic primitives like private\n * keys, public keys, curve parameters, and signature points.\n *\n * If starting from a hex value, consider using the BigInt constructor instead:\n * ```\n * BigInt(`0x${hex}`)\n * ```\n * @param bin - the Uint8Array to decode\n */\nconst binToBigIntUint256BE = (bin) => {\n const uint256Bytes = 32;\n return binToBigIntUintBE(bin, uint256Bytes);\n};\n/**\n * Encode a positive BigInt into an unsigned 32-byte big-endian Uint8Array. This\n * can be used to encoded numbers for cryptographic primitives like private\n * keys, public keys, curve parameters, and signature points.\n *\n * Negative values will return the same result as `0`, values higher than\n * 2^256-1 will return the maximum expressible unsigned 256-bit value\n * (`0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`).\n *\n * @param value - the BigInt to encode\n */\nconst bigIntToBinUint256BEClamped = (value) => {\n const uint256Bytes = 32;\n return binToFixedLength(bigIntToBinUintLE(value), uint256Bytes).reverse();\n};\n/**\n * Decode a little-endian Uint8Array of any length into a BigInt.\n *\n * The `bytes` parameter can be set to constrain the expected length (default:\n * `bin.length`). This method throws if `bin.length` is not equal to `bytes`.\n *\n * @param bin - the Uint8Array to decode\n * @param bytes - the number of bytes to read (default: `bin.length`)\n */\nconst binToBigIntUintLE = (bin, bytes = bin.length) => {\n const bitsInAByte = 8;\n if (bin.length !== bytes) {\n // eslint-disable-next-line functional/no-throw-statement\n throw new TypeError(`Bin length must be ${bytes}.`);\n }\n return new Uint8Array(bin.buffer, bin.byteOffset, bin.length).reduceRight(\n // eslint-disable-next-line no-bitwise\n (accumulated, byte) => (accumulated << BigInt(bitsInAByte)) | BigInt(byte), 0n);\n};\n/**\n * Decode an 8-byte Uint64LE Uint8Array into a BigInt.\n *\n * Throws if `bin` is shorter than 8 bytes.\n *\n * @param bin - the Uint8Array to decode\n */\nconst binToBigIntUint64LE = (bin) => {\n const uint64LengthInBytes = 8;\n const truncatedBin = bin.length > uint64LengthInBytes ? bin.slice(0, uint64LengthInBytes) : bin;\n return binToBigIntUintLE(truncatedBin, uint64LengthInBytes);\n};\n/**\n * Decode an {@link Output.valueSatoshis} into a `BigInt`. This is an alias for\n * {@link binToBigIntUint64LE}.\n *\n * Throws if the provided value is shorter than 8 bytes.\n */\nconst binToValueSatoshis = binToBigIntUint64LE;\n/**\n * Encode a `BigInt` into an {@link Output.valueSatoshis}. This is an alias for\n * {@link bigIntToBinUint64LE}.\n *\n * This method will return an incorrect result for values outside of the range 0\n * to 0xffff_ffff_ffff_ffff (`18446744073709551615`).\n */\nconst valueSatoshisToBin = bigIntToBinUint64LE;\n/**\n * Get the expected byte length of a CompactSize given a first byte.\n *\n * @param firstByte - the first byte of the CompactSize\n */\nconst compactSizePrefixToSize = (firstByte) => {\n switch (firstByte) {\n case 253 /* CompactSize.uint16Prefix */:\n return 2 /* CompactSize.uint16 */ + 1;\n case 254 /* CompactSize.uint32Prefix */:\n return 4 /* CompactSize.uint32 */ + 1;\n case 255 /* CompactSize.uint64Prefix */:\n return 8 /* CompactSize.uint64 */ + 1;\n default:\n return 1 /* CompactSize.uint8 */;\n }\n};\nvar CompactSizeError;\n(function (CompactSizeError) {\n CompactSizeError[\"noPrefix\"] = \"Error reading CompactSize: requires at least one byte.\";\n CompactSizeError[\"insufficientBytes\"] = \"Error reading CompactSize: insufficient bytes.\";\n CompactSizeError[\"nonMinimal\"] = \"Error reading CompactSize: CompactSize is not minimally encoded.\";\n CompactSizeError[\"excessiveBytes\"] = \"Error decoding CompactSize: unexpected bytes after CompactSize.\";\n})(CompactSizeError || (CompactSizeError = {}));\n/**\n * Read a non-minimally-encoded `CompactSize` (see {@link bigIntToCompactSize})\n * from the provided {@link ReadPosition}, returning either an error message (as\n * a string) or an object containing the value and the\n * next {@link ReadPosition}.\n *\n * Rather than this function, most applications should\n * use {@link readCompactSizeMinimal}.\n *\n * @param position - the {@link ReadPosition} at which to start reading the\n * `CompactSize`\n */\nconst readCompactSize = (position) => {\n const { bin, index } = position;\n const prefix = bin[index];\n if (prefix === undefined) {\n return (0,_error_js__WEBPACK_IMPORTED_MODULE_0__.formatError)(CompactSizeError.noPrefix);\n }\n const bytes = compactSizePrefixToSize(prefix);\n if (bin.length - index < bytes) {\n return (0,_error_js__WEBPACK_IMPORTED_MODULE_0__.formatError)(CompactSizeError.insufficientBytes, `CompactSize prefix ${prefix} requires at least ${bytes} bytes. Remaining bytes: ${bin.length - index}`);\n }\n const hasPrefix = bytes !== 1;\n const contents = hasPrefix\n ? bin.subarray(index + 1, index + bytes)\n : bin.subarray(index, index + bytes);\n return {\n position: { bin, index: index + bytes },\n result: binToBigIntUintLE(contents),\n };\n};\n/**\n * Encode a positive BigInt as a `CompactSize` (Satoshi's variable-length,\n * positive integer format).\n *\n * Note: the maximum value of a CompactSize is `0xffff_ffff_ffff_ffff`\n * (`18446744073709551615`). This method will return an incorrect result for\n * values outside of the range `0` to `0xffff_ffff_ffff_ffff`. If applicable,\n * applications should handle such cases prior to calling this method.\n *\n * @param value - the BigInt to encode (must be no larger than\n * `0xffff_ffff_ffff_ffff`)\n */\nconst bigIntToCompactSize = (value) => value <= BigInt(252 /* CompactSize.uint8MaxValue */)\n ? Uint8Array.of(Number(value))\n : value <= BigInt(65535 /* CompactSize.uint16MaxValue */)\n ? Uint8Array.from([\n 253 /* CompactSize.uint16Prefix */,\n ...numberToBinUint16LE(Number(value)),\n ])\n : value <= BigInt(4294967295 /* CompactSize.uint32MaxValue */)\n ? Uint8Array.from([\n 254 /* CompactSize.uint32Prefix */,\n ...numberToBinUint32LE(Number(value)),\n ])\n : Uint8Array.from([\n 255 /* CompactSize.uint64Prefix */,\n ...bigIntToBinUint64LE(value),\n ]);\n/**\n * Read a minimally-encoded `CompactSize` from the provided\n * {@link ReadPosition}, returning either an error message (as a string) or an\n * object containing the value and the next {@link ReadPosition}.\n *\n * @param position - the {@link ReadPosition} at which to start reading the\n * `CompactSize`\n */\nconst readCompactSizeMinimal = (position) => {\n const read = readCompactSize(position);\n if (typeof read === 'string') {\n return read;\n }\n const readLength = read.position.index - position.index;\n const canonicalEncoding = bigIntToCompactSize(read.result);\n if (readLength !== canonicalEncoding.length) {\n return (0,_error_js__WEBPACK_IMPORTED_MODULE_0__.formatError)(CompactSizeError.nonMinimal, `Value: ${read.result.toString()}, encoded length: ${readLength}, canonical length: ${canonicalEncoding.length}`);\n }\n return read;\n};\n/**\n * Decode a minimally-encoded `CompactSize` (Satoshi's variable-length, positive\n * integer format) from a Uint8Array, returning the value as a BigInt. This\n * function returns an error if the entire input is not consumed – to read a\n * `CompactSize` from a position within a larger `Uint8Array`,\n * use {@link readCompactSizeMinimal} or {@link readCompactSize}.\n *\n * @param bin - the Uint8Array from which to read the CompactSize\n */\nconst compactSizeToBigInt = (bin) => {\n const read = readCompactSizeMinimal({ bin, index: 0 });\n if (typeof read === 'string') {\n return read;\n }\n if (read.position.index !== bin.length) {\n return (0,_error_js__WEBPACK_IMPORTED_MODULE_0__.formatError)(CompactSizeError.excessiveBytes, `CompactSize ends at index ${read.position.index}, but input includes ${bin.length} bytes.`);\n }\n return read.result;\n};\n/**\n * Convert a signed integer into it's two's compliment unsigned equivalent, e.g.\n * `0b11111111111111111111111111111110` is `-2` as a signed integer or\n * `4294967294` as an unsigned integer.\n */\nconst int32SignedToUnsigned = (int32) => \n// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\nUint32Array.from(Int32Array.of(int32))[0];\n/**\n * Convert an unsigned integer into it's two's compliment signed equivalent,\n * e.g. `0b11111111111111111111111111111110` is `4294967294` as an unsigned\n * integer or `-2` as a signed integer.\n */\nconst int32UnsignedToSigned = (int32) => \n// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\nInt32Array.from(Uint32Array.of(int32))[0];\n//# sourceMappingURL=number.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@bitauth/libauth/build/lib/format/number.js?");
1897
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"bigIntToBinUint256BEClamped\": () => (/* binding */ bigIntToBinUint256BEClamped),\n/* harmony export */ \"bigIntToCompactSize\": () => (/* binding */ bigIntToCompactSize),\n/* harmony export */ \"binToBigIntUint256BE\": () => (/* binding */ binToBigIntUint256BE),\n/* harmony export */ \"binToBigIntUint64LE\": () => (/* binding */ binToBigIntUint64LE),\n/* harmony export */ \"binToNumberUint16LE\": () => (/* binding */ binToNumberUint16LE),\n/* harmony export */ \"binToNumberUint32LE\": () => (/* binding */ binToNumberUint32LE),\n/* harmony export */ \"binToValueSatoshis\": () => (/* binding */ binToValueSatoshis),\n/* harmony export */ \"int32UnsignedToSigned\": () => (/* binding */ int32UnsignedToSigned),\n/* harmony export */ \"numberToBinUint16LE\": () => (/* binding */ numberToBinUint16LE),\n/* harmony export */ \"numberToBinUint32BE\": () => (/* binding */ numberToBinUint32BE),\n/* harmony export */ \"numberToBinUint32LE\": () => (/* binding */ numberToBinUint32LE),\n/* harmony export */ \"readCompactSizeMinimal\": () => (/* binding */ readCompactSizeMinimal),\n/* harmony export */ \"valueSatoshisToBin\": () => (/* binding */ valueSatoshisToBin)\n/* harmony export */ });\n/* unused harmony exports numberToBinUintLE, binToFixedLength, numberToBinUint16LEClamped, numberToBinUint32LEClamped, numberToBinInt16LE, numberToBinInt32LE, binToNumberInt16LE, binToNumberInt32LE, numberToBinUint16BE, bigIntToBinUintLE, bigIntToBinUint64LEClamped, bigIntToBinUint64LE, numberToBinInt32TwosCompliment, binToNumberUintLE, binToBigIntUintBE, binToBigIntUintLE, compactSizePrefixToSize, CompactSizeError, readCompactSize, compactSizeToBigInt, int32SignedToUnsigned */\n/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./error.js */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n\n/**\n * Encode a positive integer as a little-endian Uint8Array. For values exceeding\n * `Number.MAX_SAFE_INTEGER` (`9007199254740991`), use `bigIntToBinUintLE`.\n * Negative values will return the same result as `0`.\n *\n * @param value - the number to encode\n */\nconst numberToBinUintLE = (value) => {\n const baseUint8Array = 256;\n const result = [];\n // eslint-disable-next-line functional/no-let\n let remaining = value;\n // eslint-disable-next-line functional/no-loop-statement\n while (remaining >= baseUint8Array) {\n // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data\n result.push(remaining % baseUint8Array);\n // eslint-disable-next-line functional/no-expression-statement\n remaining = Math.floor(remaining / baseUint8Array);\n }\n // eslint-disable-next-line functional/no-conditional-statement, functional/no-expression-statement, functional/immutable-data\n if (remaining > 0)\n result.push(remaining);\n return Uint8Array.from(result);\n};\n/**\n * Fill a new Uint8Array of a specific byte-length with the contents of a given\n * Uint8Array, truncating or padding the Uint8Array with zeros.\n *\n * @param bin - the Uint8Array to resize\n * @param bytes - the desired byte-length\n */\nconst binToFixedLength = (bin, bytes) => {\n const fixedBytes = new Uint8Array(bytes);\n const maxValue = 255;\n // eslint-disable-next-line functional/no-expression-statement\n bin.length > bytes ? fixedBytes.fill(maxValue) : fixedBytes.set(bin);\n return fixedBytes;\n};\n/**\n * Encode a positive integer as a 2-byte Uint16LE Uint8Array, clamping the\n * results – values exceeding `0xffff` (`65535`) return the same result as\n * `0xffff`, negative values will return the same result as `0`.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint16LEClamped = (value) => {\n const uint16 = 2;\n return binToFixedLength(numberToBinUintLE(value), uint16);\n};\n/**\n * Encode a positive integer as a 4-byte Uint32LE Uint8Array, clamping the\n * results – values exceeding `0xffffffff` (`4294967295`) return the same result\n * as `0xffffffff`, negative values will return the same result as `0`.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint32LEClamped = (value) => {\n const uint32 = 4;\n return binToFixedLength(numberToBinUintLE(value), uint32);\n};\n/**\n * Encode a positive integer as a 2-byte Uint16LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0` to `0xffff` (`65535`). If applicable, applications should handle such\n * cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint16LE = (value) => {\n const uint16Length = 2;\n const bin = new Uint8Array(uint16Length);\n const writeAsLittleEndian = true;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setUint16(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Encode an integer as a 2-byte Int16LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0x0000` to `0xffff` (`65535`). If applicable, applications should handle\n * such cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinInt16LE = (value) => {\n const int16Length = 2;\n const bin = new Uint8Array(int16Length);\n const writeAsLittleEndian = true;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setInt16(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Encode an integer as a 4-byte Uint32LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0x00000000` to `0xffffffff` (`4294967295`). If applicable, applications\n * should handle such cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinInt32LE = (value) => {\n const int32Length = 4;\n const bin = new Uint8Array(int32Length);\n const writeAsLittleEndian = true;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setInt32(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Decode a 2-byte Int16LE Uint8Array into a number.\n *\n * Throws if `bin` is shorter than 2 bytes.\n *\n * @param bin - the Uint8Array to decode\n */\nconst binToNumberInt16LE = (bin) => {\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n const readAsLittleEndian = true;\n return view.getInt16(0, readAsLittleEndian);\n};\n/**\n * Decode a 4-byte Int32LE Uint8Array into a number.\n *\n * Throws if `bin` is shorter than 4 bytes.\n *\n * @param bin - the Uint8Array to decode\n */\nconst binToNumberInt32LE = (bin) => {\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n const readAsLittleEndian = true;\n return view.getInt32(0, readAsLittleEndian);\n};\n/**\n * Encode a positive integer as a 2-byte Uint16LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0` to `0xffff` (`65535`). If applicable, applications should handle such\n * cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint16BE = (value) => {\n const uint16Length = 2;\n const bin = new Uint8Array(uint16Length);\n const writeAsLittleEndian = false;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setUint16(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Encode a positive number as a 4-byte Uint32LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0` to `0xffffffff` (`4294967295`). If applicable, applications should handle\n * such cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint32LE = (value) => {\n const uint32Length = 4;\n const bin = new Uint8Array(uint32Length);\n const writeAsLittleEndian = true;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setUint32(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Encode a positive number as a 4-byte Uint32BE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0` to `0xffffffff` (`4294967295`). If applicable, applications should handle\n * such cases prior to calling this method.\n *\n * @param value - the number to encode\n */\nconst numberToBinUint32BE = (value) => {\n const uint32Length = 4;\n const bin = new Uint8Array(uint32Length);\n const writeAsLittleEndian = false;\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n // eslint-disable-next-line functional/no-expression-statement\n view.setUint32(0, value, writeAsLittleEndian);\n return bin;\n};\n/**\n * Encode a positive BigInt as little-endian Uint8Array. Negative values will\n * return the same result as `0`.\n *\n * @param value - the number to encode\n */\nconst bigIntToBinUintLE = (value) => {\n const baseUint8Array = 256;\n const base = BigInt(baseUint8Array);\n const result = [];\n // eslint-disable-next-line functional/no-let\n let remaining = value;\n // eslint-disable-next-line functional/no-loop-statement\n while (remaining >= base) {\n // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data\n result.push(Number(remaining % base));\n // eslint-disable-next-line functional/no-expression-statement\n remaining /= base;\n }\n // eslint-disable-next-line functional/no-conditional-statement, functional/no-expression-statement, functional/immutable-data\n if (remaining > 0n)\n result.push(Number(remaining));\n return Uint8Array.from(result.length > 0 ? result : [0]);\n};\n/**\n * Encode a positive BigInt as an 8-byte Uint64LE Uint8Array, clamping the\n * results – values exceeding `0xffff_ffff_ffff_ffff` (`18446744073709551615`)\n * return the same result as `0xffff_ffff_ffff_ffff`, negative values return the\n * same result as `0`.\n *\n * @param value - the number to encode\n */\nconst bigIntToBinUint64LEClamped = (value) => {\n const uint64 = 8;\n return binToFixedLength(bigIntToBinUintLE(value), uint64);\n};\n/**\n * Encode a positive BigInt as an 8-byte Uint64LE Uint8Array.\n *\n * This method will return an incorrect result for values outside of the range\n * `0` to `0xffff_ffff_ffff_ffff` (`18446744073709551615`).\n *\n * @param value - the number to encode\n */\nconst bigIntToBinUint64LE = (value) => {\n const uint64LengthInBits = 64;\n const valueAsUint64 = BigInt.asUintN(uint64LengthInBits, value);\n const fixedLengthBin = bigIntToBinUint64LEClamped(valueAsUint64);\n return fixedLengthBin;\n};\n/**\n * Encode an integer as a 4-byte, little-endian Uint8Array using the number's\n * two's compliment representation (the format used by JavaScript's bitwise\n * operators).\n *\n * @remarks\n * The C++ bitcoin implementations sometimes represent short vectors using\n * signed 32-bit integers (e.g. `sighashType`). This method can be used to test\n * compatibility with those implementations.\n *\n * @param value - the number to encode\n */\nconst numberToBinInt32TwosCompliment = (value) => {\n const bytes = 4;\n const bitsInAByte = 8;\n const bin = new Uint8Array(bytes);\n // eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus\n for (let index = 0; index < bytes; index++) {\n // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data\n bin[index] = value;\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, no-param-reassign\n value >>>= bitsInAByte;\n }\n return bin;\n};\n/**\n * Decode a little-endian Uint8Array of any length into a number. For numbers\n * larger than `Number.MAX_SAFE_INTEGER` (`9007199254740991`), use\n * `binToBigIntUintLE`.\n *\n * The `bytes` parameter can be set to constrain the expected length (default:\n * `bin.length`). This method throws if `bin.length` is not equal to `bytes`.\n *\n * @privateRemarks\n * We avoid a bitwise strategy here because JavaScript uses 32-bit signed\n * integers for bitwise math, so larger numbers are converted incorrectly. E.g.\n * `2147483648 << 8` is `0`, while `2147483648n << 8n` is `549755813888n`.\n *\n * @param bin - the Uint8Array to decode\n * @param bytes - the number of bytes to read (default: `bin.length`)\n */\nconst binToNumberUintLE = (bin, bytes = bin.length) => {\n const base = 2;\n const bitsInAByte = 8;\n if (bin.length !== bytes) {\n // eslint-disable-next-line functional/no-throw-statement\n throw new TypeError(`Bin length must be ${bytes}.`);\n }\n return new Uint8Array(bin.buffer, bin.byteOffset, bin.length).reduce((accumulated, byte, i) => accumulated + byte * base ** (bitsInAByte * i), 0);\n};\n/**\n * Decode a 2-byte Uint16LE Uint8Array into a number.\n *\n * Throws if `bin` is shorter than 2 bytes.\n *\n * @param bin - the Uint8Array to decode\n */\nconst binToNumberUint16LE = (bin) => {\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n const readAsLittleEndian = true;\n return view.getUint16(0, readAsLittleEndian);\n};\n/**\n * Decode a 4-byte Uint32LE Uint8Array into a number.\n *\n * Throws if `bin` is shorter than 4 bytes.\n *\n * @param bin - the Uint8Array to decode\n */\nconst binToNumberUint32LE = (bin) => {\n const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);\n const readAsLittleEndian = true;\n return view.getUint32(0, readAsLittleEndian);\n};\n/**\n * Decode a big-endian Uint8Array of any length into a BigInt. If starting from\n * a hex value, consider using the BigInt constructor instead:\n * ```\n * BigInt(`0x${hex}`)\n * ```\n *\n * The `bytes` parameter can be set to constrain the expected length (default:\n * `bin.length`). This method throws if `bin.length` is not equal to `bytes`.\n *\n * @param bin - the Uint8Array to decode\n * @param bytes - the number of bytes to read (default: `bin.length`)\n */\nconst binToBigIntUintBE = (bin, bytes = bin.length) => {\n const bitsInAByte = 8;\n const shift = BigInt(bitsInAByte);\n if (bin.length !== bytes) {\n // eslint-disable-next-line functional/no-throw-statement\n throw new TypeError(`Bin length must be ${bytes}.`);\n }\n return new Uint8Array(bin.buffer, bin.byteOffset, bin.length).reduce(\n // eslint-disable-next-line no-bitwise\n (accumulated, byte) => (accumulated << shift) | BigInt(byte), 0n);\n};\n/**\n * Decode an unsigned, 32-byte big-endian Uint8Array into a BigInt. This can be\n * used to decode Uint8Array-encoded cryptographic primitives like private\n * keys, public keys, curve parameters, and signature points.\n *\n * If starting from a hex value, consider using the BigInt constructor instead:\n * ```\n * BigInt(`0x${hex}`)\n * ```\n * @param bin - the Uint8Array to decode\n */\nconst binToBigIntUint256BE = (bin) => {\n const uint256Bytes = 32;\n return binToBigIntUintBE(bin, uint256Bytes);\n};\n/**\n * Encode a positive BigInt into an unsigned 32-byte big-endian Uint8Array. This\n * can be used to encoded numbers for cryptographic primitives like private\n * keys, public keys, curve parameters, and signature points.\n *\n * Negative values will return the same result as `0`, values higher than\n * 2^256-1 will return the maximum expressible unsigned 256-bit value\n * (`0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`).\n *\n * @param value - the BigInt to encode\n */\nconst bigIntToBinUint256BEClamped = (value) => {\n const uint256Bytes = 32;\n return binToFixedLength(bigIntToBinUintLE(value), uint256Bytes).reverse();\n};\n/**\n * Decode a little-endian Uint8Array of any length into a BigInt.\n *\n * The `bytes` parameter can be set to constrain the expected length (default:\n * `bin.length`). This method throws if `bin.length` is not equal to `bytes`.\n *\n * @param bin - the Uint8Array to decode\n * @param bytes - the number of bytes to read (default: `bin.length`)\n */\nconst binToBigIntUintLE = (bin, bytes = bin.length) => {\n const bitsInAByte = 8;\n if (bin.length !== bytes) {\n // eslint-disable-next-line functional/no-throw-statement\n throw new TypeError(`Bin length must be ${bytes}.`);\n }\n return new Uint8Array(bin.buffer, bin.byteOffset, bin.length).reduceRight(\n // eslint-disable-next-line no-bitwise\n (accumulated, byte) => (accumulated << BigInt(bitsInAByte)) | BigInt(byte), 0n);\n};\n/**\n * Decode an 8-byte Uint64LE Uint8Array into a BigInt.\n *\n * Throws if `bin` is shorter than 8 bytes.\n *\n * @param bin - the Uint8Array to decode\n */\nconst binToBigIntUint64LE = (bin) => {\n const uint64LengthInBytes = 8;\n const truncatedBin = bin.length > uint64LengthInBytes ? bin.slice(0, uint64LengthInBytes) : bin;\n return binToBigIntUintLE(truncatedBin, uint64LengthInBytes);\n};\n/**\n * Decode an {@link Output.valueSatoshis} into a `BigInt`. This is an alias for\n * {@link binToBigIntUint64LE}.\n *\n * Throws if the provided value is shorter than 8 bytes.\n */\nconst binToValueSatoshis = binToBigIntUint64LE;\n/**\n * Encode a `BigInt` into an {@link Output.valueSatoshis}. This is an alias for\n * {@link bigIntToBinUint64LE}.\n *\n * This method will return an incorrect result for values outside of the range 0\n * to 0xffff_ffff_ffff_ffff (`18446744073709551615`).\n */\nconst valueSatoshisToBin = bigIntToBinUint64LE;\n/**\n * Get the expected byte length of a CompactSize given a first byte.\n *\n * @param firstByte - the first byte of the CompactSize\n */\nconst compactSizePrefixToSize = (firstByte) => {\n switch (firstByte) {\n case 253 /* CompactSize.uint16Prefix */:\n return 2 /* CompactSize.uint16 */ + 1;\n case 254 /* CompactSize.uint32Prefix */:\n return 4 /* CompactSize.uint32 */ + 1;\n case 255 /* CompactSize.uint64Prefix */:\n return 8 /* CompactSize.uint64 */ + 1;\n default:\n return 1 /* CompactSize.uint8 */;\n }\n};\nvar CompactSizeError;\n(function (CompactSizeError) {\n CompactSizeError[\"noPrefix\"] = \"Error reading CompactSize: requires at least one byte.\";\n CompactSizeError[\"insufficientBytes\"] = \"Error reading CompactSize: insufficient bytes.\";\n CompactSizeError[\"nonMinimal\"] = \"Error reading CompactSize: CompactSize is not minimally encoded.\";\n CompactSizeError[\"excessiveBytes\"] = \"Error decoding CompactSize: unexpected bytes after CompactSize.\";\n})(CompactSizeError || (CompactSizeError = {}));\n/**\n * Read a non-minimally-encoded `CompactSize` (see {@link bigIntToCompactSize})\n * from the provided {@link ReadPosition}, returning either an error message (as\n * a string) or an object containing the value and the\n * next {@link ReadPosition}.\n *\n * Rather than this function, most applications should\n * use {@link readCompactSizeMinimal}.\n *\n * @param position - the {@link ReadPosition} at which to start reading the\n * `CompactSize`\n */\nconst readCompactSize = (position) => {\n const { bin, index } = position;\n const prefix = bin[index];\n if (prefix === undefined) {\n return (0,_error_js__WEBPACK_IMPORTED_MODULE_0__.formatError)(CompactSizeError.noPrefix);\n }\n const bytes = compactSizePrefixToSize(prefix);\n if (bin.length - index < bytes) {\n return (0,_error_js__WEBPACK_IMPORTED_MODULE_0__.formatError)(CompactSizeError.insufficientBytes, `CompactSize prefix ${prefix} requires at least ${bytes} bytes. Remaining bytes: ${bin.length - index}`);\n }\n const hasPrefix = bytes !== 1;\n const contents = hasPrefix\n ? bin.subarray(index + 1, index + bytes)\n : bin.subarray(index, index + bytes);\n return {\n position: { bin, index: index + bytes },\n result: binToBigIntUintLE(contents),\n };\n};\n/**\n * Encode a positive BigInt as a `CompactSize` (Satoshi's variable-length,\n * positive integer format).\n *\n * Note: the maximum value of a CompactSize is `0xffff_ffff_ffff_ffff`\n * (`18446744073709551615`). This method will return an incorrect result for\n * values outside of the range `0` to `0xffff_ffff_ffff_ffff`. If applicable,\n * applications should handle such cases prior to calling this method.\n *\n * @param value - the BigInt to encode (must be no larger than\n * `0xffff_ffff_ffff_ffff`)\n */\nconst bigIntToCompactSize = (value) => value <= BigInt(252 /* CompactSize.uint8MaxValue */)\n ? Uint8Array.of(Number(value))\n : value <= BigInt(65535 /* CompactSize.uint16MaxValue */)\n ? Uint8Array.from([\n 253 /* CompactSize.uint16Prefix */,\n ...numberToBinUint16LE(Number(value)),\n ])\n : value <= BigInt(4294967295 /* CompactSize.uint32MaxValue */)\n ? Uint8Array.from([\n 254 /* CompactSize.uint32Prefix */,\n ...numberToBinUint32LE(Number(value)),\n ])\n : Uint8Array.from([\n 255 /* CompactSize.uint64Prefix */,\n ...bigIntToBinUint64LE(value),\n ]);\n/**\n * Read a minimally-encoded `CompactSize` from the provided\n * {@link ReadPosition}, returning either an error message (as a string) or an\n * object containing the value and the next {@link ReadPosition}.\n *\n * @param position - the {@link ReadPosition} at which to start reading the\n * `CompactSize`\n */\nconst readCompactSizeMinimal = (position) => {\n const read = readCompactSize(position);\n if (typeof read === 'string') {\n return read;\n }\n const readLength = read.position.index - position.index;\n const canonicalEncoding = bigIntToCompactSize(read.result);\n if (readLength !== canonicalEncoding.length) {\n return (0,_error_js__WEBPACK_IMPORTED_MODULE_0__.formatError)(CompactSizeError.nonMinimal, `Value: ${read.result.toString()}, encoded length: ${readLength}, canonical length: ${canonicalEncoding.length}`);\n }\n return read;\n};\n/**\n * Decode a minimally-encoded `CompactSize` (Satoshi's variable-length, positive\n * integer format) from a Uint8Array, returning the value as a BigInt. This\n * function returns an error if the entire input is not consumed – to read a\n * `CompactSize` from a position within a larger `Uint8Array`,\n * use {@link readCompactSizeMinimal} or {@link readCompactSize}.\n *\n * @param bin - the Uint8Array from which to read the CompactSize\n */\nconst compactSizeToBigInt = (bin) => {\n const read = readCompactSizeMinimal({ bin, index: 0 });\n if (typeof read === 'string') {\n return read;\n }\n if (read.position.index !== bin.length) {\n return (0,_error_js__WEBPACK_IMPORTED_MODULE_0__.formatError)(CompactSizeError.excessiveBytes, `CompactSize ends at index ${read.position.index}, but input includes ${bin.length} bytes.`);\n }\n return read.result;\n};\n/**\n * Convert a signed integer into it's two's compliment unsigned equivalent, e.g.\n * `0b11111111111111111111111111111110` is `-2` as a signed integer or\n * `4294967294` as an unsigned integer.\n */\nconst int32SignedToUnsigned = (int32) => \n// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\nUint32Array.from(Int32Array.of(int32))[0];\n/**\n * Convert an unsigned integer into it's two's compliment signed equivalent,\n * e.g. `0b11111111111111111111111111111110` is `4294967294` as an unsigned\n * integer or `-2` as a signed integer.\n */\nconst int32UnsignedToSigned = (int32) => \n// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\nInt32Array.from(Uint32Array.of(int32))[0];\n//# sourceMappingURL=number.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@bitauth/libauth/build/lib/format/number.js?");
2198
1898
 
2199
1899
  /***/ }),
2200
1900
 
@@ -2702,16 +2402,13 @@ eval("module.exports = JSON.parse('[\"abandon\",\"ability\",\"able\",\"about\",\
2702
2402
  /******/ }
2703
2403
  /******/ // Create a new module (and put it into the cache)
2704
2404
  /******/ var module = __webpack_module_cache__[moduleId] = {
2705
- /******/ id: moduleId,
2706
- /******/ loaded: false,
2405
+ /******/ // no module.id needed
2406
+ /******/ // no module.loaded needed
2707
2407
  /******/ exports: {}
2708
2408
  /******/ };
2709
2409
  /******/
2710
2410
  /******/ // Execute the module function
2711
- /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
2712
- /******/
2713
- /******/ // Flag the module as loaded
2714
- /******/ module.loaded = true;
2411
+ /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
2715
2412
  /******/
2716
2413
  /******/ // Return the exports of the module
2717
2414
  /******/ return module.exports;
@@ -2839,15 +2536,6 @@ eval("module.exports = JSON.parse('[\"abandon\",\"ability\",\"able\",\"about\",\
2839
2536
  /******/ };
2840
2537
  /******/ })();
2841
2538
  /******/
2842
- /******/ /* webpack/runtime/node module decorator */
2843
- /******/ (() => {
2844
- /******/ __webpack_require__.nmd = (module) => {
2845
- /******/ module.paths = [];
2846
- /******/ if (!module.children) module.children = [];
2847
- /******/ return module;
2848
- /******/ };
2849
- /******/ })();
2850
- /******/
2851
2539
  /************************************************************************/
2852
2540
  /******/
2853
2541
  /******/ // startup