mainnet-js 3.1.7 → 4.0.0-next.2

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 (83) hide show
  1. package/dist/index.html +1 -1
  2. package/dist/{mainnet-3.1.7.js → mainnet-4.0.0-next.2.js} +66 -166
  3. package/dist/module/cache/walletCache.d.ts +16 -6
  4. package/dist/module/cache/walletCache.d.ts.map +1 -1
  5. package/dist/module/cache/walletCache.js +92 -34
  6. package/dist/module/cache/walletCache.js.map +1 -1
  7. package/dist/module/mine/mine.d.ts.map +1 -1
  8. package/dist/module/mine/mine.js +14 -19
  9. package/dist/module/mine/mine.js.map +1 -1
  10. package/dist/module/network/Connection.d.ts +1 -12
  11. package/dist/module/network/Connection.d.ts.map +1 -1
  12. package/dist/module/network/Connection.js +12 -33
  13. package/dist/module/network/Connection.js.map +1 -1
  14. package/dist/module/network/ElectrumNetworkProvider.d.ts +4 -7
  15. package/dist/module/network/ElectrumNetworkProvider.d.ts.map +1 -1
  16. package/dist/module/network/ElectrumNetworkProvider.js +43 -70
  17. package/dist/module/network/ElectrumNetworkProvider.js.map +1 -1
  18. package/dist/module/network/configuration.d.ts +2 -4
  19. package/dist/module/network/configuration.d.ts.map +1 -1
  20. package/dist/module/network/configuration.js +25 -50
  21. package/dist/module/network/configuration.js.map +1 -1
  22. package/dist/module/network/constant.d.ts +7 -7
  23. package/dist/module/network/constant.d.ts.map +1 -1
  24. package/dist/module/network/constant.js +20 -24
  25. package/dist/module/network/constant.js.map +1 -1
  26. package/dist/module/network/default.d.ts +3 -2
  27. package/dist/module/network/default.d.ts.map +1 -1
  28. package/dist/module/network/default.js +19 -51
  29. package/dist/module/network/default.js.map +1 -1
  30. package/dist/module/network/index.d.ts +2 -2
  31. package/dist/module/network/index.d.ts.map +1 -1
  32. package/dist/module/network/index.js +2 -2
  33. package/dist/module/network/index.js.map +1 -1
  34. package/dist/module/network/interface.d.ts +0 -6
  35. package/dist/module/network/interface.d.ts.map +1 -1
  36. package/dist/module/wallet/Base.d.ts.map +1 -1
  37. package/dist/module/wallet/Base.js +33 -12
  38. package/dist/module/wallet/Base.js.map +1 -1
  39. package/dist/module/wallet/HDWallet.d.ts.map +1 -1
  40. package/dist/module/wallet/HDWallet.js +16 -35
  41. package/dist/module/wallet/HDWallet.js.map +1 -1
  42. package/dist/module/wallet/Watch.d.ts +22 -1
  43. package/dist/module/wallet/Watch.d.ts.map +1 -1
  44. package/dist/module/wallet/Watch.js +137 -6
  45. package/dist/module/wallet/Watch.js.map +1 -1
  46. package/dist/module/wallet/Wif.d.ts +1 -1
  47. package/dist/module/wallet/Wif.d.ts.map +1 -1
  48. package/dist/module/wallet/Wif.js +0 -4
  49. package/dist/module/wallet/Wif.js.map +1 -1
  50. package/dist/tsconfig.tsbuildinfo +1 -1
  51. package/package.json +5 -3
  52. package/src/cache/walletCache.ts +122 -57
  53. package/src/mine/mine.ts +18 -22
  54. package/src/network/Connection.test.ts +8 -7
  55. package/src/network/Connection.ts +16 -42
  56. package/src/network/ElectrumNetworkProvider.ts +54 -88
  57. package/src/network/Rpc.test.ts +6 -5
  58. package/src/network/configuration.test.ts +23 -25
  59. package/src/network/configuration.ts +29 -55
  60. package/src/network/constant.ts +20 -25
  61. package/src/network/default.ts +25 -87
  62. package/src/network/electrum.test.ts +47 -11
  63. package/src/network/index.ts +7 -2
  64. package/src/network/interface.ts +0 -7
  65. package/src/network/subscription.test.ts +268 -0
  66. package/src/wallet/Base.ts +39 -17
  67. package/src/wallet/Cashtokens.test.headless.js +6 -0
  68. package/src/wallet/Cashtokens.test.ts +13 -0
  69. package/src/wallet/HDWallet.test.ts +4 -4
  70. package/src/wallet/HDWallet.ts +19 -35
  71. package/src/wallet/WalletCache.test.ts +6 -2
  72. package/src/wallet/Watch.ts +199 -7
  73. package/src/wallet/Wif.test.ts +6 -0
  74. package/src/wallet/Wif.ts +2 -9
  75. package/tsconfig.browser.json +10 -1
  76. package/tsconfig.json +12 -1
  77. package/webpack.config.cjs +1 -0
  78. package/dist/module/network/util.d.ts +0 -3
  79. package/dist/module/network/util.d.ts.map +0 -1
  80. package/dist/module/network/util.js +0 -27
  81. package/dist/module/network/util.js.map +0 -1
  82. package/src/network/util.test.ts +0 -24
  83. package/src/network/util.ts +0 -30
@@ -8,43 +8,13 @@
8
8
  */
9
9
  /******/ var __webpack_modules__ = ({
10
10
 
11
- /***/ "../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/browser.js":
12
- /*!**************************************************************************************!*\
13
- !*** ../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/browser.js ***!
14
- \**************************************************************************************/
15
- /***/ ((module, exports, __webpack_require__) => {
16
-
17
- eval("/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = __webpack_require__(/*! ./common */ \"../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/common.js\")(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/browser.js?");
18
-
19
- /***/ }),
20
-
21
- /***/ "../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/common.js":
22
- /*!*************************************************************************************!*\
23
- !*** ../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/common.js ***!
24
- \*************************************************************************************/
25
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
26
-
27
- eval("\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = __webpack_require__(/*! ms */ \"../../node_modules/ms/index.js\");\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/common.js?");
28
-
29
- /***/ }),
30
-
31
- /***/ "../../node_modules/eventemitter3/index.js":
32
- /*!*************************************************!*\
33
- !*** ../../node_modules/eventemitter3/index.js ***!
34
- \*************************************************/
35
- /***/ ((module) => {
36
-
37
- eval("\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif (true) {\n module.exports = EventEmitter;\n}\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/eventemitter3/index.js?");
38
-
39
- /***/ }),
40
-
41
- /***/ "../../node_modules/ms/index.js":
42
- /*!**************************************!*\
43
- !*** ../../node_modules/ms/index.js ***!
44
- \**************************************/
11
+ /***/ "../../node_modules/@rpckit/core/dist lazy recursive":
12
+ /*!**************************************************************************!*\
13
+ !*** ../../node_modules/@rpckit/core/dist/ lazy strict namespace object ***!
14
+ \**************************************************************************/
45
15
  /***/ ((module) => {
46
16
 
47
- eval("/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/ms/index.js?");
17
+ eval("function webpackEmptyAsyncContext(req) {\n\t// Here Promise.resolve().then() is used instead of new Promise() to prevent\n\t// uncaught exception popping up in devtools\n\treturn Promise.resolve().then(() => {\n\t\tvar e = new Error(\"Cannot find module '\" + req + \"'\");\n\t\te.code = 'MODULE_NOT_FOUND';\n\t\tthrow e;\n\t});\n}\nwebpackEmptyAsyncContext.keys = () => ([]);\nwebpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;\nwebpackEmptyAsyncContext.id = \"../../node_modules/@rpckit/core/dist lazy recursive\";\nmodule.exports = webpackEmptyAsyncContext;\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@rpckit/core/dist/_lazy_strict_namespace_object?");
48
18
 
49
19
  /***/ }),
50
20
 
@@ -84,7 +54,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
84
54
  \**********************************/
85
55
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
86
56
 
87
- 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 */ \"PersistentWalletCache\": () => (/* binding */ PersistentWalletCache)\n/* harmony export */ });\n/* unused harmony exports stringify, parse */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/combinations.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\n/* harmony import */ var _WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\nconst stringify = (_) => JSON.stringify(_, (key, value) => {\n if (key.includes(\"Key\"))\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(value);\n return typeof value === \"bigint\" ? value.toString() + \"n\" : value;\n});\nconst parse = (data) => JSON.parse(data, (key, value) => {\n if (key.includes(\"Key\") && typeof value === \"string\") {\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(value);\n }\n if (typeof value === \"string\" && /^\\d+n$/.test(value)) {\n return BigInt(value.slice(0, -1));\n }\n return value;\n});\nclass PersistentWalletCache {\n get storage() {\n if (!_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache) {\n this._storage = undefined;\n return this._storage;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache && !(this._storage instanceof _MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache)) {\n this._storage = new _MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache();\n return this._storage;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !(this._storage instanceof _WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache)) {\n this._storage = new _WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache();\n return this._storage;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache &&\n !(this._storage instanceof _IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache)) {\n this._storage = new _IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache(\"WalletCache\");\n return this._storage;\n }\n return this._storage;\n }\n constructor(walletId, hdNode, networkPrefix, writeTimeout = 2000) {\n this.walletId = walletId;\n this.hdNode = hdNode;\n this.networkPrefix = networkPrefix;\n this.writeTimeout = writeTimeout;\n this.walletCache = {};\n this.indexCache = {};\n if (!this.hdNode) {\n throw new Error(\"HDNode is undefined\");\n }\n }\n async init() {\n await this.storage?.init();\n const data = await this.storage?.getItem(`walletCache-${this.walletId}`);\n if (data) {\n try {\n const parsed = parse(data);\n this.walletCache = parsed.walletCache || {};\n this.indexCache = parsed.indexCache || {};\n }\n catch (e) {\n // ignore\n }\n }\n }\n schedulePersist() {\n if (this.debounceTimer)\n clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => {\n this.persist().catch(() => { });\n }, this.writeTimeout);\n }\n async persist() {\n if (this.debounceTimer)\n clearTimeout(this.debounceTimer);\n this.debounceTimer = undefined;\n this.storage?.setItem(`walletCache-${this.walletId}`, stringify({\n walletCache: this.walletCache,\n indexCache: this.indexCache,\n }));\n }\n getByIndex(addressIndex, change) {\n const id = `${this.walletId}-${addressIndex}-${change}`;\n if (!this.walletCache[id]) {\n const node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.deriveHdPathRelative)(this.hdNode, `${change ? 1 : 0}/${addressIndex}`);\n const privateKey = \"privateKey\" in node ? node.privateKey : undefined;\n const publicKey = \"publicKey\" in node\n ? node.publicKey\n : (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.secp256k1.derivePublicKeyUncompressed(privateKey));\n const publicKeyCompressed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.secp256k1.compressPublicKey(publicKey));\n const publicKeyHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.hash160)(publicKeyCompressed);\n const address = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.encodeCashAddress)({\n throwErrors: true,\n prefix: this.networkPrefix,\n type: _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.CashAddressType.p2pkh,\n payload: publicKeyHash,\n }).address;\n const tokenAddress = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.encodeCashAddress)({\n throwErrors: true,\n prefix: this.networkPrefix,\n type: _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.CashAddressType.p2pkhWithTokens,\n payload: publicKeyHash,\n }).address;\n this.walletCache[id] = {\n address,\n tokenAddress,\n privateKey: privateKey,\n publicKey,\n publicKeyHash,\n index: addressIndex,\n change,\n status: null,\n utxos: [],\n rawHistory: [],\n lastConfirmedHeight: 0,\n };\n this.indexCache[address] = {\n index: addressIndex,\n change,\n };\n this.schedulePersist();\n }\n return this.walletCache[id];\n }\n get(address) {\n const { index, change } = this.indexCache[address] || {};\n if (index === undefined || change === undefined) {\n return undefined;\n }\n return this.getByIndex(index, change);\n }\n setStatusAndUtxos(address, status, utxos, rawHistory, lastConfirmedHeight) {\n const entry = this.get(address);\n if (!entry) {\n return;\n }\n const { index, change } = this.indexCache[address] || {};\n if (index === undefined || change === undefined) {\n return;\n }\n const key = `${this.walletId}-${index}-${change}`;\n this.walletCache[key].status = status;\n this.walletCache[key].utxos = utxos;\n this.walletCache[key].rawHistory = rawHistory;\n this.walletCache[key].lastConfirmedHeight = lastConfirmedHeight;\n this.schedulePersist();\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/cache/walletCache.ts?");
57
+ 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 */ \"HDWalletCache\": () => (/* binding */ HDWalletCache),\n/* harmony export */ \"SingleAddressWalletCache\": () => (/* binding */ SingleAddressWalletCache)\n/* harmony export */ });\n/* unused harmony exports stringify, parse */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/combinations.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\n/* harmony import */ var _WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\nconst stringify = (_) => JSON.stringify(_, (key, value) => {\n if (key.includes(\"Key\"))\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(value);\n return typeof value === \"bigint\" ? value.toString() + \"n\" : value;\n});\nconst parse = (data) => JSON.parse(data, (key, value) => {\n if (key.includes(\"Key\") && typeof value === \"string\") {\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(value);\n }\n if (typeof value === \"string\" && /^\\d+n$/.test(value)) {\n return BigInt(value.slice(0, -1));\n }\n return value;\n});\nfunction getStorage() {\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache)\n return new _MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache();\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache)\n return new _WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache();\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache)\n return new _IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache(\"WalletCache\");\n return undefined;\n}\n/// Cache for single-address wallets (WatchWallet, Wif)\nclass SingleAddressWalletCache {\n constructor(walletId, address, tokenAddress, writeTimeout = 2000) {\n this.walletId = walletId;\n this.writeTimeout = writeTimeout;\n this.entry = {\n address,\n tokenAddress,\n privateKey: undefined,\n publicKey: new Uint8Array(),\n publicKeyHash: new Uint8Array(),\n index: 0,\n change: false,\n status: null,\n utxos: [],\n rawHistory: [],\n lastConfirmedHeight: 0,\n };\n }\n async init() {\n this._storage = getStorage();\n await this._storage?.init();\n const data = await this._storage?.getItem(`walletCache-${this.walletId}`);\n if (data) {\n try {\n const parsed = parse(data);\n // Restore persisted fields, keep address identity from constructor\n const addr = this.entry.address;\n const tokenAddr = this.entry.tokenAddress;\n Object.assign(this.entry, parsed, {\n address: addr,\n tokenAddress: tokenAddr,\n });\n }\n catch (_e) {\n // ignore\n }\n }\n }\n async persist(immediate = false) {\n if (this.debounceTimer)\n clearTimeout(this.debounceTimer);\n if (immediate) {\n this.debounceTimer = undefined;\n await this._storage?.setItem(`walletCache-${this.walletId}`, stringify(this.entry));\n }\n else {\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = undefined;\n this._storage?.setItem(`walletCache-${this.walletId}`, stringify(this.entry));\n }, this.writeTimeout);\n }\n }\n get(address) {\n return address === this.entry.address ? this.entry : undefined;\n }\n getByIndex(_index, _change) {\n return this.entry;\n }\n setStatusAndUtxos(address, status, utxos, rawHistory, lastConfirmedHeight) {\n if (address !== this.entry.address)\n return;\n this.entry.status = status;\n this.entry.utxos = utxos;\n this.entry.rawHistory = rawHistory;\n this.entry.lastConfirmedHeight = lastConfirmedHeight;\n this.persist();\n }\n}\nclass HDWalletCache {\n constructor(walletId, hdNode, networkPrefix, writeTimeout = 2000) {\n this.walletId = walletId;\n this.hdNode = hdNode;\n this.networkPrefix = networkPrefix;\n this.writeTimeout = writeTimeout;\n this.walletCache = {};\n this.indexCache = {};\n if (!this.hdNode) {\n throw new Error(\"HDNode is undefined\");\n }\n }\n async init() {\n this._storage = getStorage();\n await this._storage?.init();\n const data = await this._storage?.getItem(`walletCache-${this.walletId}`);\n if (data) {\n try {\n const parsed = parse(data);\n this.walletCache = parsed.walletCache || {};\n this.indexCache = parsed.indexCache || {};\n }\n catch (e) {\n // ignore\n }\n }\n }\n async persist(immediate = false) {\n if (this.debounceTimer)\n clearTimeout(this.debounceTimer);\n const write = () => this._storage?.setItem(`walletCache-${this.walletId}`, stringify({\n walletCache: this.walletCache,\n indexCache: this.indexCache,\n }));\n if (immediate) {\n this.debounceTimer = undefined;\n await write();\n }\n else {\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = undefined;\n write();\n }, this.writeTimeout);\n }\n }\n getByIndex(addressIndex, change) {\n const id = `${this.walletId}-${addressIndex}-${change}`;\n if (!this.walletCache[id]) {\n const node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.deriveHdPathRelative)(this.hdNode, `${change ? 1 : 0}/${addressIndex}`);\n const privateKey = \"privateKey\" in node ? node.privateKey : undefined;\n const publicKey = \"publicKey\" in node\n ? node.publicKey\n : (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.secp256k1.derivePublicKeyUncompressed(privateKey));\n const publicKeyCompressed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.secp256k1.compressPublicKey(publicKey));\n const publicKeyHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.hash160)(publicKeyCompressed);\n const address = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.encodeCashAddress)({\n throwErrors: true,\n prefix: this.networkPrefix,\n type: _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.CashAddressType.p2pkh,\n payload: publicKeyHash,\n }).address;\n const tokenAddress = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.encodeCashAddress)({\n throwErrors: true,\n prefix: this.networkPrefix,\n type: _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.CashAddressType.p2pkhWithTokens,\n payload: publicKeyHash,\n }).address;\n this.walletCache[id] = {\n address,\n tokenAddress,\n privateKey: privateKey,\n publicKey,\n publicKeyHash,\n index: addressIndex,\n change,\n status: null,\n utxos: [],\n rawHistory: [],\n lastConfirmedHeight: 0,\n };\n this.indexCache[address] = {\n index: addressIndex,\n change,\n };\n this.persist();\n }\n return this.walletCache[id];\n }\n get(address) {\n const { index, change } = this.indexCache[address] || {};\n if (index === undefined || change === undefined) {\n return undefined;\n }\n return this.getByIndex(index, change);\n }\n setStatusAndUtxos(address, status, utxos, rawHistory, lastConfirmedHeight) {\n const entry = this.get(address);\n if (!entry) {\n return;\n }\n const { index, change } = this.indexCache[address] || {};\n if (index === undefined || change === undefined) {\n return;\n }\n const key = `${this.walletId}-${index}-${change}`;\n this.walletCache[key].status = status;\n this.walletCache[key].utxos = utxos;\n this.walletCache[key].rawHistory = rawHistory;\n this.walletCache[key].lastConfirmedHeight = lastConfirmedHeight;\n this.persist();\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/cache/walletCache.ts?");
88
58
 
89
59
  /***/ }),
90
60
 
@@ -174,7 +144,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
174
144
  \**********************/
175
145
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
176
146
 
177
- 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 */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.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_4__.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_4__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchageRatePromise\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.ExchageRatePromise),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"FeePaidByEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__.FeePaidByEnum),\n/* harmony export */ \"GAP_SIZE\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.GAP_SIZE),\n/* harmony export */ \"HDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.HDWallet),\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 */ \"RegTestHDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.RegTestHDWallet),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.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_5__.SignedMessage),\n/* harmony export */ \"StorageProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_2__.StorageProvider),\n/* harmony export */ \"TestNetHDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.TestNetHDWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.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_8__.Wallet),\n/* harmony export */ \"WalletTypeEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WifWallet),\n/* harmony export */ \"XPubKey\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.XPubKey),\n/* harmony export */ \"_checkContextSafety\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__._checkContextSafety),\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 */ \"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 */ \"checkUtxos\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.checkUtxos),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convert),\n/* harmony export */ \"convertAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convertAddress),\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 */ \"decodeHeader\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.decodeHeader),\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_4__.disconnectProviders),\n/* harmony export */ \"expect\": () => (/* reexport safe */ _test_expect_js__WEBPACK_IMPORTED_MODULE_1__.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 */ \"getHistory\": () => (/* reexport safe */ _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__.getHistory),\n/* harmony export */ \"getNamedWalletId\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.getNamedWalletId),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.getNetworkProvider),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getRuntimePlatform),\n/* harmony export */ \"getStorageProvider\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.getStorageProvider),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getUsdRate),\n/* harmony export */ \"getWeakRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getWeakRandomInt),\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 */ \"initProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.initProvider),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.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_18__),\n/* harmony export */ \"mine\": () => (/* reexport safe */ _mine_index_js__WEBPACK_IMPORTED_MODULE_3__.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 */ \"placeholderCashAddr\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.placeholderCashAddr),\n/* harmony export */ \"placeholderTokenAddr\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.placeholderTokenAddr),\n/* harmony export */ \"removeFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.removeFetchMock),\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 */ \"setupFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.setupFetchMock),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sumUtxoValue),\n/* harmony export */ \"toBch\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toBch),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toCashaddr),\n/* harmony export */ \"toCurrency\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toCurrency),\n/* harmony export */ \"toSat\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toSat),\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 _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./test/fetch.js */ \"./src/test/fetch.ts\");\n/* harmony import */ var _test_expect_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./test/expect.js */ \"./src/test/expect.ts\");\n/* harmony import */ var _db_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./db/index.js */ \"./src/db/index.ts\");\n/* harmony import */ var _mine_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mine/index.js */ \"./src/mine/index.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./wallet/Watch.js */ \"./src/wallet/Watch.ts\");\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/HDWallet.js */ \"./src/wallet/HDWallet.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 _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./history/getHistory.js */ \"./src/history/getHistory.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.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__([_mine_index_js__WEBPACK_IMPORTED_MODULE_3__, _network_index_js__WEBPACK_IMPORTED_MODULE_4__, _message_signed_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_HDWallet_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__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__, _libauth_js__WEBPACK_IMPORTED_MODULE_18__]);\n([_mine_index_js__WEBPACK_IMPORTED_MODULE_3__, _network_index_js__WEBPACK_IMPORTED_MODULE_4__, _message_signed_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_HDWallet_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__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__, _libauth_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\n// libauth\n\n// constants\n\n\n// interfaces\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
147
+ 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 */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.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 */ \"DefaultProvider\": () => (/* reexport safe */ _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__.DefaultProvider),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchageRatePromise\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.ExchageRatePromise),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"FeePaidByEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__.FeePaidByEnum),\n/* harmony export */ \"GAP_SIZE\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.GAP_SIZE),\n/* harmony export */ \"HDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.HDWallet),\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 */ \"RegTestHDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.RegTestHDWallet),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.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_5__.SignedMessage),\n/* harmony export */ \"StorageProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_2__.StorageProvider),\n/* harmony export */ \"TestNetHDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.TestNetHDWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.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_8__.Wallet),\n/* harmony export */ \"WalletTypeEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WifWallet),\n/* harmony export */ \"XPubKey\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.XPubKey),\n/* harmony export */ \"_checkContextSafety\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__._checkContextSafety),\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 */ \"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 */ \"checkUtxos\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.checkUtxos),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convert),\n/* harmony export */ \"convertAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convertAddress),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convertObject),\n/* harmony export */ \"createProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.createProvider),\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 */ \"decodeHeader\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.decodeHeader),\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_4__.disconnectProviders),\n/* harmony export */ \"expect\": () => (/* reexport safe */ _test_expect_js__WEBPACK_IMPORTED_MODULE_1__.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 */ \"getGlobalProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.getGlobalProvider),\n/* harmony export */ \"getHistory\": () => (/* reexport safe */ _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__.getHistory),\n/* harmony export */ \"getNamedWalletId\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.getNamedWalletId),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.getNetworkProvider),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getRuntimePlatform),\n/* harmony export */ \"getStorageProvider\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.getStorageProvider),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getUsdRate),\n/* harmony export */ \"getWeakRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getWeakRandomInt),\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 */ \"initProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.initProvider),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.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_18__),\n/* harmony export */ \"mine\": () => (/* reexport safe */ _mine_index_js__WEBPACK_IMPORTED_MODULE_3__.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 */ \"placeholderCashAddr\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.placeholderCashAddr),\n/* harmony export */ \"placeholderTokenAddr\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.placeholderTokenAddr),\n/* harmony export */ \"removeFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.removeFetchMock),\n/* harmony export */ \"removeGlobalProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.removeGlobalProvider),\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 */ \"setGlobalProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.setGlobalProvider),\n/* harmony export */ \"setupFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.setupFetchMock),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sumUtxoValue),\n/* harmony export */ \"toBch\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toBch),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toCashaddr),\n/* harmony export */ \"toCurrency\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toCurrency),\n/* harmony export */ \"toSat\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toSat),\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 _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./test/fetch.js */ \"./src/test/fetch.ts\");\n/* harmony import */ var _test_expect_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./test/expect.js */ \"./src/test/expect.ts\");\n/* harmony import */ var _db_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./db/index.js */ \"./src/db/index.ts\");\n/* harmony import */ var _mine_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mine/index.js */ \"./src/mine/index.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./wallet/Watch.js */ \"./src/wallet/Watch.ts\");\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/HDWallet.js */ \"./src/wallet/HDWallet.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 _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./history/getHistory.js */ \"./src/history/getHistory.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.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__([_mine_index_js__WEBPACK_IMPORTED_MODULE_3__, _network_index_js__WEBPACK_IMPORTED_MODULE_4__, _message_signed_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_HDWallet_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__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__, _libauth_js__WEBPACK_IMPORTED_MODULE_18__]);\n([_mine_index_js__WEBPACK_IMPORTED_MODULE_3__, _network_index_js__WEBPACK_IMPORTED_MODULE_4__, _message_signed_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_HDWallet_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__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__, _libauth_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\n// libauth\n\n// constants\n\n\n// interfaces\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
178
148
 
179
149
  /***/ }),
180
150
 
@@ -224,7 +194,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
224
194
  \**************************/
225
195
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
226
196
 
227
- 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 */ \"mine\": () => (/* binding */ mine)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n\n/**\n * Mine blocks to a regtest address\n *\n * @param cashaddr - the address to mine to\n * @param blocks - the number of blocks to mine\n *\n * @remarks\n * This function assumes a local regtest bitcoin node with RPC_* matching the docker configuration\n */\nconst mine = async ({ cashaddr, blocks, }) => {\n const response = await fetch(`http://127.0.0.1:${process.env.RPC_PORT}/`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \"Basic \" +\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToBase64)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.utf8ToBin)(`${process.env.RPC_USER}:${process.env.RPC_PASS}`)),\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: \"0\",\n method: \"generatetoaddress\",\n params: {\n nblocks: blocks,\n address: cashaddr,\n },\n }),\n });\n const json = await response.json();\n return json.result;\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/mine/mine.ts?");
197
+ 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 */ \"mine\": () => (/* binding */ mine)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _rpckit_http__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @rpckit/http */ \"../../node_modules/@rpckit/http/dist/http.js\");\n/* harmony import */ var _rpckit_fallback__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @rpckit/fallback */ \"../../node_modules/@rpckit/fallback/dist/fallback.js\");\n\n\n\n/**\n * Mine blocks to a regtest address\n *\n * @param cashaddr - the address to mine to\n * @param blocks - the number of blocks to mine\n *\n * @remarks\n * This function assumes a local regtest bitcoin node with RPC_* matching the docker configuration\n */\nconst mine = async ({ cashaddr, blocks, }) => {\n const auth = \"Basic \" +\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToBase64)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.utf8ToBin)(`${process.env.RPC_USER}:${process.env.RPC_PASS}`));\n const transports = [\"127.0.0.1\", \"host.docker.internal\"].map((host) => (0,_rpckit_http__WEBPACK_IMPORTED_MODULE_2__.http)(`http://${host}:${process.env.RPC_PORT}/`, {\n headers: { Authorization: auth },\n }));\n const transport = (0,_rpckit_fallback__WEBPACK_IMPORTED_MODULE_3__.fallback)(transports);\n try {\n return await transport.request(\"generatetoaddress\", blocks, cashaddr);\n }\n finally {\n await transport.close();\n }\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/mine/mine.ts?");
228
198
 
229
199
  /***/ }),
230
200
 
@@ -234,7 +204,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
234
204
  \***********************************/
235
205
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
236
206
 
237
- 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 */ \"Connection\": () => (/* binding */ Connection),\n/* harmony export */ \"disconnectProviders\": () => (/* binding */ disconnectProviders),\n/* harmony export */ \"initProvider\": () => (/* binding */ initProvider),\n/* harmony export */ \"initProviders\": () => (/* binding */ initProviders)\n/* harmony export */ });\n/* harmony import */ var _default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./default.js */ \"./src/network/default.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constant.js */ \"./src/network/constant.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\nasync function initProvider(network) {\n if (!(0,_default_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalProvider)(network)) {\n const conn = new Connection(network);\n const provider = (await conn.ready()).networkProvider;\n (0,_default_js__WEBPACK_IMPORTED_MODULE_0__.setGlobalProvider)(network, provider);\n return provider;\n }\n return (0,_default_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalProvider)(network);\n}\nasync function initProviders(networks) {\n networks = networks ? networks : Object.keys(_constant_js__WEBPACK_IMPORTED_MODULE_1__.networkTickerMap);\n let initPromises = networks.map((n) => initProvider(n));\n await Promise.all(initPromises).catch((e) => {\n console.warn(`Warning, couldn't establish a connection for ${e}`);\n });\n}\nasync function disconnectProvider(network) {\n const provider = (0,_default_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalProvider)(network);\n if (provider) {\n await provider.disconnect();\n (0,_default_js__WEBPACK_IMPORTED_MODULE_0__.removeGlobalProvider)(network);\n return;\n }\n else {\n // console.warn(\n // `Ignoring attempt to disconnect non-existent ${network} provider`\n // );\n return true;\n }\n}\nasync function disconnectProviders(networks) {\n networks = networks ? networks : Object.keys(_constant_js__WEBPACK_IMPORTED_MODULE_1__.networkTickerMap);\n let disconnectPromises = networks.map((n) => disconnectProvider(n));\n await Promise.all(disconnectPromises);\n}\nclass Connection {\n constructor(network, servers) {\n this.network = network ? network : \"mainnet\";\n this.networkPrefix = _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n this.networkProvider = (0,_default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider)(this.network, servers, true);\n }\n async ready() {\n await this.networkProvider.connect();\n await this.networkProvider.ready();\n return this;\n }\n async disconnect() {\n await this.networkProvider.disconnect();\n return this;\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/Connection.ts?");
207
+ 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 */ \"disconnectProviders\": () => (/* binding */ disconnectProviders),\n/* harmony export */ \"initProvider\": () => (/* binding */ initProvider),\n/* harmony export */ \"initProviders\": () => (/* binding */ initProviders)\n/* harmony export */ });\n/* harmony import */ var _default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./default.js */ \"./src/network/default.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constant.js */ \"./src/network/constant.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_default_js__WEBPACK_IMPORTED_MODULE_0__]);\n_default_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\nasync function initProvider(network) {\n if (!(0,_default_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalProvider)(network)) {\n const provider = await (0,_default_js__WEBPACK_IMPORTED_MODULE_0__.createProvider)(network);\n await provider.connect();\n (0,_default_js__WEBPACK_IMPORTED_MODULE_0__.setGlobalProvider)(network, provider);\n return provider;\n }\n return (0,_default_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalProvider)(network);\n}\nasync function initProviders(networks) {\n networks = networks ? networks : Object.keys(_constant_js__WEBPACK_IMPORTED_MODULE_1__.networkTickerMap);\n const results = await Promise.allSettled(networks.map((n) => initProvider(n)));\n for (let i = 0; i < results.length; i++) {\n if (results[i].status === \"rejected\") {\n const { reason } = results[i];\n const message = reason instanceof Error ? reason.message : reason;\n console.warn(`Warning, couldn't establish a connection for ${networks[i]}: ${message}`);\n }\n }\n}\nasync function disconnectProvider(network) {\n const provider = (0,_default_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalProvider)(network);\n if (provider) {\n await provider.disconnect();\n (0,_default_js__WEBPACK_IMPORTED_MODULE_0__.removeGlobalProvider)(network);\n }\n}\nasync function disconnectProviders(networks) {\n networks = networks ? networks : Object.keys(_constant_js__WEBPACK_IMPORTED_MODULE_1__.networkTickerMap);\n await Promise.all(networks.map((n) => disconnectProvider(n)));\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/Connection.ts?");
238
208
 
239
209
  /***/ }),
240
210
 
@@ -244,7 +214,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
244
214
  \************************************************/
245
215
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
246
216
 
247
- 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 */ \"default\": () => (/* binding */ ElectrumNetworkProvider)\n/* harmony export */ });\n/* harmony import */ var _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @electrum-cash/network */ \"../../node_modules/@electrum-cash/network/dist/index.mjs\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_header_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/header.js */ \"./src/util/header.ts\");\n/* harmony import */ var _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../cache/IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../cache/WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\n/* harmony import */ var _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../cache/MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__]);\n([_util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\nclass ElectrumNetworkProvider {\n get cache() {\n if (!_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache) {\n this._cache = undefined;\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache && !(this._cache instanceof _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache)) {\n this._cache = new _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !(this._cache instanceof _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache)) {\n this._cache = new _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache && !(this._cache instanceof _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache)) {\n this._cache = new _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache();\n return this._cache;\n }\n return this._cache;\n }\n constructor(electrum, network = _interface_js__WEBPACK_IMPORTED_MODULE_5__.Network.MAINNET, manualConnectionManagement) {\n this.network = network;\n this.manualConnectionManagement = manualConnectionManagement;\n this.subscriptions = 0;\n this.subscriptionMap = {};\n this.currentHeight = 0;\n if (electrum) {\n this.electrum = electrum;\n }\n else {\n throw new Error(`A electrum-cash client is required.`);\n }\n }\n async getUtxos(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.listunspent\", cashaddr, \"include_tokens\");\n return result.map((utxo) => ({\n address: cashaddr,\n txid: utxo.tx_hash,\n vout: utxo.tx_pos,\n satoshis: BigInt(utxo.value),\n height: utxo.height,\n token: utxo.token_data\n ? {\n ...utxo.token_data,\n amount: BigInt(utxo.token_data.amount),\n }\n : undefined,\n }));\n }\n async getBalance(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.get_balance\", cashaddr);\n return BigInt(result.confirmed) + BigInt(result.unconfirmed);\n }\n async getHeader(height, verbose = false) {\n const key = `header-${this.network}-${height}-${verbose}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(JSON.parse(cached)) : JSON.parse(cached);\n }\n }\n const result = await this.performRequest(\"blockchain.header.get\", height);\n if (this.cache) {\n await this.cache.setItem(key, JSON.stringify(result));\n }\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(result) : result;\n }\n async getRawTransactions(hashes) {\n if (hashes.length === 0)\n return new Map();\n const results = new Map();\n const keys = hashes.map((hash) => `txraw-${this.network}-${hash}`);\n // batch cache read\n let cached;\n if (this.cache) {\n cached = await this.cache.getItems(keys);\n }\n const misses = [];\n for (let i = 0; i < hashes.length; i++) {\n const val = cached?.get(keys[i]);\n if (val) {\n results.set(hashes[i], val);\n }\n else {\n misses.push(hashes[i]);\n }\n }\n if (misses.length > 0) {\n const fetched = await Promise.all(misses.map(async (hash) => {\n const tx = await this.performRequest(\"blockchain.transaction.get\", hash, false);\n return [hash, tx];\n }));\n // batch cache write\n if (this.cache) {\n const entries = fetched.map(([hash, tx]) => [\n `txraw-${this.network}-${hash}`,\n tx,\n ]);\n await this.cache.setItems(entries);\n }\n for (const [hash, tx] of fetched) {\n results.set(hash, tx);\n }\n }\n return results;\n }\n async getHeaders(heights) {\n if (heights.length === 0)\n return new Map();\n const results = new Map();\n const keys = heights.map((height) => `header-${this.network}-${height}-true`);\n // batch cache read\n let cached;\n if (this.cache) {\n cached = await this.cache.getItems(keys);\n }\n const misses = [];\n for (let i = 0; i < heights.length; i++) {\n const val = cached?.get(keys[i]);\n if (val) {\n results.set(heights[i], (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(JSON.parse(val)));\n }\n else {\n misses.push(heights[i]);\n }\n }\n if (misses.length > 0) {\n const fetched = await Promise.all(misses.map(async (height) => {\n const result = await this.performRequest(\"blockchain.header.get\", height);\n return [height, result];\n }));\n // batch cache write\n if (this.cache) {\n const entries = fetched.map(([height, result]) => [\n `header-${this.network}-${height}-true`,\n JSON.stringify(result),\n ]);\n await this.cache.setItems(entries);\n }\n for (const [height, result] of fetched) {\n results.set(height, (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(result));\n }\n }\n return results;\n }\n async getBlockHeight() {\n if (!this.headerCancelFn) {\n this.headerCancelFn = await this.subscribeToHeaders((header) => {\n if (header.height > this.currentHeight) {\n this.currentHeight = header.height;\n }\n });\n }\n if (!this.currentHeight) {\n throw new Error(\"Check failed for eventual inconsistency in subscription implementations.\");\n }\n return this.currentHeight;\n }\n async getRawTransaction(txHash, verbose = false, loadInputValues = false) {\n const nonVerboseKey = `txraw-${this.network}-${txHash}`;\n const verboseKey = `tx-${this.network}-${txHash}`;\n const key = verbose ? verboseKey : nonVerboseKey;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n if (!verbose) {\n return cached;\n }\n const cachedTx = JSON.parse(cached);\n if (cachedTx.confirmations > 0) {\n const currentHeight = await this.getBlockHeight();\n cachedTx.confirmations += currentHeight - cachedTx.fetchHeight;\n }\n const { fetchHeight: _, ...transaction } = cachedTx;\n if (loadInputValues) {\n return this.enrichWithInputValues(transaction);\n }\n return transaction;\n }\n }\n try {\n const result = await this.performRequest(\"blockchain.transaction.get\", txHash, verbose);\n if (!verbose) {\n const hex = result;\n if (this.cache) {\n await this.cache.setItem(key, hex);\n }\n return hex;\n }\n const cachedTx = result;\n cachedTx.confirmations ??= 0;\n cachedTx.fetchHeight = await this.getBlockHeight();\n if (this.cache) {\n await this.cache.setItem(key, JSON.stringify(cachedTx));\n }\n const { fetchHeight: _, ...transaction } = cachedTx;\n if (loadInputValues) {\n return this.enrichWithInputValues(transaction);\n }\n return transaction;\n }\n catch (error) {\n if (error.message.indexOf(\"No such mempool or blockchain transaction.\") > -1)\n throw Error(`Could not decode transaction ${txHash}. It might not exist on the current blockchain (${this.network}).`);\n else\n throw error;\n }\n }\n async enrichWithInputValues(transaction) {\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.getRawTransactionObject(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n const enrichedVin = transaction.vin.map((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n return { ...input, ...output };\n });\n return { ...transaction, vin: enrichedVin };\n }\n async getRawTransactionObject(txHash, loadInputValues = false) {\n if (loadInputValues) {\n return this.getRawTransaction(txHash, true, true);\n }\n return this.getRawTransaction(txHash, true);\n }\n async sendRawTransaction(txHex, awaitPropagation = true) {\n return new Promise(async (resolve, reject) => {\n let txHash = await (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_7__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash && data[1] !== null) {\n await cancel?.();\n resolve(txHash);\n }\n };\n cancel = await this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch(async (error) => {\n await cancel?.();\n reject(error);\n });\n }\n });\n }\n // Get transaction history of a given cashaddr\n async getHistory(cashaddr, fromHeight = 0, toHeight = -1) {\n const result = await this.performRequest(\"blockchain.address.get_history\", cashaddr, fromHeight, toHeight);\n return result;\n }\n // Get the minimum fee a low-priority transaction must pay in order to be accepted to the daemon's memory pool.\n async getRelayFee() {\n const result = (await this.performRequest(\"blockchain.relayfee\"));\n return result;\n }\n async watchAddressStatus(cashaddr, callback) {\n const watchAddressStatusCallback = async (data) => {\n // subscription acknowledgement is the latest known status or null if no status is known\n // status is an array: [ cashaddr, statusHash ]\n if (data instanceof Array) {\n if (data[0] !== cashaddr) {\n return;\n }\n callback(data[1]);\n }\n };\n return this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n }\n // watch for block headers and block height, if `skipCurrentHeight` is set, the notification about current block will not arrive\n async watchBlocks(callback, skipCurrentHeight = true) {\n let acknowledged = !skipCurrentHeight;\n const waitForBlockCallback = (_header) => {\n if (!acknowledged) {\n acknowledged = true;\n return;\n }\n _header = _header instanceof Array ? _header[0] : _header;\n callback(_header);\n };\n return this.subscribeToHeaders(waitForBlockCallback);\n }\n // Wait for the next block or a block at given blockchain height.\n async waitForBlock(height) {\n return new Promise(async (resolve) => {\n let cancelWatch;\n if (this.electrum.chainHeight && !height) {\n height = this.electrum.chainHeight + 1;\n }\n cancelWatch = await this.watchBlocks(async (header) => {\n if (!height) {\n height = header.height + 1;\n return;\n }\n if (header.height >= height) {\n await cancelWatch?.();\n resolve(header);\n return;\n }\n });\n });\n }\n // subscribe to notifications sent when new block is found, the block header is sent to callback\n async subscribeToHeaders(callback) {\n return this.subscribeRequest(\"blockchain.headers.subscribe\", (data) => {\n callback(data[0] ?? data);\n });\n }\n async subscribeToAddress(cashaddr, callback) {\n return this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n return this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async performRequest(name, ...parameters) {\n await this.ready();\n const requestTimeout = new Promise(function (_resolve, reject) {\n setTimeout(function () {\n reject(\"electrum-cash request timed out, retrying\");\n }, 30000);\n }).catch(function (e) {\n throw e;\n });\n const request = this.electrum.request(name, ...parameters);\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(async () => {\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(function (e) {\n throw e;\n });\n });\n }\n async trackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]++;\n }\n else {\n this.subscriptionMap[key] = 1;\n }\n await this.electrum.subscribe(methodName, ...parameters);\n }\n async untrackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]--;\n if (this.subscriptionMap[key] <= 0) {\n // only really unsubscribe if there are no more subscriptions for this `key`\n delete this.subscriptionMap[key];\n try {\n await this.electrum.unsubscribe(methodName, ...parameters);\n }\n catch { }\n }\n }\n }\n async subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const handler = (data) => {\n if (data.method === methodName) {\n callback(data.params);\n }\n };\n this.electrum.on(\"notification\", handler);\n await this.trackSubscription(methodName, ...parameters);\n this.subscriptions++;\n return async () => {\n this.electrum.off(\"notification\", handler);\n await this.untrackSubscription(methodName, ...parameters);\n this.subscriptions--;\n };\n }\n async ready() {\n return this.connect();\n }\n async connect() {\n await this.cache?.init();\n if (this.electrum.status !== _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__.ConnectionStatus.CONNECTED) {\n await this.electrum.connect();\n }\n }\n async disconnect() {\n if (this.subscriptions > 0) {\n // console.warn(\n // `Trying to disconnect a network provider with ${this.subscriptions} active subscriptions. This is in most cases a bad idea.`\n // );\n }\n await this.headerCancelFn?.();\n return this.electrum.disconnect(true, false);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
217
+ 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 */ \"default\": () => (/* binding */ ElectrumNetworkProvider)\n/* harmony export */ });\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_header_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/header.js */ \"./src/util/header.ts\");\n/* harmony import */ var _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../cache/IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../cache/WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\n/* harmony import */ var _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../cache/MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_header_js__WEBPACK_IMPORTED_MODULE_5__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_6__]);\n([_util_header_js__WEBPACK_IMPORTED_MODULE_5__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_6__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\nclass ElectrumNetworkProvider {\n get cache() {\n if (!_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseMemoryCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseLocalStorageCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseIndexedDBCache) {\n this._cache = undefined;\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseMemoryCache && !(this._cache instanceof _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_1__.MemoryCache)) {\n this._cache = new _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_1__.MemoryCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseLocalStorageCache &&\n !(this._cache instanceof _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_2__.WebStorageCache)) {\n this._cache = new _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_2__.WebStorageCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseIndexedDBCache && !(this._cache instanceof _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache)) {\n this._cache = new _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache();\n return this._cache;\n }\n return this._cache;\n }\n constructor(transport, network = _interface_js__WEBPACK_IMPORTED_MODULE_4__.Network.MAINNET) {\n this.network = network;\n this.subscriptions = 0;\n this.currentHeight = 0;\n if (transport) {\n this.transport = transport;\n }\n else {\n throw new Error(`A transport is required.`);\n }\n }\n async getUtxos(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.listunspent\", cashaddr, \"include_tokens\");\n return result.map((utxo) => ({\n address: cashaddr,\n txid: utxo.tx_hash,\n vout: utxo.tx_pos,\n satoshis: BigInt(utxo.value),\n height: utxo.height,\n token: utxo.token_data\n ? {\n ...utxo.token_data,\n amount: BigInt(utxo.token_data.amount),\n }\n : undefined,\n }));\n }\n async getBalance(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.get_balance\", cashaddr);\n return BigInt(result.confirmed) + BigInt(result.unconfirmed);\n }\n async getHeader(height, verbose = false) {\n const key = `header-${this.network}-${height}-${verbose}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_5__.decodeHeader)(JSON.parse(cached)) : JSON.parse(cached);\n }\n }\n const result = await this.performRequest(\"blockchain.header.get\", height);\n if (this.cache) {\n await this.cache.setItem(key, JSON.stringify(result));\n }\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_5__.decodeHeader)(result) : result;\n }\n async getRawTransactions(hashes) {\n if (hashes.length === 0)\n return new Map();\n const results = new Map();\n const keys = hashes.map((hash) => `txraw-${this.network}-${hash}`);\n // batch cache read\n let cached;\n if (this.cache) {\n cached = await this.cache.getItems(keys);\n }\n const misses = [];\n for (let i = 0; i < hashes.length; i++) {\n const val = cached?.get(keys[i]);\n if (val) {\n results.set(hashes[i], val);\n }\n else {\n misses.push(hashes[i]);\n }\n }\n if (misses.length > 0) {\n // rpckit automatically batches concurrent requests via BatchScheduler\n const fetched = await Promise.all(misses.map(async (hash) => {\n const tx = await this.performRequest(\"blockchain.transaction.get\", hash, false);\n return [hash, tx];\n }));\n // batch cache write\n if (this.cache) {\n const entries = fetched.map(([hash, tx]) => [\n `txraw-${this.network}-${hash}`,\n tx,\n ]);\n await this.cache.setItems(entries);\n }\n for (const [hash, tx] of fetched) {\n results.set(hash, tx);\n }\n }\n return results;\n }\n async getHeaders(heights) {\n if (heights.length === 0)\n return new Map();\n const results = new Map();\n const keys = heights.map((height) => `header-${this.network}-${height}-true`);\n // batch cache read\n let cached;\n if (this.cache) {\n cached = await this.cache.getItems(keys);\n }\n const misses = [];\n for (let i = 0; i < heights.length; i++) {\n const val = cached?.get(keys[i]);\n if (val) {\n results.set(heights[i], (0,_util_header_js__WEBPACK_IMPORTED_MODULE_5__.decodeHeader)(JSON.parse(val)));\n }\n else {\n misses.push(heights[i]);\n }\n }\n if (misses.length > 0) {\n // rpckit automatically batches concurrent requests via BatchScheduler\n const fetched = await Promise.all(misses.map(async (height) => {\n const result = await this.performRequest(\"blockchain.header.get\", height);\n return [height, result];\n }));\n // batch cache write\n if (this.cache) {\n const entries = fetched.map(([height, result]) => [\n `header-${this.network}-${height}-true`,\n JSON.stringify(result),\n ]);\n await this.cache.setItems(entries);\n }\n for (const [height, result] of fetched) {\n results.set(height, (0,_util_header_js__WEBPACK_IMPORTED_MODULE_5__.decodeHeader)(result));\n }\n }\n return results;\n }\n async getBlockHeight() {\n if (!this.headerCancelFn) {\n this.headerCancelFn = await this.subscribeToHeaders((header) => {\n if (header.height > this.currentHeight) {\n this.currentHeight = header.height;\n }\n });\n }\n if (!this.currentHeight) {\n throw new Error(\"Check failed for eventual inconsistency in subscription implementations.\");\n }\n return this.currentHeight;\n }\n async getRawTransaction(txHash, verbose = false, loadInputValues = false) {\n const nonVerboseKey = `txraw-${this.network}-${txHash}`;\n const verboseKey = `tx-${this.network}-${txHash}`;\n const key = verbose ? verboseKey : nonVerboseKey;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n if (!verbose) {\n return cached;\n }\n const cachedTx = JSON.parse(cached);\n if (cachedTx.confirmations > 0) {\n const currentHeight = await this.getBlockHeight();\n cachedTx.confirmations += currentHeight - cachedTx.fetchHeight;\n }\n const { fetchHeight: _, ...transaction } = cachedTx;\n if (loadInputValues) {\n return this.enrichWithInputValues(transaction);\n }\n return transaction;\n }\n }\n try {\n const result = await this.performRequest(\"blockchain.transaction.get\", txHash, verbose);\n if (!verbose) {\n const hex = result;\n if (this.cache) {\n await this.cache.setItem(key, hex);\n }\n return hex;\n }\n const cachedTx = result;\n cachedTx.confirmations ??= 0;\n cachedTx.fetchHeight = await this.getBlockHeight();\n if (this.cache) {\n await this.cache.setItem(key, JSON.stringify(cachedTx));\n }\n const { fetchHeight: _, ...transaction } = cachedTx;\n if (loadInputValues) {\n return this.enrichWithInputValues(transaction);\n }\n return transaction;\n }\n catch (error) {\n if (error.message.indexOf(\"No such mempool or blockchain transaction\") > -1)\n throw Error(`Could not decode transaction ${txHash}. It might not exist on the current blockchain (${this.network}).`);\n else\n throw error;\n }\n }\n async enrichWithInputValues(transaction) {\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.getRawTransactionObject(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n const enrichedVin = transaction.vin.map((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n return { ...input, ...output };\n });\n return { ...transaction, vin: enrichedVin };\n }\n async getRawTransactionObject(txHash, loadInputValues = false) {\n if (loadInputValues) {\n return this.getRawTransaction(txHash, true, true);\n }\n return this.getRawTransaction(txHash, true);\n }\n async sendRawTransaction(txHex, awaitPropagation = true) {\n return new Promise(async (resolve, reject) => {\n let txHash = await (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_6__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash && data[1] !== null) {\n await cancel?.();\n resolve(txHash);\n }\n };\n cancel = await this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch(async (error) => {\n await cancel?.();\n reject(error);\n });\n }\n });\n }\n // Get transaction history of a given cashaddr\n async getHistory(cashaddr, fromHeight = 0, toHeight = -1) {\n const result = await this.performRequest(\"blockchain.address.get_history\", cashaddr, fromHeight, toHeight);\n return result;\n }\n // Get the minimum fee a low-priority transaction must pay in order to be accepted to the daemon's memory pool.\n async getRelayFee() {\n const result = (await this.performRequest(\"blockchain.relayfee\"));\n return result;\n }\n async watchAddressStatus(cashaddr, callback) {\n const watchAddressStatusCallback = async (data) => {\n // subscription acknowledgement is the latest known status or null if no status is known\n // status is an array: [ cashaddr, statusHash ]\n if (data instanceof Array) {\n if (data[0] !== cashaddr) {\n return;\n }\n callback(data[1]);\n }\n };\n return this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n }\n // watch for block headers and block height, if `skipCurrentHeight` is set, the notification about current block will not arrive\n async watchBlocks(callback, skipCurrentHeight = true) {\n let acknowledged = !skipCurrentHeight;\n const waitForBlockCallback = (_header) => {\n if (!acknowledged) {\n acknowledged = true;\n return;\n }\n _header = _header instanceof Array ? _header[0] : _header;\n callback(_header);\n };\n return this.subscribeToHeaders(waitForBlockCallback);\n }\n // Wait for the next block or a block at given blockchain height.\n async waitForBlock(height) {\n return new Promise(async (resolve) => {\n let cancelWatch;\n if (this.currentHeight && !height) {\n height = this.currentHeight + 1;\n }\n cancelWatch = await this.watchBlocks(async (header) => {\n if (!height) {\n height = header.height + 1;\n return;\n }\n if (header.height >= height) {\n await cancelWatch?.();\n resolve(header);\n return;\n }\n });\n });\n }\n // subscribe to notifications sent when new block is found, the block header is sent to callback\n async subscribeToHeaders(callback) {\n return this.subscribeRequest(\"blockchain.headers.subscribe\", (data) => {\n callback(data[0] ?? data);\n });\n }\n async subscribeToAddress(cashaddr, callback) {\n return this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n return this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async performRequest(name, ...parameters) {\n await this.ready();\n const TIMEOUT_MSG = \"electrum-cash request timed out, retrying\";\n const makeTimeout = () => new Promise(function (_resolve, reject) {\n setTimeout(function () {\n reject(TIMEOUT_MSG);\n }, 30000);\n });\n const ensureError = (e) => {\n if (e instanceof Error)\n return e;\n if (typeof e === \"object\" && e !== null && \"message\" in e)\n return Object.assign(new Error(e.message), e);\n return new Error(typeof e === \"string\" ? e : String(e));\n };\n const request = this.transport.request(name, ...parameters);\n try {\n const value = await Promise.race([request, makeTimeout()]);\n if (value instanceof Error)\n throw value;\n return value;\n }\n catch (e) {\n const error = ensureError(e);\n // Only retry on timeout, not on server errors\n if (error.message !== TIMEOUT_MSG)\n throw error;\n try {\n const value = await Promise.race([request, makeTimeout()]);\n if (value instanceof Error)\n throw value;\n return value;\n }\n catch (e2) {\n throw ensureError(e2);\n }\n }\n }\n async subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const subscribeFn = this.transport.subscribe.bind(this.transport);\n const unsubscribe = await subscribeFn(methodName, ...parameters, (data) => {\n callback(data);\n });\n this.subscriptions++;\n return async () => {\n await unsubscribe();\n this.subscriptions--;\n };\n }\n async ready() {\n return this.connect();\n }\n async connect() {\n await this.cache?.init();\n await this.transport.connect();\n }\n async disconnect() {\n await this.headerCancelFn?.();\n await this.transport.close();\n return true;\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
248
218
 
249
219
  /***/ }),
250
220
 
@@ -254,7 +224,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
254
224
  \**************************************/
255
225
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
256
226
 
257
- 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 */ \"DefaultProvider\": () => (/* binding */ DefaultProvider),\n/* harmony export */ \"getDefaultServers\": () => (/* binding */ getDefaultServers),\n/* harmony export */ \"getUserAgent\": () => (/* binding */ getUserAgent)\n/* harmony export */ });\n/* unused harmony export getConfidence */\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constant.js */ \"./src/network/constant.ts\");\n\n\nlet mainnetServers, testnetServers, regtestServers;\nclass DefaultProvider {\n static { this.servers = {\n mainnet: [],\n testnet: [],\n regtest: [],\n }; }\n}\nfunction getDefaultServers(network) {\n let env;\n if ((0,_util_index_js__WEBPACK_IMPORTED_MODULE_0__.getRuntimePlatform)() == \"node\") {\n env = process.env;\n }\n else {\n env = {};\n }\n mainnetServers = DefaultProvider.servers.mainnet.length\n ? DefaultProvider.servers.mainnet\n : env.ELECTRUM\n ? env.ELECTRUM.split(\",\")\n : _constant_js__WEBPACK_IMPORTED_MODULE_1__.mainnetServers;\n testnetServers = DefaultProvider.servers.testnet.length\n ? DefaultProvider.servers.testnet\n : env.ELECTRUM_TESTNET\n ? env.ELECTRUM_TESTNET.split(\",\")\n : _constant_js__WEBPACK_IMPORTED_MODULE_1__.testnetServers;\n regtestServers = DefaultProvider.servers.regtest.length\n ? DefaultProvider.servers.regtest\n : env.ELECTRUM_REGTEST\n ? env.ELECTRUM_REGTEST.split(\",\")\n : _constant_js__WEBPACK_IMPORTED_MODULE_1__.regtestServers;\n return {\n mainnet: mainnetServers,\n testnet: testnetServers,\n regtest: regtestServers,\n }[network];\n}\nfunction getUserAgent() {\n // Allow users to configure the cluster confidence\n let ua;\n if ((0,_util_index_js__WEBPACK_IMPORTED_MODULE_0__.getRuntimePlatform)() === \"node\") {\n ua = process.env.ELECTRUM_USER_AGENT\n ? process.env.ELECTRUM_USER_AGENT\n : \"mainnet-js-\" + (0,_util_index_js__WEBPACK_IMPORTED_MODULE_0__.getRuntimePlatform)();\n }\n else {\n ua = \"mainnet-js-\" + (0,_util_index_js__WEBPACK_IMPORTED_MODULE_0__.getRuntimePlatform)();\n }\n return ua;\n}\nfunction getConfidence() {\n // Allow users to configure the cluster confidence\n let confidence;\n if ((0,_util_index_js__WEBPACK_IMPORTED_MODULE_0__.getRuntimePlatform)() === \"node\") {\n confidence = process.env.ELECTRUM_CONFIDENCE\n ? parseInt(process.env.ELECTRUM_CONFIDENCE)\n : 1;\n }\n else {\n confidence = 1;\n }\n return confidence;\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/configuration.ts?");
227
+ 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 */ \"DefaultProvider\": () => (/* binding */ DefaultProvider),\n/* harmony export */ \"getDefaultServers\": () => (/* binding */ getDefaultServers)\n/* harmony export */ });\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constant.js */ \"./src/network/constant.ts\");\n\n\nclass DefaultProvider {\n static { this.servers = {\n mainnet: \"\",\n testnet: \"\",\n regtest: \"\",\n }; }\n}\n// Detect plain comma-separated URLs (not already in parse notation like \"fallback(...)\") and convert\nfunction normalizeServers(value) {\n if (!value)\n return value;\n // Already parse notation (contains parens) or a single URL — pass through\n if (value.includes(\"(\") || !value.includes(\",\"))\n return value;\n // Plain comma-separated URLs: convert to parse notation with fallback\n return _constant_js__WEBPACK_IMPORTED_MODULE_0__.toParseNotation(value.split(\",\").map((s) => s.trim()));\n}\nfunction getDefaultServers(network) {\n let env;\n if ((0,_util_index_js__WEBPACK_IMPORTED_MODULE_1__.getRuntimePlatform)() == \"node\") {\n env = process.env;\n }\n else {\n env = {};\n }\n const servers = {\n mainnet: DefaultProvider.servers.mainnet ||\n normalizeServers(env.ELECTRUM) ||\n _constant_js__WEBPACK_IMPORTED_MODULE_0__.mainnetServers,\n testnet: DefaultProvider.servers.testnet ||\n normalizeServers(env.ELECTRUM_TESTNET) ||\n _constant_js__WEBPACK_IMPORTED_MODULE_0__.testnetServers,\n regtest: DefaultProvider.servers.regtest ||\n normalizeServers(env.ELECTRUM_REGTEST) ||\n _constant_js__WEBPACK_IMPORTED_MODULE_0__.regtestServers,\n };\n return servers[network];\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/configuration.ts?");
258
228
 
259
229
  /***/ }),
260
230
 
@@ -264,7 +234,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
264
234
  \*********************************/
265
235
  /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
266
236
 
267
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ELECTRUM_CASH_PROTOCOL_VERSION\": () => (/* binding */ ELECTRUM_CASH_PROTOCOL_VERSION),\n/* harmony export */ \"mainnetServers\": () => (/* binding */ mainnetServers),\n/* harmony export */ \"networkTickerMap\": () => (/* binding */ networkTickerMap),\n/* harmony export */ \"regtestServers\": () => (/* binding */ regtestServers),\n/* harmony export */ \"testnetServers\": () => (/* binding */ testnetServers)\n/* harmony export */ });\n/* unused harmony export defaultServers */\nconst ELECTRUM_CASH_PROTOCOL_VERSION = \"1.5\";\nconst networkTickerMap = {\n mainnet: \"BCH\",\n testnet: \"tBCH\",\n regtest: \"rBCH\",\n};\nconst mainnetServers = [\n // \"wss://bch.imaginary.cash:50004\",\n \"wss://blackie.c3-soft.com:50004\",\n // \"wss://electrum.imaginary.cash:50004\",\n // \"wss://fulcrum.fountainhead.cash\",\n];\n// export const testnetServers = [\n// // \"wss://tbch.loping.net:60004\",\n// \"wss://blackie.c3-soft.com:60004\",\n// // \"wss://testnet.bitcoincash.network:60004\",\n// //,\"wss://unavailable.invalid:50004\"\n// ];\n// testnet4\n// export const testnetServers = [\n// //\"wss://t4fork.c3-soft.com:61004\",\n// \"wss://testnet4.imaginary.cash:50004\",\n// //,\"wss://unavailable.invalid:50004\"\n// ];\n// chipnet\nconst testnetServers = [\n \"wss://chipnet.imaginary.cash:50004\",\n //\"wss://blackie.c3-soft.com:64004\", // chipnet with protocol 1.5.0\n // \"wss://chipnet.bch.ninja:50004\",\n];\nconst regtestServers = [\"ws://127.0.0.1:60003\"];\nconst defaultServers = {\n mainnet: mainnetServers,\n testnet: testnetServers,\n regtest: regtestServers,\n};\n\n\n//# sourceURL=webpack://mainnet-js/./src/network/constant.ts?");
237
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"mainnetServers\": () => (/* binding */ mainnetServers),\n/* harmony export */ \"networkTickerMap\": () => (/* binding */ networkTickerMap),\n/* harmony export */ \"regtestServers\": () => (/* binding */ regtestServers),\n/* harmony export */ \"testnetServers\": () => (/* binding */ testnetServers),\n/* harmony export */ \"toParseNotation\": () => (/* binding */ toParseNotation)\n/* harmony export */ });\n/* unused harmony export defaultServers */\nconst networkTickerMap = {\n mainnet: \"BCH\",\n testnet: \"tBCH\",\n regtest: \"rBCH\",\n};\nconst opts = \"connectTimeout=5000&timeout=5000&keepAlive=60000&protocolVersion=1.6&batchSize=5\";\nfunction toParseNotation(urls) {\n const withOpts = urls.map((u) => `${u}?${opts}`);\n if (withOpts.length === 1)\n return withOpts[0];\n return `fallback(${withOpts.join(\",\")})?eagerConnect=true&rank=true`;\n}\nconst mainnetServers = toParseNotation([\n \"wss://bch.imaginary.cash:50004\",\n \"wss://electrum.imaginary.cash:50004\",\n \"wss://fulcrum.pat.mn:50004\",\n]);\n// chipnet\nconst testnetServers = toParseNotation([\n \"wss://chipnet.bch.ninja:50004\",\n \"wss://chipnet.imaginary.cash:50004\",\n \"wss://chipnet.c3-soft.com:64004\",\n]);\nconst regtestServers = toParseNotation([\n \"ws://127.0.0.1:60003\",\n \"ws://host.docker.internal:60003\",\n]);\nconst defaultServers = {\n mainnet: mainnetServers,\n testnet: testnetServers,\n regtest: regtestServers,\n};\n\n\n//# sourceURL=webpack://mainnet-js/./src/network/constant.ts?");
268
238
 
269
239
  /***/ }),
270
240
 
@@ -274,7 +244,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
274
244
  \********************************/
275
245
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
276
246
 
277
- 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 */ \"getGlobalProvider\": () => (/* binding */ getGlobalProvider),\n/* harmony export */ \"getNetworkProvider\": () => (/* binding */ getNetworkProvider),\n/* harmony export */ \"removeGlobalProvider\": () => (/* binding */ removeGlobalProvider),\n/* harmony export */ \"setGlobalProvider\": () => (/* binding */ setGlobalProvider)\n/* harmony export */ });\n/* harmony import */ var _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./ElectrumNetworkProvider.js */ \"./src/network/ElectrumNetworkProvider.ts\");\n/* harmony import */ var _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @electrum-cash/network */ \"../../node_modules/@electrum-cash/network/dist/index.mjs\");\n/* harmony import */ var _electrum_cash_web_socket__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @electrum-cash/web-socket */ \"../../node_modules/@electrum-cash/web-socket/dist/index.mjs\");\n/* harmony import */ var _configuration_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./util.js */ \"./src/network/util.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constant.js */ \"./src/network/constant.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_configuration_js__WEBPACK_IMPORTED_MODULE_4__, _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_5__]);\n([_configuration_js__WEBPACK_IMPORTED_MODULE_4__, _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_5__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\nfunction setGlobalProvider(network, provider) {\n const accessor = _constant_js__WEBPACK_IMPORTED_MODULE_2__.networkTickerMap[network];\n globalThis[accessor] = provider;\n return provider;\n}\nfunction getGlobalProvider(network) {\n const accessor = _constant_js__WEBPACK_IMPORTED_MODULE_2__.networkTickerMap[network];\n return globalThis[accessor];\n}\nfunction removeGlobalProvider(network) {\n const accessor = _constant_js__WEBPACK_IMPORTED_MODULE_2__.networkTickerMap[network];\n if (accessor in globalThis) {\n delete globalThis[accessor];\n }\n}\nfunction getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_3__.Network.MAINNET, servers, manualConnectionManagement, options) {\n const globalContext = servers === undefined &&\n manualConnectionManagement === undefined &&\n options === undefined;\n if (globalContext) {\n const globalProvider = getGlobalProvider(network);\n if (globalProvider) {\n return globalProvider;\n }\n }\n manualConnectionManagement = manualConnectionManagement\n ? manualConnectionManagement\n : false;\n servers = servers ? servers : (0,_configuration_js__WEBPACK_IMPORTED_MODULE_4__.getDefaultServers)(network);\n // If the user has passed a single string, assume a single client connection\n if (typeof servers === \"string\") {\n servers = [servers];\n }\n // There were server(s)\n if (servers) {\n const client = getClient(servers[0], network, options);\n let provider = new _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_5__[\"default\"](client, network, manualConnectionManagement);\n if (globalContext) {\n return setGlobalProvider(network, provider);\n }\n return provider;\n }\n else {\n throw Error(\"No servers provided, defaults not available.\");\n }\n}\n// create a client with a server\nfunction getClient(server, network, options) {\n let url = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__.parseElectrumUrl)(server);\n return getElectrumClient(url, options?.timeout ?? 120000, network);\n}\nfunction getElectrumClient(params, timeout, network) {\n if (params.scheme?.includes(\"tcp\")) {\n throw Error(\"TCP connections are not supported.\");\n }\n const webSocket = new _electrum_cash_web_socket__WEBPACK_IMPORTED_MODULE_1__.ElectrumWebSocket(params.host, params.port, params.scheme === \"wss\", timeout, {\n disableBrowserConnectivityHandling: true,\n disableBrowserVisibilityHandling: true,\n });\n return new _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__.ElectrumClient((0,_configuration_js__WEBPACK_IMPORTED_MODULE_4__.getUserAgent)(), _constant_js__WEBPACK_IMPORTED_MODULE_2__.ELECTRUM_CASH_PROTOCOL_VERSION, webSocket, {\n disableBrowserConnectivityHandling: true,\n disableBrowserVisibilityHandling: true,\n });\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/default.ts?");
247
+ 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 */ \"createProvider\": () => (/* binding */ createProvider),\n/* harmony export */ \"getGlobalProvider\": () => (/* binding */ getGlobalProvider),\n/* harmony export */ \"getNetworkProvider\": () => (/* binding */ getNetworkProvider),\n/* harmony export */ \"removeGlobalProvider\": () => (/* binding */ removeGlobalProvider),\n/* harmony export */ \"setGlobalProvider\": () => (/* binding */ setGlobalProvider)\n/* harmony export */ });\n/* harmony import */ var _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ElectrumNetworkProvider.js */ \"./src/network/ElectrumNetworkProvider.ts\");\n/* harmony import */ var _configuration_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constant.js */ \"./src/network/constant.ts\");\n/* harmony import */ var _rpckit_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @rpckit/core */ \"../../node_modules/@rpckit/core/dist/parse.js\");\n/* harmony import */ var _rpckit_websocket_electrum_cash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @rpckit/websocket/electrum-cash */ \"../../node_modules/@rpckit/websocket/dist/electrum-cash/webSocket.js\");\n/* harmony import */ var _rpckit_fallback_electrum_cash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @rpckit/fallback/electrum-cash */ \"../../node_modules/@rpckit/fallback/dist/electrum-cash/fallback.js\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_configuration_js__WEBPACK_IMPORTED_MODULE_5__, _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_6__]);\n([_configuration_js__WEBPACK_IMPORTED_MODULE_5__, _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_6__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\nconst parseSync = (0,_rpckit_core__WEBPACK_IMPORTED_MODULE_0__.createParseSync)({ webSocket: _rpckit_websocket_electrum_cash__WEBPACK_IMPORTED_MODULE_1__.webSocket, fallback: _rpckit_fallback_electrum_cash__WEBPACK_IMPORTED_MODULE_2__.fallback });\nfunction setGlobalProvider(network, provider) {\n const accessor = _constant_js__WEBPACK_IMPORTED_MODULE_3__.networkTickerMap[network];\n globalThis[accessor] = provider;\n return provider;\n}\nfunction getGlobalProvider(network) {\n const accessor = _constant_js__WEBPACK_IMPORTED_MODULE_3__.networkTickerMap[network];\n return globalThis[accessor];\n}\nfunction removeGlobalProvider(network) {\n const accessor = _constant_js__WEBPACK_IMPORTED_MODULE_3__.networkTickerMap[network];\n if (accessor in globalThis) {\n delete globalThis[accessor];\n }\n}\nasync function createProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_4__.Network.MAINNET, servers) {\n const serverStr = servers ?? (0,_configuration_js__WEBPACK_IMPORTED_MODULE_5__.getDefaultServers)(network);\n const transport = parseSync(serverStr);\n return new _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_6__[\"default\"](transport, network);\n}\nfunction getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_4__.Network.MAINNET) {\n const globalProvider = getGlobalProvider(network);\n if (globalProvider) {\n return globalProvider;\n }\n const serverStr = (0,_configuration_js__WEBPACK_IMPORTED_MODULE_5__.getDefaultServers)(network);\n const transport = parseSync(serverStr);\n const provider = new _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_6__[\"default\"](transport, network);\n setGlobalProvider(network, provider);\n return provider;\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/default.ts?");
278
248
 
279
249
  /***/ }),
280
250
 
@@ -294,17 +264,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
294
264
  \******************************/
295
265
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
296
266
 
297
- 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 */ \"Connection\": () => (/* reexport safe */ _Connection_js__WEBPACK_IMPORTED_MODULE_1__.Connection),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"]),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _Connection_js__WEBPACK_IMPORTED_MODULE_1__.disconnectProviders),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider),\n/* harmony export */ \"initProvider\": () => (/* reexport safe */ _Connection_js__WEBPACK_IMPORTED_MODULE_1__.initProvider),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _Connection_js__WEBPACK_IMPORTED_MODULE_1__.initProviders)\n/* harmony export */ });\n/* harmony import */ var _default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./default.js */ \"./src/network/default.ts\");\n/* harmony import */ var _Connection_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Connection.js */ \"./src/network/Connection.ts\");\n/* harmony import */ var _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ElectrumNetworkProvider.js */ \"./src/network/ElectrumNetworkProvider.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_default_js__WEBPACK_IMPORTED_MODULE_0__, _Connection_js__WEBPACK_IMPORTED_MODULE_1__, _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_default_js__WEBPACK_IMPORTED_MODULE_0__, _Connection_js__WEBPACK_IMPORTED_MODULE_1__, _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/index.ts?");
298
-
299
- /***/ }),
300
-
301
- /***/ "./src/network/util.ts":
302
- /*!*****************************!*\
303
- !*** ./src/network/util.ts ***!
304
- \*****************************/
305
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
306
-
307
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"parseElectrumUrl\": () => (/* binding */ parseElectrumUrl)\n/* harmony export */ });\nfunction parseElectrumUrl(givenUrl) {\n let url = new URL(givenUrl);\n let port = parseInt(url.port || \"443\");\n let scheme = getElectrumScheme(url.protocol);\n return { host: url.hostname, port: port, scheme: scheme };\n}\nfunction getElectrumScheme(protocol) {\n let transport;\n switch (protocol) {\n case \"http:\":\n transport = \"tcp\";\n break;\n case \"https:\":\n transport = \"tcp_tls\";\n break;\n case \"ws:\":\n transport = \"ws\";\n break;\n case \"wss:\":\n transport = \"wss\";\n break;\n default:\n throw Error(\"Electrum transport protocol not understood.\");\n }\n return transport;\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/network/util.ts?");
267
+ 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 */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"]),\n/* harmony export */ \"createProvider\": () => (/* reexport safe */ _default_js__WEBPACK_IMPORTED_MODULE_0__.createProvider),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _Connection_js__WEBPACK_IMPORTED_MODULE_1__.disconnectProviders),\n/* harmony export */ \"getGlobalProvider\": () => (/* reexport safe */ _default_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalProvider),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider),\n/* harmony export */ \"initProvider\": () => (/* reexport safe */ _Connection_js__WEBPACK_IMPORTED_MODULE_1__.initProvider),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _Connection_js__WEBPACK_IMPORTED_MODULE_1__.initProviders),\n/* harmony export */ \"removeGlobalProvider\": () => (/* reexport safe */ _default_js__WEBPACK_IMPORTED_MODULE_0__.removeGlobalProvider),\n/* harmony export */ \"setGlobalProvider\": () => (/* reexport safe */ _default_js__WEBPACK_IMPORTED_MODULE_0__.setGlobalProvider)\n/* harmony export */ });\n/* harmony import */ var _default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./default.js */ \"./src/network/default.ts\");\n/* harmony import */ var _Connection_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Connection.js */ \"./src/network/Connection.ts\");\n/* harmony import */ var _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ElectrumNetworkProvider.js */ \"./src/network/ElectrumNetworkProvider.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_default_js__WEBPACK_IMPORTED_MODULE_0__, _Connection_js__WEBPACK_IMPORTED_MODULE_1__, _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_default_js__WEBPACK_IMPORTED_MODULE_0__, _Connection_js__WEBPACK_IMPORTED_MODULE_1__, _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/index.ts?");
308
268
 
309
269
  /***/ }),
310
270
 
@@ -634,7 +594,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
634
594
  \****************************/
635
595
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
636
596
 
637
- 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 */ \"_checkContextSafety\": () => (/* binding */ _checkContextSafety),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId),\n/* harmony export */ \"getStorageProvider\": () => (/* binding */ getStorageProvider),\n/* harmony export */ \"placeholderCashAddr\": () => (/* binding */ placeholderCashAddr),\n/* harmony export */ \"placeholderTokenAddr\": () => (/* binding */ placeholderTokenAddr)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../network/default.js */ \"./src/network/default.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 _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../message/signed.js */ \"./src/message/signed.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _model_js__WEBPACK_IMPORTED_MODULE_6__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__, _util_index_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_11__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__, _message_signed_js__WEBPACK_IMPORTED_MODULE_14__]);\n([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _model_js__WEBPACK_IMPORTED_MODULE_6__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__, _util_index_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_11__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__, _message_signed_js__WEBPACK_IMPORTED_MODULE_14__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst placeholderCashAddr = \"bitcoincash:qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqfnhks603\";\nconst placeholderTokenAddr = \"bitcoincash:zqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqweyg7usz\";\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n get networkPrefix() {\n return _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\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_3__.Util(this.network);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return new this().util;\n }\n // Return wallet info\n getInfo() {\n throw Error(\"getInfo not implemented in BaseWallet\");\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n return (0,_network_default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider)(network);\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.cashaddr;\n throw Error(\"getDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getChangeAddress - get a wallet change address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/changeAddress|/wallet/change_address} for REST endpoint\n *\n * @returns The change address as a string\n */\n getChangeAddress() {\n // return this.cashaddr;\n throw Error(\"getChangeAddress not implemented in BaseWallet\");\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 throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenChangeAddress() {\n // return this.tokenaddr;\n throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n // check if a given address belongs to this wallet\n hasAddress(address) {\n return (address === this.getDepositAddress() ||\n address === this.getChangeAddress());\n }\n //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\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.name = \"\";\n this.cancelFns = [];\n this.network = network;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? false : true;\n this.walletCache = new Map();\n }\n //#endregion Constructors\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 : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n const db = getStorageProvider(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n const 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 const recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n const wallet = await this.initialize();\n wallet.name = name;\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 : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = 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 : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = 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 async initialize() {\n return this;\n }\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 return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\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 return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n //#endregion Serialization\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 /**\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 fromId(walletId) {\n throw Error(\"fromId not implemented in BaseWallet\");\n }\n //#region Funds\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n throw Error(\"getUtxos not implemented in BaseWallet\");\n }\n // Gets balance by summing value in all utxos in sats\n // Balance includes DUST utxos which could be slp tokens and also cashtokens with BCH amounts\n async getBalance() {\n throw Error(\"getBalance not implemented in BaseWallet\");\n }\n /**\n * Track a cancel function so it can be cancelled by stop()\n * Returns a wrapped cancel function that also removes itself from tracking\n */\n trackCancelFn(cancelFn) {\n this.cancelFns.push(cancelFn);\n return async () => {\n const index = this.cancelFns.indexOf(cancelFn);\n if (index !== -1) {\n this.cancelFns.splice(index, 1);\n }\n await cancelFn();\n };\n }\n /**\n * Stop all active subscriptions on this wallet\n */\n async stop() {\n const fns = this.cancelFns.splice(0);\n await Promise.all(fns.map((fn) => fn()));\n }\n /**\n * Watch wallet for any activity (status changes)\n * This is the foundation for watchWalletBalance and watchWalletTransactions\n * @param callback - Called when the wallet has a status change\n * @returns Cancel function to stop watching\n */\n async watchStatus(callback) {\n const cancelFn = await this.provider.watchAddressStatus(this.getDepositAddress(), (status) => callback(status, this.getDepositAddress()));\n return this.trackCancelFn(cancelFn);\n }\n /**\n * No-op for single-address wallets. HDWallet overrides this to wait for\n * depositIndex/changeIndex advancement.\n */\n async waitForUpdate(_options = {}) { }\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 async watchBalance(callback) {\n return this.watchStatus(async () => {\n const balance = await this.getBalance();\n callback(balance);\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) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchBalance(async (balance) => {\n if (balance >= value) {\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 async watchTokenBalance(category, callback) {\n return await this.watchStatus(async () => {\n const balance = await this.getTokenBalance(category);\n callback(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(category, amount) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchTokenBalance(category, async (balance) => {\n if (balance >= amount) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n /**\n * Watch wallet for new transactions\n * @param callback - Called with new transaction hashes when they appear\n * @returns Cancel function to stop watching\n */\n async watchTransactionHashes(callback) {\n const seenTxHashes = new Set();\n let topHeight = 0;\n return this.watchStatus(async () => {\n const history = (await this.getRawHistory(topHeight)).sort((a, b) => a.height <= 0 || b.height <= 0 ? -1 : b.height - a.height);\n const newTxHashes = [];\n for (const tx of history) {\n if (tx.height > topHeight) {\n topHeight = tx.height;\n }\n if (!seenTxHashes.has(tx.tx_hash)) {\n seenTxHashes.add(tx.tx_hash);\n newTxHashes.push(tx.tx_hash);\n }\n }\n if (newTxHashes.length > 0) {\n newTxHashes.forEach((txHash) => callback(txHash));\n }\n });\n }\n /**\n * Watch wallet for new transactions\n * @param callback - Called with new transaction hashes when they appear\n * @returns Cancel function to stop watching\n */\n async watchTransactions(callback) {\n return this.watchTransactionHashes(async (txHash) => {\n const tx = await this.provider.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n async watchTokenTransactions(callback) {\n return this.watchTransactions(async (transaction) => {\n if (transaction.vout.some((val) => val.tokenData)) {\n callback(transaction);\n }\n });\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\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_4__.FeePaidByEnum.change;\n }\n // get inputs\n let utxos;\n const allUtxos = await this.getUtxos();\n if (params.options && params.options.utxoIds) {\n utxos = (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_5__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_6__.fromUtxoId)(utxoId) : utxoId), allUtxos);\n }\n else {\n utxos = allUtxos.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_6__.SendRequest({\n cashaddr: placeholderCashAddr,\n value: 100n,\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__.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_7__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: placeholderCashAddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_8__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0n) {\n result = 0n;\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 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, categories, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_6__.SendResponse({});\n resp.categories = categories;\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_9__.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, privateKey) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n privateKey: privateKey,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_6__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n });\n const { encodedTransaction, categories, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options, privateKey);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_6__.SendResponse({});\n resp.categories = categories;\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_9__.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, privateKey) {\n let sendRequests = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_10__.asSendRequestObject)(requests);\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options?.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_4__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options?.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.getChangeAddress();\n }\n let checkTokenQuantities = true;\n if (options?.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos = await this.getUtxos();\n if (options && options.utxoIds) {\n utxos = (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_5__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_6__.fromUtxoId)(utxoId) : utxoId), utxos);\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_6__.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_6__.TokenSendRequest);\n const categories = allTokenOutputs\n .map((val) => val.category)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let category of categories) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.category === category);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0n);\n const tokenOutputs = allTokenOutputs.filter((val) => val.category === category);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0n);\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 = 0n;\n let change = 0n;\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_6__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n amount: change,\n category: category,\n nft: tokenOutputs[0].nft,\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_12__.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_7__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__.getSuitableUtxos)(utxos, spendAmount + 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_7__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n walletCache: this.walletCache,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: privateKey ?? _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__.placeholderPrivateKeyBin,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n walletCache: this.walletCache,\n });\n const categories = [\n ...fundingUtxos\n .filter((val) => val.token?.category)\n .map((val) => val.token.category),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_6__.TokenSendRequest)\n .map((val) => val.category),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, categories, sourceOutputs };\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_9__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory(fromHeight = 0, toHeight = -1) {\n throw Error(\"getRawHistory not implemented in BaseWallet\");\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 let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash && data[1] !== null) {\n txHashSeen = true;\n await cancel?.();\n resolve(makeResponse(options.txHash));\n }\n };\n cancel = await this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n let watchCancel;\n let initialResponseSeen = false;\n watchCancel = await this.watchStatus(async (_status) => {\n if (initialResponseSeen) {\n await watchCancel?.();\n resolve(makeResponse());\n return;\n }\n initialResponseSeen = true;\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n * @param skipCurrentHeight if set, the notification about current block will not arrive\n *\n * @returns a function which will cancel watching upon evaluation\n */\n async watchBlocks(callback, skipCurrentHeight = true) {\n return this.provider.watchBlocks(callback, skipCurrentHeight);\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 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 = await this.getUtxos();\n if (options?.utxoIds) {\n utxos = (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_5__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_6__.fromUtxoId)(utxoId) : utxoId), utxos);\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_6__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.getTokenDepositAddress(),\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000n,\n nft: genesisRequest.nft,\n category: 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} category category 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(category, mintRequests, deductTokenAmount = false, options) {\n if (category?.length !== 64) {\n throw Error(`Invalid category supplied: ${category}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getUtxos();\n const nftUtxos = utxos.filter((val) => val.token?.category === category &&\n val.token?.nft?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_13__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified category\");\n }\n const newAmount = deductTokenAmount && nftUtxos[0].token.amount > 0\n ? nftUtxos[0].token.amount - BigInt(mintRequests.length)\n : nftUtxos[0].token.amount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_6__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(nftUtxos[0].address),\n category: category,\n nft: nftUtxos[0].token?.nft,\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_6__.TokenSendRequest({\n cashaddr: val.cashaddr || this.getTokenDepositAddress(),\n amount: 0n,\n category: category,\n value: val.value,\n nft: val.nft,\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.category category 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.category?.length !== 64) {\n throw Error(`Invalid category supplied: ${burnRequest.category}`);\n }\n const utxos = await this.getUtxos();\n const tokenUtxos = utxos.filter((val) => val.token?.category === burnRequest.category &&\n val.token?.nft?.capability === burnRequest.nft?.capability &&\n val.token?.nft?.commitment === burnRequest.nft?.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 || 0n), 0n);\n let fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0n;\n fungibleBurnAmount = BigInt(fungibleBurnAmount);\n const hasNFT = burnRequest.nft !== undefined;\n let utxoIds = [];\n let changeSendRequests;\n if (hasNFT) {\n // does not have FT tokens, let us destroy the token completely\n if (totalFungibleAmount === 0n) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0n;\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 = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_6__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n category: burnRequest.category,\n nft: burnRequest.nft,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last fungible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(...tokenUtxos);\n }\n else {\n // add utxos to spend from\n let available = 0n;\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 = available - fungibleBurnAmount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_6__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n category: burnRequest.category,\n amount: safeNewAmount,\n value: tokenUtxos.reduce((a, c) => a + c.satoshis, 0n),\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_6__.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 `category` provided\n * @param {string?} category category to filter utxos by, if not set will return utxos from all tokens\n * @returns {Utxo[]} token utxos\n */\n async getTokenUtxos(category) {\n const utxos = await this.getUtxos();\n return utxos.filter((val) => category ? val.token?.category === category : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} category category to get balance for\n * @returns {bigint} fungible token balance\n */\n async getTokenBalance(category) {\n const utxos = (await this.getTokenUtxos(category)).filter((val) => val.token?.amount);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_8__.sumTokenAmounts)(utxos, category);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particular category\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} category category to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(category) {\n const utxos = (await this.getTokenUtxos(category)).filter((val) => val.token?.nft?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [category => 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.category]) {\n result[utxo.token.category] = 0n;\n }\n result[utxo.token.category] += 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 [category => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.nft?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.category]) {\n result[utxo.token.category] = 0;\n }\n result[utxo.token.category] += 1;\n }\n return result;\n }\n //#endregion Cashtokens\n sign(message, privateKey = undefined) {\n if (!privateKey) {\n throw new Error(\"Signing private key not provided\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_14__.SignedMessage().sign(message, privateKey);\n }\n // Convenience wrapper to verify interface\n verify(message, sig, address, publicKey) {\n if (!address && !publicKey) {\n throw new Error(\"Either address or publicKey must be provided for verification\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_14__.SignedMessage().verify(message, sig, address, publicKey);\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_index_js__WEBPACK_IMPORTED_MODULE_15__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.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 = 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}\nfunction getStorageProvider(dbName) {\n if (!BaseWallet.StorageProvider) {\n return undefined;\n }\n return new BaseWallet.StorageProvider(dbName);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
597
+ 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 */ \"_checkContextSafety\": () => (/* binding */ _checkContextSafety),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId),\n/* harmony export */ \"getStorageProvider\": () => (/* binding */ getStorageProvider),\n/* harmony export */ \"placeholderCashAddr\": () => (/* binding */ placeholderCashAddr),\n/* harmony export */ \"placeholderTokenAddr\": () => (/* binding */ placeholderTokenAddr)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../network/default.js */ \"./src/network/default.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 _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../message/signed.js */ \"./src/message/signed.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _model_js__WEBPACK_IMPORTED_MODULE_6__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__, _util_index_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_11__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__, _message_signed_js__WEBPACK_IMPORTED_MODULE_14__]);\n([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _model_js__WEBPACK_IMPORTED_MODULE_6__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__, _util_index_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_11__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__, _message_signed_js__WEBPACK_IMPORTED_MODULE_14__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst placeholderCashAddr = \"bitcoincash:qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqfnhks603\";\nconst placeholderTokenAddr = \"bitcoincash:zqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqweyg7usz\";\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n get networkPrefix() {\n return _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\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_3__.Util(this.network);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return new this().util;\n }\n // Return wallet info\n getInfo() {\n throw Error(\"getInfo not implemented in BaseWallet\");\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n return (0,_network_default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider)(network);\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.cashaddr;\n throw Error(\"getDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getChangeAddress - get a wallet change address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/changeAddress|/wallet/change_address} for REST endpoint\n *\n * @returns The change address as a string\n */\n getChangeAddress() {\n // return this.cashaddr;\n throw Error(\"getChangeAddress not implemented in BaseWallet\");\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 throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenChangeAddress() {\n // return this.tokenaddr;\n throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n // check if a given address belongs to this wallet\n hasAddress(address) {\n return (address === this.getDepositAddress() ||\n address === this.getChangeAddress());\n }\n //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\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.name = \"\";\n this.cancelFns = [];\n this.network = network;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? false : true;\n this.walletCache = new Map();\n }\n //#endregion Constructors\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 : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n const db = getStorageProvider(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n const 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 const recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n const wallet = await this.initialize();\n wallet.name = name;\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 : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = 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 : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = 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 async initialize() {\n return this;\n }\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 return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\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 return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n //#endregion Serialization\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 /**\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 fromId(walletId) {\n throw Error(\"fromId not implemented in BaseWallet\");\n }\n //#region Funds\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n throw Error(\"getUtxos not implemented in BaseWallet\");\n }\n // Gets balance by summing value in all utxos in sats\n // Balance includes DUST utxos which could be slp tokens and also cashtokens with BCH amounts\n async getBalance() {\n throw Error(\"getBalance not implemented in BaseWallet\");\n }\n /**\n * Track a cancel function so it can be cancelled by stop()\n * Returns a wrapped cancel function that also removes itself from tracking\n */\n trackCancelFn(cancelFn) {\n this.cancelFns.push(cancelFn);\n return async () => {\n const index = this.cancelFns.indexOf(cancelFn);\n if (index !== -1) {\n this.cancelFns.splice(index, 1);\n }\n await cancelFn();\n };\n }\n /**\n * Stop all active subscriptions on this wallet\n */\n async stop() {\n const fns = this.cancelFns.splice(0);\n await Promise.all(fns.map((fn) => fn()));\n }\n /**\n * Watch wallet for any activity (status changes)\n * This is the foundation for watchWalletBalance and watchWalletTransactions\n * @param callback - Called when the wallet has a status change\n * @returns Cancel function to stop watching\n */\n async watchStatus(callback) {\n const cancelFn = await this.provider.watchAddressStatus(this.getDepositAddress(), (status) => callback(status, this.getDepositAddress()));\n return this.trackCancelFn(cancelFn);\n }\n /**\n * No-op for single-address wallets. HDWallet overrides this to wait for\n * depositIndex/changeIndex advancement.\n */\n async waitForUpdate(_options = {}) { }\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 async watchBalance(callback) {\n return this.watchStatus(async () => {\n const balance = await this.getBalance();\n callback(balance);\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) {\n // Check if condition is already met before watching\n const currentBalance = await this.getBalance();\n if (currentBalance >= value) {\n return currentBalance;\n }\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchBalance(async (balance) => {\n if (balance >= value) {\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 async watchTokenBalance(category, callback) {\n return await this.watchStatus(async () => {\n const balance = await this.getTokenBalance(category);\n callback(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(category, amount) {\n // Check if condition is already met before watching\n const currentBalance = await this.getTokenBalance(category);\n if (currentBalance >= amount) {\n return currentBalance;\n }\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchTokenBalance(category, async (balance) => {\n if (balance >= amount) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n /**\n * Watch wallet for new transactions\n * @param callback - Called with new transaction hashes when they appear\n * @returns Cancel function to stop watching\n */\n async watchTransactionHashes(callback) {\n const seenTxHashes = new Set();\n let topHeight = 0;\n return this.watchStatus(async () => {\n const history = (await this.getRawHistory(topHeight)).sort((a, b) => a.height <= 0 || b.height <= 0 ? -1 : b.height - a.height);\n const newTxHashes = [];\n for (const tx of history) {\n if (tx.height > topHeight) {\n topHeight = tx.height;\n }\n if (!seenTxHashes.has(tx.tx_hash)) {\n seenTxHashes.add(tx.tx_hash);\n newTxHashes.push(tx.tx_hash);\n }\n }\n if (newTxHashes.length > 0) {\n newTxHashes.forEach((txHash) => callback(txHash));\n }\n });\n }\n /**\n * Watch wallet for new transactions\n * @param callback - Called with new transaction hashes when they appear\n * @returns Cancel function to stop watching\n */\n async watchTransactions(callback) {\n return this.watchTransactionHashes(async (txHash) => {\n const tx = await this.provider.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n async watchTokenTransactions(callback) {\n return this.watchTransactions(async (transaction) => {\n if (transaction.vout.some((val) => val.tokenData)) {\n callback(transaction);\n }\n });\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\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_4__.FeePaidByEnum.change;\n }\n // get inputs\n let utxos;\n const allUtxos = await this.getUtxos();\n if (params.options && params.options.utxoIds) {\n utxos = (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_5__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_6__.fromUtxoId)(utxoId) : utxoId), allUtxos);\n }\n else {\n utxos = allUtxos.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_6__.SendRequest({\n cashaddr: placeholderCashAddr,\n value: 100n,\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__.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_7__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: placeholderCashAddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_8__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0n) {\n result = 0n;\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 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, categories, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_6__.SendResponse({});\n resp.categories = categories;\n if (options?.buildUnsigned !== true) {\n const awaitPropagation = options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true;\n let updatePromise;\n if (awaitPropagation) {\n updatePromise = this.waitForUpdate({ timeout: 2500 });\n }\n const [_, txId] = await Promise.all([\n updatePromise,\n this.submitTransaction(encodedTransaction, awaitPropagation),\n ]);\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_9__.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, privateKey) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n privateKey: privateKey,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_6__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n });\n const { encodedTransaction, categories, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options, privateKey);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_6__.SendResponse({});\n resp.categories = categories;\n if (options?.buildUnsigned !== true) {\n const awaitPropagation = options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true;\n let updatePromise;\n if (awaitPropagation) {\n updatePromise = this.waitForUpdate({ timeout: 2500 });\n }\n const [_, txId] = await Promise.all([\n updatePromise,\n this.submitTransaction(encodedTransaction, awaitPropagation),\n ]);\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_9__.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, privateKey) {\n let sendRequests = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_10__.asSendRequestObject)(requests);\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options?.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_4__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options?.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.getChangeAddress();\n }\n let checkTokenQuantities = true;\n if (options?.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos = await this.getUtxos();\n if (options && options.utxoIds) {\n utxos = (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_5__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_6__.fromUtxoId)(utxoId) : utxoId), utxos);\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_6__.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_6__.TokenSendRequest);\n const categories = allTokenOutputs\n .map((val) => val.category)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let category of categories) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.category === category);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0n);\n const tokenOutputs = allTokenOutputs.filter((val) => val.category === category);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0n);\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 = 0n;\n let change = 0n;\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_6__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n amount: change,\n category: category,\n nft: tokenOutputs[0].nft,\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_12__.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_7__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__.getSuitableUtxos)(utxos, spendAmount + 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_7__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n walletCache: this.walletCache,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: privateKey ?? _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_7__.placeholderPrivateKeyBin,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n walletCache: this.walletCache,\n });\n const categories = [\n ...fundingUtxos\n .filter((val) => val.token?.category)\n .map((val) => val.token.category),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_6__.TokenSendRequest)\n .map((val) => val.category),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, categories, sourceOutputs };\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_9__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory(fromHeight = 0, toHeight = -1) {\n throw Error(\"getRawHistory not implemented in BaseWallet\");\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 let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash && data[1] !== null) {\n txHashSeen = true;\n await cancel?.();\n resolve(makeResponse(options.txHash));\n }\n };\n cancel = await this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n let watchCancel;\n watchCancel = await this.watchStatus(async (_status) => {\n await watchCancel?.();\n resolve(makeResponse());\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n * @param skipCurrentHeight if set, the notification about current block will not arrive\n *\n * @returns a function which will cancel watching upon evaluation\n */\n async watchBlocks(callback, skipCurrentHeight = true) {\n return this.provider.watchBlocks(callback, skipCurrentHeight);\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 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 = await this.getUtxos();\n if (options?.utxoIds) {\n utxos = (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_5__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_6__.fromUtxoId)(utxoId) : utxoId), utxos);\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_6__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.getTokenDepositAddress(),\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000n,\n nft: genesisRequest.nft,\n category: 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} category category 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(category, mintRequests, deductTokenAmount = false, options) {\n if (category?.length !== 64) {\n throw Error(`Invalid category supplied: ${category}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getUtxos();\n const nftUtxos = utxos.filter((val) => val.token?.category === category &&\n val.token?.nft?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_13__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified category\");\n }\n const newAmount = deductTokenAmount && nftUtxos[0].token.amount > 0\n ? nftUtxos[0].token.amount - BigInt(mintRequests.length)\n : nftUtxos[0].token.amount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_6__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(nftUtxos[0].address),\n category: category,\n nft: nftUtxos[0].token?.nft,\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_6__.TokenSendRequest({\n cashaddr: val.cashaddr || this.getTokenDepositAddress(),\n amount: 0n,\n category: category,\n value: val.value,\n nft: val.nft,\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.category category 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.category?.length !== 64) {\n throw Error(`Invalid category supplied: ${burnRequest.category}`);\n }\n const utxos = await this.getUtxos();\n const tokenUtxos = utxos.filter((val) => val.token?.category === burnRequest.category &&\n val.token?.nft?.capability === burnRequest.nft?.capability &&\n val.token?.nft?.commitment === burnRequest.nft?.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 || 0n), 0n);\n let fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0n;\n fungibleBurnAmount = BigInt(fungibleBurnAmount);\n const hasNFT = burnRequest.nft !== undefined;\n let utxoIds = [];\n let changeSendRequests;\n if (hasNFT) {\n // does not have FT tokens, let us destroy the token completely\n if (totalFungibleAmount === 0n) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0n;\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 = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_6__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n category: burnRequest.category,\n nft: burnRequest.nft,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last fungible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(...tokenUtxos);\n }\n else {\n // add utxos to spend from\n let available = 0n;\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 = available - fungibleBurnAmount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_6__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n category: burnRequest.category,\n amount: safeNewAmount,\n value: tokenUtxos.reduce((a, c) => a + c.satoshis, 0n),\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_6__.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 `category` provided\n * @param {string?} category category to filter utxos by, if not set will return utxos from all tokens\n * @returns {Utxo[]} token utxos\n */\n async getTokenUtxos(category) {\n const utxos = await this.getUtxos();\n return utxos.filter((val) => category ? val.token?.category === category : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} category category to get balance for\n * @returns {bigint} fungible token balance\n */\n async getTokenBalance(category) {\n const utxos = (await this.getTokenUtxos(category)).filter((val) => val.token?.amount && val.token?.category === category);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_8__.sumTokenAmounts)(utxos, category);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particular category\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} category category to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(category) {\n const utxos = (await this.getTokenUtxos(category)).filter((val) => val.token?.nft?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [category => 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.category]) {\n result[utxo.token.category] = 0n;\n }\n result[utxo.token.category] += 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 [category => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.nft?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.category]) {\n result[utxo.token.category] = 0;\n }\n result[utxo.token.category] += 1;\n }\n return result;\n }\n //#endregion Cashtokens\n sign(message, privateKey = undefined) {\n if (!privateKey) {\n throw new Error(\"Signing private key not provided\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_14__.SignedMessage().sign(message, privateKey);\n }\n // Convenience wrapper to verify interface\n verify(message, sig, address, publicKey) {\n if (!address && !publicKey) {\n throw new Error(\"Either address or publicKey must be provided for verification\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_14__.SignedMessage().verify(message, sig, address, publicKey);\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_index_js__WEBPACK_IMPORTED_MODULE_15__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.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 = 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}\nfunction getStorageProvider(dbName) {\n if (!BaseWallet.StorageProvider) {\n return undefined;\n }\n return new BaseWallet.StorageProvider(dbName);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
638
598
 
639
599
  /***/ }),
640
600
 
@@ -644,7 +604,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
644
604
  \********************************/
645
605
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
646
606
 
647
- 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 */ \"GAP_SIZE\": () => (/* binding */ GAP_SIZE),\n/* harmony export */ \"HDWallet\": () => (/* binding */ HDWallet),\n/* harmony export */ \"RegTestHDWallet\": () => (/* binding */ RegTestHDWallet),\n/* harmony export */ \"TestNetHDWallet\": () => (/* binding */ TestNetHDWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/bip39.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __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/utf8.js\");\n/* harmony import */ var _cache_index_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../cache/index.js */ \"./src/cache/walletCache.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _history_getHistory_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../history/getHistory.js */ \"./src/history/getHistory.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _util_hd_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/hd.js */ \"./src/util/hd.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _cache_index_js__WEBPACK_IMPORTED_MODULE_12__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_16__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _cache_index_js__WEBPACK_IMPORTED_MODULE_12__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_16__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\nconst GAP_SIZE = 20;\nclass HDWallet extends _Base_js__WEBPACK_IMPORTED_MODULE_0__.BaseWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.mainnet; }\n get networkPrefix() {\n return _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n }\n /// Create an uninitialized HDWallet, this method should not be called directly\n /// Instead static methods such as `newRandom` or `fromSeed` should be used\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n super(network);\n this.derivation = _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath;\n // Callback type for wallet activity watching\n this.walletWatchCallbacks = [];\n // max index used for deposit address derivation\n this.depositIndex = 0;\n // max index used for change address derivation\n this.changeIndex = 0;\n this.depositWatchCancels = [];\n this.changeWatchCancels = [];\n this.depositStatuses = [];\n this.changeStatuses = [];\n this.depositUtxos = [];\n this.changeUtxos = [];\n this.depositRawHistory = [];\n this.changeRawHistory = [];\n this.watchPromise = undefined;\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Hd;\n }\n /// Initialize the wallet given the options mnemonic, xPriv or xPub\n /// If none provided, a new random mnemonic will be generated\n /// If mnemonic or xPriv provided, the wallet will be able to sign transactions\n /// If xPub provided, the wallet will be watch-only\n /// This internal method is called by the various static constructors\n async initialize({ name = \"\", depositIndex = 0, changeIndex = 0, mnemonic = undefined, derivation = undefined, xPriv = undefined, xPub = undefined, } = {}) {\n // newRandom\n if (!xPriv && !xPub && !mnemonic) {\n mnemonic = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.generateBip39Mnemonic)();\n }\n this.depositIndex = depositIndex;\n this.changeIndex = changeIndex;\n // @ts-ignore\n this.xPub = xPub ? xPub : \"\";\n if (mnemonic?.length) {\n // @ts-ignore\n this.derivation = derivation\n ? derivation\n : _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath;\n // @ts-ignore\n this.mnemonic = mnemonic ? mnemonic : (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.generateBip39Mnemonic)();\n if (this.mnemonic.length == 0) {\n throw Error(\"refusing to create wallet from empty mnemonic\");\n }\n if (![12, 24].includes(this.mnemonic.split(\" \").length)) {\n throw Error(\"Invalid mnemonic, must be 12 or 24 words\");\n }\n const seed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.deriveSeedFromBip39Mnemonic)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_6__.checkForEmptySeed)(seed);\n const rootNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true,\n throwErrors: true,\n });\n const node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.deriveHdPath)(rootNode, this.derivation);\n // @ts-ignore\n this.xPriv = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.encodeHdPrivateKey)({\n ...node,\n network: this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\",\n node: node,\n })).hdPrivateKey;\n // @ts-ignore\n this.xPrivNode = node;\n // @ts-ignore\n this.xPubNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.deriveHdPublicNode)(node);\n // @ts-ignore\n this.xPub = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.encodeHdPublicKey)({\n node: this.xPubNode,\n network: this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\",\n })).hdPublicKey;\n }\n else if (xPriv) {\n // @ts-ignore\n this.xPriv = xPriv;\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.decodeHdPrivateKey)(xPriv));\n if (decoded.network !==\n (this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\")) {\n throw new Error(`xPriv network (${decoded.network}) does not match wallet network (${this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\"})`);\n }\n // @ts-ignore\n this.xPrivNode = decoded.node;\n // @ts-ignore\n this.xPubNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.deriveHdPublicNode)(decoded.node);\n // @ts-ignore\n this.xPub = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.encodeHdPublicKey)({\n node: this.xPubNode,\n network: this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\",\n })).hdPublicKey;\n }\n else if (xPub) {\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.decodeHdPublicKey)(xPub));\n if (decoded.network !==\n (this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\")) {\n throw new Error(`xPriv network (${decoded.network}) does not match wallet network (${this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\"})`);\n }\n // @ts-ignore\n this.xPubNode = decoded.node;\n // @ts-ignore\n this.xPub = xPub;\n }\n else {\n throw new Error(\"mnemonic, xPriv or xPub must be provided to create an HDWallet\");\n }\n this.name = name;\n // @ts-ignore\n this.walletId = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.sha256.hash((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.utf8ToBin)(`${(this.mnemonic ? this.mnemonic + this.derivation : undefined) ??\n this.xPriv ??\n this.xPub}-${this.network}`)));\n // @ts-ignore\n this.walletCache = new _cache_index_js__WEBPACK_IMPORTED_MODULE_12__.PersistentWalletCache(this.walletId, this.xPrivNode ?? this.xPubNode, this.networkPrefix);\n // init wallet cache\n await this.walletCache.init();\n // start watching addresses asynchronously\n this.watchPromise = this.makeWatchPromise().catch(() => { });\n return this;\n }\n /// Stops the wallet from watching for address changes\n /// After calling this method, the wallet will no longer update and is considered defunct\n async stop() {\n await Promise.all([\n super.stop(),\n ...this.depositWatchCancels.map((fn) => fn?.()),\n ...this.changeWatchCancels.map((fn) => fn?.()),\n ]);\n this.depositWatchCancels = [];\n this.changeWatchCancels = [];\n this.walletWatchCallbacks = [];\n }\n /// Scan more addresses for activity beyond the current gap limit, extending the watched range as needed\n async scanMoreAddresses(amount = GAP_SIZE) {\n await this.watchPromise;\n this.watchPromise = this.makeWatchPromise(amount);\n await this.watchPromise;\n }\n /// Internal method to start watching addresses for activity, extending the watched range as needed\n async makeWatchPromise(gapSize = GAP_SIZE) {\n await this.watchPromise;\n let needsMore = true;\n while (needsMore) {\n await Promise.all([\n this.watchAddressType(false, gapSize),\n this.watchAddressType(true, gapSize),\n ]);\n // Check if we have a full gap of addresses beyond the last used index\n const depositGap = this.depositStatuses.length - this.depositIndex;\n const changeGap = this.changeStatuses.length - this.changeIndex;\n needsMore = depositGap < gapSize || changeGap < gapSize;\n }\n }\n /// Watch addresses of a specific type (deposit or change) for activity\n async watchAddressType(isChange, gapSize) {\n // Select the appropriate arrays based on address type\n const statuses = isChange ? this.changeStatuses : this.depositStatuses;\n const utxosArray = isChange ? this.changeUtxos : this.depositUtxos;\n const historyArray = isChange\n ? this.changeRawHistory\n : this.depositRawHistory;\n const watchCancels = isChange\n ? this.changeWatchCancels\n : this.depositWatchCancels;\n const getCurrentIndex = () => isChange ? this.changeIndex : this.depositIndex;\n const setCurrentIndex = (val) => {\n if (isChange) {\n this.changeIndex = val;\n }\n else {\n this.depositIndex = val;\n }\n };\n const startIndex = statuses.length;\n const stopIndex = getCurrentIndex() + gapSize;\n const addresses = (0,_util_hd_js__WEBPACK_IMPORTED_MODULE_13__.arrayRange)(startIndex, stopIndex).map((i) => this.walletCache.getByIndex(i, isChange).address);\n await Promise.all(addresses.map(async (addr, idx) => new Promise(async (resolve) => {\n const index = startIndex + idx;\n if (statuses[index] !== undefined) {\n resolve();\n return;\n }\n const { status: prevStatus, utxos: prevUtxos, rawHistory: prevRawHistory, lastConfirmedHeight: prevLastConfirmedHeight, } = this.walletCache.getByIndex(index, isChange);\n statuses[index] = prevStatus;\n utxosArray[index] = prevUtxos;\n historyArray[index] = prevRawHistory;\n // Track lastConfirmedHeight in closure, updated after each fetch\n let lastConfirmedHeight = prevLastConfirmedHeight;\n const callback = async (args) => {\n const [address, status] = args;\n if (address != addr) {\n return;\n }\n if (status === null) {\n utxosArray[index] = [];\n historyArray[index] = [];\n }\n if (status !== null && status !== statuses[index]) {\n // Use lastConfirmedHeight from closure for incremental fetch\n const fromHeight = lastConfirmedHeight;\n const currentHistory = historyArray[index] || [];\n const [utxos, newHistory] = await Promise.all([\n this.provider.getUtxos(addr).then((utxos) => utxos.map((utxo) => {\n utxo.address = addr;\n return utxo;\n })),\n // Fetch only from last confirmed height to reduce server load\n this.provider.getHistory(addr, fromHeight),\n ]);\n // Merge: keep confirmed items from current history, add new items\n const confirmedFromHistory = currentHistory.filter((tx) => tx.height > 0 && tx.height < fromHeight);\n const seen = new Set(confirmedFromHistory.map((tx) => tx.tx_hash));\n const merged = [...confirmedFromHistory];\n for (const tx of newHistory) {\n if (!seen.has(tx.tx_hash)) {\n seen.add(tx.tx_hash);\n merged.push(tx);\n }\n }\n // Update lastConfirmedHeight in closure\n lastConfirmedHeight = merged.reduce((max, tx) => (tx.height > 0 ? Math.max(max, tx.height) : max), fromHeight);\n utxosArray[index] = utxos;\n historyArray[index] = merged;\n this.walletCache.setStatusAndUtxos(addr, status, utxos, merged, lastConfirmedHeight);\n }\n statuses[index] = status;\n if (status !== null) {\n const newIndex = index + 1;\n if (newIndex > getCurrentIndex()) {\n setCurrentIndex(newIndex);\n }\n // Maintain the gap: extend watched range if it shrank\n const gap = statuses.length - getCurrentIndex();\n if (gap < gapSize) {\n await this.watchAddressType(isChange, gapSize);\n }\n }\n // Notify wallet watchers of the status change\n this.notifyWalletWatchers(status, addr);\n resolve();\n };\n watchCancels[index] = await this.provider.subscribeToAddress(addr, callback);\n })));\n return addresses.length;\n }\n // Return wallet info\n getInfo() {\n return {\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n /// Internal method called when any address status changes\n notifyWalletWatchers(status, address) {\n for (const callback of this.walletWatchCallbacks) {\n try {\n callback(status, address);\n }\n catch (e) {\n // Ignore callback errors to not break other watchers\n }\n }\n }\n /**\n * Watch wallet for any activity (status changes on any address)\n * This is the foundation for watchWalletBalance and watchWalletTransactions\n * @param callback - Called when any address in the wallet has a status change\n * @returns Cancel function to stop watching\n */\n async watchStatus(callback, debounce = 100) {\n await this.watchPromise;\n let debounceTimer;\n let pendingStatus = null;\n let pendingAddress = \"\";\n const debouncedCallback = (status, address) => {\n pendingStatus = status;\n pendingAddress = address;\n if (debounceTimer)\n clearTimeout(debounceTimer);\n debounceTimer = setTimeout(() => {\n debounceTimer = undefined;\n callback(pendingStatus, pendingAddress);\n }, debounce);\n };\n this.walletWatchCallbacks.push(debouncedCallback);\n return async () => {\n if (debounceTimer)\n clearTimeout(debounceTimer);\n const index = this.walletWatchCallbacks.indexOf(debouncedCallback);\n if (index > -1) {\n this.walletWatchCallbacks.splice(index, 1);\n }\n };\n }\n /**\n * Wait for the wallet to reach a target depositIndex and/or changeIndex,\n * resolving once the condition is met or after an idle timeout with no\n * status changes.\n */\n async waitForUpdate(options = {}) {\n const timeout = options.timeout ?? 100;\n const isSatisfied = () => {\n if (options.depositIndex !== undefined &&\n this.depositIndex < options.depositIndex)\n return false;\n if (options.changeIndex !== undefined &&\n this.changeIndex < options.changeIndex)\n return false;\n return true;\n };\n if (isSatisfied())\n return;\n return new Promise(async (resolve) => {\n let timer;\n let resolved = false;\n let watchCancel;\n const done = async () => {\n if (resolved)\n return;\n resolved = true;\n clearTimeout(timer);\n await watchCancel?.();\n resolve();\n };\n const resetTimer = () => {\n clearTimeout(timer);\n timer = setTimeout(done, timeout);\n };\n // Uses default 100ms debounce — callback only fires after 100ms of\n // quiet, meaning the cascade has settled before we check the condition.\n watchCancel = await this.watchStatus(async () => {\n if (isSatisfied()) {\n await done();\n }\n else {\n resetTimer(); // cascade settled but target not met — wait for more activity\n }\n });\n // Re-check + start initial idle timer after subscription\n if (isSatisfied()) {\n await done();\n }\n else {\n resetTimer();\n }\n });\n }\n /**\n * Watch wallet for new transactions (HD wallet override)\n *\n * Uses unfiltered history so that seenTxHashes always covers all known\n * transactions, including those from newly discovered addresses when\n * depositIndex/changeIndex extends and widens getRawHistory's scope.\n */\n async watchTransactionHashes(callback) {\n const seenTxHashes = new Set();\n return this.watchStatus(async () => {\n const history = await this.getRawHistory();\n const newTxHashes = [];\n for (const tx of history) {\n if (!seenTxHashes.has(tx.tx_hash)) {\n seenTxHashes.add(tx.tx_hash);\n newTxHashes.push(tx.tx_hash);\n }\n }\n if (newTxHashes.length > 0) {\n newTxHashes.forEach((txHash) => callback(txHash));\n }\n });\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n await this.watchPromise;\n const utxos = [...this.depositUtxos, ...this.changeUtxos].flat();\n return this._slpSemiAware\n ? utxos.filter((u) => u.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_14__.DUST_UTXO_THRESHOLD)\n : utxos;\n }\n // Gets balance by summing value in all utxos in sats\n // Balance includes DUST utxos which could be slp tokens and also cashtokens with BCH amounts\n async getBalance() {\n await this.watchPromise;\n const utxos = [...this.depositUtxos, ...this.changeUtxos].flat();\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_15__.sumUtxoValue)(utxos);\n }\n /// Get next unused deposit address, or the address at the specified index\n getDepositAddress(index = -1) {\n index = (0,_util_hd_js__WEBPACK_IMPORTED_MODULE_13__.getNextUnusedIndex)(index, this.depositStatuses);\n return this.walletCache.getByIndex(index, false).address;\n }\n /// Get next unused token deposit address, or the token address at the specified index\n getTokenDepositAddress(index = -1) {\n index = (0,_util_hd_js__WEBPACK_IMPORTED_MODULE_13__.getNextUnusedIndex)(index, this.depositStatuses);\n return this.walletCache.getByIndex(index, false).tokenAddress;\n }\n /// Get next unused change address, or the address at the specified index\n getChangeAddress(index = -1) {\n index = (0,_util_hd_js__WEBPACK_IMPORTED_MODULE_13__.getNextUnusedIndex)(index, this.changeStatuses);\n return this.walletCache.getByIndex(index, true).address;\n }\n /// Get next unused token change address, or the token address at the specified index\n getChangeTokenAddress(index = -1) {\n index = (0,_util_hd_js__WEBPACK_IMPORTED_MODULE_13__.getNextUnusedIndex)(index, this.changeStatuses);\n return this.walletCache.getByIndex(index, true).tokenAddress;\n }\n hasAddress(address) {\n return this.walletCache.get(address) !== undefined;\n }\n /**\n * fromSeed - create a wallet using the seed phrase and derivation path\n *\n * unless specified the derivation path m/44'/0'/0'/0/0 will be used\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, depositIndex, changeIndex) {\n return new this().initialize({\n mnemonic: seed,\n derivation: derivationPath,\n depositIndex: depositIndex,\n changeIndex: changeIndex,\n });\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 dbName = dbName ? dbName : this.networkPrefix;\n if (name.length > 0) {\n return this.named(name, dbName);\n }\n return new this().initialize();\n }\n /**\n * fromXPub - create a watch-only wallet using the HD Wallet Public key\n *\n * @param xPub HD Wallet Public Key\n *\n * @returns instantiated wallet\n */\n static async fromXPub(xPub) {\n return new this().initialize({\n xPub: xPub,\n });\n }\n /**\n * fromXPriv - create a wallet using the HD Wallet Private key\n *\n * @param xPub HD Wallet Private Key\n *\n * @returns instantiated wallet\n */\n static async fromXPriv(xPriv) {\n return new this().initialize({\n xPriv: xPriv,\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 /// override the base class fromId method implementation\n async fromId(walletId) {\n const [walletType, networkGiven, arg1, arg2, arg3, arg4] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n if (walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.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 }\n if (walletType !== _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Hd) {\n throw Error(`fromId called on a ${walletType} wallet, expected a ${_enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Hd} wallet`);\n }\n if (arg1.startsWith(\"priv\", 1)) {\n return this.initialize({\n xPriv: arg1,\n depositIndex: parseInt(arg2) || 0,\n changeIndex: parseInt(arg3) || 0,\n });\n }\n if (arg1.startsWith(\"pub\", 1)) {\n return this.initialize({\n xPub: arg1,\n depositIndex: parseInt(arg2) || 0,\n changeIndex: parseInt(arg3) || 0,\n });\n }\n return this.initialize({\n mnemonic: arg1,\n derivation: arg2,\n depositIndex: parseInt(arg3) || 0,\n changeIndex: parseInt(arg4) || 0,\n });\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, privateKey) {\n if (!this.xPriv && !privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Missing private key`);\n }\n return super.encodeTransaction(requests, discardChange, options, privateKey);\n }\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 if (this.name) {\n return `named:${this.network}:${this.name}`;\n }\n return this.toDbString();\n }\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_4__.WalletTypeEnum.Hd) {\n if (this.mnemonic?.length > 0) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivation}:${this.depositIndex}:${this.changeIndex}`;\n }\n if (this.xPriv?.length > 0) {\n return `${this.walletType}:${this.network}:${this.xPriv}:${this.depositIndex}:${this.changeIndex}`;\n }\n if (this.xPub?.length > 0) {\n return `${this.walletType}:${this.network}:${this.xPub}:${this.depositIndex}:${this.changeIndex}`;\n }\n throw Error(\"HDWallet has no mnemonic, xPriv or xPub to serialize\");\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n /**\n * getHistory gets transaction history of this wallet with most data decoded and ready to present to user\n * @note balance calculations are valid only if querying to the blockchain tip (`toHeight` === -1, `count` === -1)\n * @note this method is heavy on network calls, if invoked in browser use of cache is advised, @see `Config.UseLocalStorageCache`\n * @note this method tries to recreate the history tab view of Electron Cash wallet, however, it may not be 100% accurate if the tnransaction value changes are the same in the same block (ordering)\n *\n * @param unit optional, BCH or currency unit to present balance and balance changes. If unit is currency like USD or EUR, balances will be subject to possible rounding errors. Default 0\n * @param fromHeight optional, if set, history will be limited. Default 0\n * @param toHeight optional, if set, history will be limited. Default -1, meaning that all history items will be returned, including mempool\n * @param start optional, if set, the result set will be paginated with offset `start`\n * @param count optional, if set, the result set will be paginated with `count`. Default -1, meaning that all history items will be returned\n *\n * @returns an array of transaction history items, with input values and addresses encoded in cashaddress format. @see `TransactionHistoryItem` type\n */\n async getHistory({ unit = \"sat\", fromHeight = 0, toHeight = -1, start = 0, count = -1, }) {\n const rawHistory = await this.getRawHistory(fromHeight, toHeight);\n const addresses = this.getUsedAddresses();\n return (0,_history_getHistory_js__WEBPACK_IMPORTED_MODULE_16__.getHistory)({\n addresses: addresses,\n provider: this.provider,\n unit,\n fromHeight,\n toHeight,\n start,\n count,\n rawHistory,\n });\n }\n // get all used addresses (deposit and change) for this wallet\n getUsedAddresses() {\n return [\n ...this.depositStatuses\n .map((status, i) => status !== null && i < this.depositIndex\n ? this.walletCache.getByIndex(i, false).address\n : undefined)\n .filter((address) => address !== undefined),\n ...this.changeStatuses\n .map((status, i) => status !== null && i < this.changeIndex\n ? this.walletCache.getByIndex(i, true).address\n : undefined)\n .filter((address) => address !== undefined),\n ];\n }\n // gets transaction history of this wallet\n async getRawHistory(fromHeight = 0, toHeight = -1) {\n await this.watchPromise;\n // Collect cached raw history from deposit and change addresses\n const historyArrays = [\n ...this.depositRawHistory.slice(0, this.depositIndex),\n ...this.changeRawHistory.slice(0, this.changeIndex),\n ];\n // Deduplicate by tx_hash\n const seen = new Set();\n let history = [];\n for (const arr of historyArrays) {\n for (const tx of arr) {\n if (!seen.has(tx.tx_hash)) {\n seen.add(tx.tx_hash);\n history.push(tx);\n }\n }\n }\n // Apply height filters if specified\n if (fromHeight > 0 || toHeight !== -1) {\n history = history.filter((tx) => {\n // Unconfirmed transactions (height <= 0) pass the filter when toHeight is -1\n if (tx.height <= 0) {\n return toHeight === -1;\n }\n const aboveFrom = tx.height >= fromHeight;\n const belowTo = toHeight === -1 || tx.height <= toHeight;\n return aboveFrom && belowTo;\n });\n }\n // Sort by height (descending, unconfirmed first)\n return history.sort((a, b) => {\n if (a.height <= 0 && b.height > 0)\n return -1;\n if (b.height <= 0 && a.height > 0)\n return 1;\n return b.height - a.height;\n });\n }\n}\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetHDWallet extends HDWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.testnet; }\n constructor() {\n super(_enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Testnet);\n }\n}\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestHDWallet extends HDWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.regtest; }\n constructor() {\n super(_enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Regtest);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/HDWallet.ts?");
607
+ 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 */ \"GAP_SIZE\": () => (/* binding */ GAP_SIZE),\n/* harmony export */ \"HDWallet\": () => (/* binding */ HDWallet),\n/* harmony export */ \"RegTestHDWallet\": () => (/* binding */ RegTestHDWallet),\n/* harmony export */ \"TestNetHDWallet\": () => (/* binding */ TestNetHDWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/bip39.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __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/utf8.js\");\n/* harmony import */ var _cache_index_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../cache/index.js */ \"./src/cache/walletCache.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _history_getHistory_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../history/getHistory.js */ \"./src/history/getHistory.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _util_hd_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/hd.js */ \"./src/util/hd.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _cache_index_js__WEBPACK_IMPORTED_MODULE_12__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_16__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _cache_index_js__WEBPACK_IMPORTED_MODULE_12__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_16__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\nconst GAP_SIZE = 20;\nclass HDWallet extends _Base_js__WEBPACK_IMPORTED_MODULE_0__.BaseWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.mainnet; }\n get networkPrefix() {\n return _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n }\n /// Create an uninitialized HDWallet, this method should not be called directly\n /// Instead static methods such as `newRandom` or `fromSeed` should be used\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n super(network);\n this.derivation = _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath;\n // Callback type for wallet activity watching\n this.walletWatchCallbacks = [];\n // max index used for deposit address derivation\n this.depositIndex = 0;\n // max index used for change address derivation\n this.changeIndex = 0;\n this.depositWatchCancels = [];\n this.changeWatchCancels = [];\n this.depositStatuses = [];\n this.changeStatuses = [];\n this.depositUtxos = [];\n this.changeUtxos = [];\n this.depositRawHistory = [];\n this.changeRawHistory = [];\n this.watchPromise = undefined;\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Hd;\n }\n /// Initialize the wallet given the options mnemonic, xPriv or xPub\n /// If none provided, a new random mnemonic will be generated\n /// If mnemonic or xPriv provided, the wallet will be able to sign transactions\n /// If xPub provided, the wallet will be watch-only\n /// This internal method is called by the various static constructors\n async initialize({ name = \"\", depositIndex = 0, changeIndex = 0, mnemonic = undefined, derivation = undefined, xPriv = undefined, xPub = undefined, } = {}) {\n // newRandom\n if (!xPriv && !xPub && !mnemonic) {\n mnemonic = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.generateBip39Mnemonic)();\n }\n this.depositIndex = depositIndex;\n this.changeIndex = changeIndex;\n // @ts-ignore\n this.xPub = xPub ? xPub : \"\";\n if (mnemonic?.length) {\n // @ts-ignore\n this.derivation = derivation\n ? derivation\n : _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath;\n // @ts-ignore\n this.mnemonic = mnemonic ? mnemonic : (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.generateBip39Mnemonic)();\n if (this.mnemonic.length == 0) {\n throw Error(\"refusing to create wallet from empty mnemonic\");\n }\n if (![12, 24].includes(this.mnemonic.split(\" \").length)) {\n throw Error(\"Invalid mnemonic, must be 12 or 24 words\");\n }\n const seed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.deriveSeedFromBip39Mnemonic)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_6__.checkForEmptySeed)(seed);\n const rootNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true,\n throwErrors: true,\n });\n const node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.deriveHdPath)(rootNode, this.derivation);\n // @ts-ignore\n this.xPriv = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.encodeHdPrivateKey)({\n ...node,\n network: this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\",\n node: node,\n })).hdPrivateKey;\n // @ts-ignore\n this.xPrivNode = node;\n // @ts-ignore\n this.xPubNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.deriveHdPublicNode)(node);\n // @ts-ignore\n this.xPub = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.encodeHdPublicKey)({\n node: this.xPubNode,\n network: this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\",\n })).hdPublicKey;\n }\n else if (xPriv) {\n // @ts-ignore\n this.xPriv = xPriv;\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.decodeHdPrivateKey)(xPriv));\n if (decoded.network !==\n (this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\")) {\n throw new Error(`xPriv network (${decoded.network}) does not match wallet network (${this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\"})`);\n }\n // @ts-ignore\n this.xPrivNode = decoded.node;\n // @ts-ignore\n this.xPubNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.deriveHdPublicNode)(decoded.node);\n // @ts-ignore\n this.xPub = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.encodeHdPublicKey)({\n node: this.xPubNode,\n network: this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\",\n })).hdPublicKey;\n }\n else if (xPub) {\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.decodeHdPublicKey)(xPub));\n if (decoded.network !==\n (this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\")) {\n throw new Error(`xPriv network (${decoded.network}) does not match wallet network (${this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\"})`);\n }\n // @ts-ignore\n this.xPubNode = decoded.node;\n // @ts-ignore\n this.xPub = xPub;\n }\n else {\n throw new Error(\"mnemonic, xPriv or xPub must be provided to create an HDWallet\");\n }\n this.name = name;\n // @ts-ignore\n this.walletId = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.sha256.hash((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.utf8ToBin)(`${(this.mnemonic ? this.mnemonic + this.derivation : undefined) ??\n this.xPriv ??\n this.xPub}-${this.network}`)));\n // @ts-ignore\n this.walletCache = new _cache_index_js__WEBPACK_IMPORTED_MODULE_12__.HDWalletCache(this.walletId, this.xPrivNode ?? this.xPubNode, this.networkPrefix);\n // init wallet cache\n await this.walletCache.init();\n // start watching addresses asynchronously\n this.watchPromise = this.makeWatchPromise().catch(() => { });\n return this;\n }\n /// Stops the wallet from watching for address changes\n /// After calling this method, the wallet will no longer update and is considered defunct\n async stop() {\n await Promise.all([\n super.stop(),\n ...this.depositWatchCancels.map((fn) => fn?.()),\n ...this.changeWatchCancels.map((fn) => fn?.()),\n ]);\n this.depositWatchCancels = [];\n this.changeWatchCancels = [];\n this.walletWatchCallbacks = [];\n }\n /// Scan more addresses for activity beyond the current gap limit, extending the watched range as needed\n async scanMoreAddresses(amount = GAP_SIZE) {\n await this.watchPromise;\n this.watchPromise = this.makeWatchPromise(amount);\n await this.watchPromise;\n }\n /// Internal method to start watching addresses for activity, extending the watched range as needed\n async makeWatchPromise(gapSize = GAP_SIZE) {\n await this.watchPromise;\n let needsMore = true;\n while (needsMore) {\n await Promise.all([\n this.watchAddressType(false, gapSize),\n this.watchAddressType(true, gapSize),\n ]);\n // Check if we have a full gap of addresses beyond the last used index\n const depositGap = this.depositStatuses.length - this.depositIndex;\n const changeGap = this.changeStatuses.length - this.changeIndex;\n needsMore = depositGap < gapSize || changeGap < gapSize;\n }\n }\n /// Watch addresses of a specific type (deposit or change) for activity\n async watchAddressType(isChange, gapSize) {\n // Select the appropriate arrays based on address type\n const statuses = isChange ? this.changeStatuses : this.depositStatuses;\n const utxosArray = isChange ? this.changeUtxos : this.depositUtxos;\n const historyArray = isChange\n ? this.changeRawHistory\n : this.depositRawHistory;\n const watchCancels = isChange\n ? this.changeWatchCancels\n : this.depositWatchCancels;\n const getCurrentIndex = () => isChange ? this.changeIndex : this.depositIndex;\n const setCurrentIndex = (val) => {\n if (isChange) {\n this.changeIndex = val;\n }\n else {\n this.depositIndex = val;\n }\n };\n const startIndex = statuses.length;\n const stopIndex = getCurrentIndex() + gapSize;\n const addresses = (0,_util_hd_js__WEBPACK_IMPORTED_MODULE_13__.arrayRange)(startIndex, stopIndex).map((i) => this.walletCache.getByIndex(i, isChange).address);\n await Promise.all(addresses.map(async (addr, idx) => new Promise(async (resolve) => {\n const index = startIndex + idx;\n if (statuses[index] !== undefined) {\n resolve();\n return;\n }\n const { status: prevStatus, utxos: prevUtxos, rawHistory: prevRawHistory, lastConfirmedHeight: prevLastConfirmedHeight, } = this.walletCache.getByIndex(index, isChange);\n statuses[index] = prevStatus;\n utxosArray[index] = prevUtxos;\n historyArray[index] = prevRawHistory;\n // Track lastConfirmedHeight in closure, updated after each fetch\n let lastConfirmedHeight = prevLastConfirmedHeight;\n const callback = async (args) => {\n const [address, status] = args;\n if (address != addr) {\n return;\n }\n if (status === null) {\n utxosArray[index] = [];\n historyArray[index] = [];\n }\n if (status !== null && status !== statuses[index]) {\n // Use lastConfirmedHeight from closure for incremental fetch\n const fromHeight = lastConfirmedHeight;\n const currentHistory = historyArray[index] || [];\n const [utxos, newHistory] = await Promise.all([\n this.provider.getUtxos(addr).then((utxos) => utxos.map((utxo) => {\n utxo.address = addr;\n return utxo;\n })),\n // Fetch only from last confirmed height to reduce server load\n this.provider.getHistory(addr, fromHeight),\n ]);\n // Merge: keep confirmed items from current history, add new items\n const confirmedFromHistory = currentHistory.filter((tx) => tx.height > 0 && tx.height < fromHeight);\n const seen = new Set(confirmedFromHistory.map((tx) => tx.tx_hash));\n const merged = [...confirmedFromHistory];\n for (const tx of newHistory) {\n if (!seen.has(tx.tx_hash)) {\n seen.add(tx.tx_hash);\n merged.push(tx);\n }\n }\n // Update lastConfirmedHeight in closure\n lastConfirmedHeight = merged.reduce((max, tx) => (tx.height > 0 ? Math.max(max, tx.height) : max), fromHeight);\n utxosArray[index] = utxos;\n historyArray[index] = merged;\n this.walletCache.setStatusAndUtxos(addr, status, utxos, merged, lastConfirmedHeight);\n }\n statuses[index] = status;\n if (status !== null) {\n const newIndex = index + 1;\n if (newIndex > getCurrentIndex()) {\n setCurrentIndex(newIndex);\n }\n // Maintain the gap: extend watched range if it shrank\n const gap = statuses.length - getCurrentIndex();\n if (gap < gapSize) {\n await this.watchAddressType(isChange, gapSize);\n }\n }\n // Notify wallet watchers of the status change\n this.notifyWalletWatchers(status, addr);\n resolve();\n };\n watchCancels[index] = await this.provider.subscribeToAddress(addr, callback);\n })));\n return addresses.length;\n }\n // Return wallet info\n getInfo() {\n return {\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n /// Internal method called when any address status changes\n notifyWalletWatchers(status, address) {\n for (const callback of this.walletWatchCallbacks) {\n try {\n callback(status, address);\n }\n catch (e) {\n // Ignore callback errors to not break other watchers\n }\n }\n }\n /**\n * Watch wallet for any activity (status changes on any address)\n * This is the foundation for watchWalletBalance and watchWalletTransactions\n * @param callback - Called when any address in the wallet has a status change\n * @returns Cancel function to stop watching\n */\n async watchStatus(callback, debounce = 100) {\n await this.watchPromise;\n let debounceTimer;\n let pendingStatus = null;\n let pendingAddress = \"\";\n const debouncedCallback = (status, address) => {\n pendingStatus = status;\n pendingAddress = address;\n if (debounceTimer)\n clearTimeout(debounceTimer);\n debounceTimer = setTimeout(() => {\n debounceTimer = undefined;\n callback(pendingStatus, pendingAddress);\n }, debounce);\n };\n this.walletWatchCallbacks.push(debouncedCallback);\n return async () => {\n if (debounceTimer)\n clearTimeout(debounceTimer);\n const index = this.walletWatchCallbacks.indexOf(debouncedCallback);\n if (index > -1) {\n this.walletWatchCallbacks.splice(index, 1);\n }\n };\n }\n /**\n * Wait for the wallet to reach a target depositIndex and/or changeIndex,\n * resolving once the condition is met or after an idle timeout with no\n * status changes.\n */\n async waitForUpdate(options = {}) {\n const timeout = options.timeout ?? 100;\n const isSatisfied = () => {\n if (options.depositIndex !== undefined &&\n this.depositIndex < options.depositIndex)\n return false;\n if (options.changeIndex !== undefined &&\n this.changeIndex < options.changeIndex)\n return false;\n return true;\n };\n if (isSatisfied())\n return;\n // Single watcher that resolves a rotating promise on each status change\n let statusResolve;\n const cancel = await this.watchStatus(() => {\n statusResolve?.();\n });\n // Race status changes against idle timeout; reset timeout on each change\n while (!isSatisfied()) {\n const statusChange = new Promise((resolve) => {\n statusResolve = () => resolve(\"status\");\n });\n const idle = new Promise((resolve) => setTimeout(resolve, timeout, \"idle\"));\n if ((await Promise.race([statusChange, idle])) === \"idle\")\n break;\n }\n await cancel();\n }\n /**\n * Watch wallet for new transactions (HD wallet override)\n *\n * Uses unfiltered history so that seenTxHashes always covers all known\n * transactions, including those from newly discovered addresses when\n * depositIndex/changeIndex extends and widens getRawHistory's scope.\n */\n async watchTransactionHashes(callback) {\n const seenTxHashes = new Set();\n return this.watchStatus(async () => {\n const history = await this.getRawHistory();\n const newTxHashes = [];\n for (const tx of history) {\n if (!seenTxHashes.has(tx.tx_hash)) {\n seenTxHashes.add(tx.tx_hash);\n newTxHashes.push(tx.tx_hash);\n }\n }\n if (newTxHashes.length > 0) {\n newTxHashes.forEach((txHash) => callback(txHash));\n }\n });\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n await this.watchPromise;\n const utxos = [...this.depositUtxos, ...this.changeUtxos].flat();\n return this._slpSemiAware\n ? utxos.filter((u) => u.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_14__.DUST_UTXO_THRESHOLD)\n : utxos;\n }\n // Gets balance by summing value in all utxos in sats\n // Balance includes DUST utxos which could be slp tokens and also cashtokens with BCH amounts\n async getBalance() {\n await this.watchPromise;\n const utxos = [...this.depositUtxos, ...this.changeUtxos].flat();\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_15__.sumUtxoValue)(utxos);\n }\n /// Get next unused deposit address, or the address at the specified index\n getDepositAddress(index = -1) {\n index = (0,_util_hd_js__WEBPACK_IMPORTED_MODULE_13__.getNextUnusedIndex)(index, this.depositStatuses);\n return this.walletCache.getByIndex(index, false).address;\n }\n /// Get next unused token deposit address, or the token address at the specified index\n getTokenDepositAddress(index = -1) {\n index = (0,_util_hd_js__WEBPACK_IMPORTED_MODULE_13__.getNextUnusedIndex)(index, this.depositStatuses);\n return this.walletCache.getByIndex(index, false).tokenAddress;\n }\n /// Get next unused change address, or the address at the specified index\n getChangeAddress(index = -1) {\n index = (0,_util_hd_js__WEBPACK_IMPORTED_MODULE_13__.getNextUnusedIndex)(index, this.changeStatuses);\n return this.walletCache.getByIndex(index, true).address;\n }\n /// Get next unused token change address, or the token address at the specified index\n getChangeTokenAddress(index = -1) {\n index = (0,_util_hd_js__WEBPACK_IMPORTED_MODULE_13__.getNextUnusedIndex)(index, this.changeStatuses);\n return this.walletCache.getByIndex(index, true).tokenAddress;\n }\n hasAddress(address) {\n return this.walletCache.get(address) !== undefined;\n }\n /**\n * fromSeed - create a wallet using the seed phrase and derivation path\n *\n * unless specified the derivation path m/44'/0'/0'/0/0 will be used\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, depositIndex, changeIndex) {\n return new this().initialize({\n mnemonic: seed,\n derivation: derivationPath,\n depositIndex: depositIndex,\n changeIndex: changeIndex,\n });\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 dbName = dbName ? dbName : this.networkPrefix;\n if (name.length > 0) {\n return this.named(name, dbName);\n }\n return new this().initialize();\n }\n /**\n * fromXPub - create a watch-only wallet using the HD Wallet Public key\n *\n * @param xPub HD Wallet Public Key\n *\n * @returns instantiated wallet\n */\n static async fromXPub(xPub) {\n return new this().initialize({\n xPub: xPub,\n });\n }\n /**\n * fromXPriv - create a wallet using the HD Wallet Private key\n *\n * @param xPub HD Wallet Private Key\n *\n * @returns instantiated wallet\n */\n static async fromXPriv(xPriv) {\n return new this().initialize({\n xPriv: xPriv,\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 /// override the base class fromId method implementation\n async fromId(walletId) {\n const [walletType, networkGiven, arg1, arg2, arg3, arg4] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n if (walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.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 }\n if (walletType !== _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Hd) {\n throw Error(`fromId called on a ${walletType} wallet, expected a ${_enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Hd} wallet`);\n }\n if (arg1.startsWith(\"priv\", 1)) {\n return this.initialize({\n xPriv: arg1,\n depositIndex: parseInt(arg2) || 0,\n changeIndex: parseInt(arg3) || 0,\n });\n }\n if (arg1.startsWith(\"pub\", 1)) {\n return this.initialize({\n xPub: arg1,\n depositIndex: parseInt(arg2) || 0,\n changeIndex: parseInt(arg3) || 0,\n });\n }\n return this.initialize({\n mnemonic: arg1,\n derivation: arg2,\n depositIndex: parseInt(arg3) || 0,\n changeIndex: parseInt(arg4) || 0,\n });\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, privateKey) {\n if (!this.xPriv && !privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Missing private key`);\n }\n return super.encodeTransaction(requests, discardChange, options, privateKey);\n }\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 if (this.name) {\n return `named:${this.network}:${this.name}`;\n }\n return this.toDbString();\n }\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_4__.WalletTypeEnum.Hd) {\n if (this.mnemonic?.length > 0) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivation}:${this.depositIndex}:${this.changeIndex}`;\n }\n if (this.xPriv?.length > 0) {\n return `${this.walletType}:${this.network}:${this.xPriv}:${this.depositIndex}:${this.changeIndex}`;\n }\n if (this.xPub?.length > 0) {\n return `${this.walletType}:${this.network}:${this.xPub}:${this.depositIndex}:${this.changeIndex}`;\n }\n throw Error(\"HDWallet has no mnemonic, xPriv or xPub to serialize\");\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n /**\n * getHistory gets transaction history of this wallet with most data decoded and ready to present to user\n * @note balance calculations are valid only if querying to the blockchain tip (`toHeight` === -1, `count` === -1)\n * @note this method is heavy on network calls, if invoked in browser use of cache is advised, @see `Config.UseLocalStorageCache`\n * @note this method tries to recreate the history tab view of Electron Cash wallet, however, it may not be 100% accurate if the tnransaction value changes are the same in the same block (ordering)\n *\n * @param unit optional, BCH or currency unit to present balance and balance changes. If unit is currency like USD or EUR, balances will be subject to possible rounding errors. Default 0\n * @param fromHeight optional, if set, history will be limited. Default 0\n * @param toHeight optional, if set, history will be limited. Default -1, meaning that all history items will be returned, including mempool\n * @param start optional, if set, the result set will be paginated with offset `start`\n * @param count optional, if set, the result set will be paginated with `count`. Default -1, meaning that all history items will be returned\n *\n * @returns an array of transaction history items, with input values and addresses encoded in cashaddress format. @see `TransactionHistoryItem` type\n */\n async getHistory({ unit = \"sat\", fromHeight = 0, toHeight = -1, start = 0, count = -1, }) {\n const rawHistory = await this.getRawHistory(fromHeight, toHeight);\n const addresses = this.getUsedAddresses();\n return (0,_history_getHistory_js__WEBPACK_IMPORTED_MODULE_16__.getHistory)({\n addresses: addresses,\n provider: this.provider,\n unit,\n fromHeight,\n toHeight,\n start,\n count,\n rawHistory,\n });\n }\n // get all used addresses (deposit and change) for this wallet\n getUsedAddresses() {\n return [\n ...this.depositStatuses\n .map((status, i) => status !== null && i < this.depositIndex\n ? this.walletCache.getByIndex(i, false).address\n : undefined)\n .filter((address) => address !== undefined),\n ...this.changeStatuses\n .map((status, i) => status !== null && i < this.changeIndex\n ? this.walletCache.getByIndex(i, true).address\n : undefined)\n .filter((address) => address !== undefined),\n ];\n }\n // gets transaction history of this wallet\n async getRawHistory(fromHeight = 0, toHeight = -1) {\n await this.watchPromise;\n // Collect cached raw history from deposit and change addresses\n const historyArrays = [\n ...this.depositRawHistory.slice(0, this.depositIndex),\n ...this.changeRawHistory.slice(0, this.changeIndex),\n ];\n // Deduplicate by tx_hash\n const seen = new Set();\n let history = [];\n for (const arr of historyArrays) {\n for (const tx of arr) {\n if (!seen.has(tx.tx_hash)) {\n seen.add(tx.tx_hash);\n history.push(tx);\n }\n }\n }\n // Apply height filters if specified\n if (fromHeight > 0 || toHeight !== -1) {\n history = history.filter((tx) => {\n // Unconfirmed transactions (height <= 0) pass the filter when toHeight is -1\n if (tx.height <= 0) {\n return toHeight === -1;\n }\n const aboveFrom = tx.height >= fromHeight;\n const belowTo = toHeight === -1 || tx.height <= toHeight;\n return aboveFrom && belowTo;\n });\n }\n // Sort by height (descending, unconfirmed first)\n return history.sort((a, b) => {\n if (a.height <= 0 && b.height > 0)\n return -1;\n if (b.height <= 0 && a.height > 0)\n return 1;\n return b.height - a.height;\n });\n }\n}\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetHDWallet extends HDWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.testnet; }\n constructor() {\n super(_enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Testnet);\n }\n}\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestHDWallet extends HDWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.regtest; }\n constructor() {\n super(_enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Regtest);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/HDWallet.ts?");
648
608
 
649
609
  /***/ }),
650
610
 
@@ -664,7 +624,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
664
624
  \*****************************/
665
625
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
666
626
 
667
- 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 */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/combinations.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _history_getHistory_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../history/getHistory.js */ \"./src/history/getHistory.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_7__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_7__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n/**\n * Class to manage a mainnet watch wallet.\n */\nclass WatchWallet extends _Base_js__WEBPACK_IMPORTED_MODULE_0__.BaseWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.mainnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch; }\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch) {\n super(network);\n this.name = name;\n // @ts-ignore\n this.walletType = walletType;\n }\n /// Initialize the watch-only wallet given the options - publicKey variations\n /// This internal method is called by the various static constructors\n async initialize({ name = \"\", publicKey = undefined, publicKeyCompressed = undefined, publicKeyHash = undefined, address = undefined, } = {}) {\n if (publicKey?.length) {\n // @ts-ignore\n this.publicKey = publicKey;\n if (!publicKeyCompressed) {\n publicKeyCompressed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.secp256k1.compressPublicKey(publicKey));\n }\n }\n if (publicKeyCompressed?.length) {\n // @ts-ignore\n this.publicKeyCompressed = publicKeyCompressed;\n if (!publicKey) {\n publicKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.secp256k1.uncompressPublicKey(publicKeyCompressed));\n // @ts-ignore\n this.publicKey = publicKey;\n }\n publicKeyHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.hash160)(publicKeyCompressed);\n }\n if (publicKeyHash?.length) {\n // @ts-ignore\n this.publicKeyHash = publicKeyHash;\n address = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.encodeCashAddress)({\n prefix: _enum_js__WEBPACK_IMPORTED_MODULE_3__.prefixFromNetworkMap[this.network],\n type: \"p2pkh\",\n payload: publicKeyHash,\n }).address;\n }\n if (address?.length) {\n // derive prefix if not provided\n if (!address.includes(\":\")) {\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.decodeCashAddressFormatWithoutPrefix)(address));\n address = `${decoded.prefix}:${address}`;\n }\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.decodeCashAddress)(address));\n if (_enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[decoded.prefix] !== this.network) {\n throw Error(`a ${decoded.prefix} address cannot be watched from a ${this.network} Wallet`);\n }\n if (!this.publicKeyHash?.length) {\n if (decoded.type.includes(\"p2pkh\")) {\n // @ts-ignore\n this.publicKeyHash = decoded.payload;\n }\n }\n // @ts-ignore\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_7__.toCashaddr)(address);\n // @ts-ignore\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_7__.toTokenaddr)(address);\n }\n if (!this.cashaddr?.length || !this.tokenaddr?.length) {\n throw Error(\"Could not initialize wallet - insufficient parameters\");\n }\n this.name = name;\n return this;\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.cashaddr;\n }\n /**\n * getChangeAddress - get a wallet change address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/changeAddress|/wallet/change_address} for REST endpoint\n *\n * @returns The change address as a string\n */\n getChangeAddress() {\n return this.cashaddr;\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 // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\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_8__.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_8__.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 // 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 publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.binToHex)(this.publicKeyHash),\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n const bchUtxos = await this.provider.getUtxos(this.cashaddr);\n return this._slpSemiAware\n ? bchUtxos.filter((u) => u.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_9__.DUST_UTXO_THRESHOLD)\n : bchUtxos;\n }\n // Gets balance by summing value in all utxos in sats\n // Balance includes DUST utxos which could be slp tokens and also cashtokens with BCH amounts\n async getBalance() {\n return this.provider.getBalance(this.cashaddr);\n }\n // gets transaction history of this wallet\n async getRawHistory(fromHeight = 0, toHeight = -1) {\n return await this.provider.getHistory(this.cashaddr, fromHeight, toHeight);\n }\n /**\n * getHistory gets transaction history of this wallet with most data decoded and ready to present to user\n * @note balance calculations are valid only if querying to the blockchain tip (`toHeight` === -1, `count` === -1)\n * @note this method is heavy on network calls, if invoked in browser use of cache is advised, @see `Config.UseLocalStorageCache`\n * @note this method tries to recreate the history tab view of Electron Cash wallet, however, it may not be 100% accurate if the tnransaction value changes are the same in the same block (ordering)\n *\n * @param unit optional, BCH or currency unit to present balance and balance changes. If unit is currency like USD or EUR, balances will be subject to possible rounding errors. Default 0\n * @param fromHeight optional, if set, history will be limited. Default 0\n * @param toHeight optional, if set, history will be limited. Default -1, meaning that all history items will be returned, including mempool\n * @param start optional, if set, the result set will be paginated with offset `start`\n * @param count optional, if set, the result set will be paginated with `count`. Default -1, meaning that all history items will be returned\n *\n * @returns an array of transaction history items, with input values and addresses encoded in cashaddress format. @see `TransactionHistoryItem` type\n */\n async getHistory({ unit = \"sat\", fromHeight = 0, toHeight = -1, start = 0, count = -1, } = {}) {\n return (0,_history_getHistory_js__WEBPACK_IMPORTED_MODULE_10__.getHistory)({\n addresses: [this.cashaddr],\n provider: this.provider,\n unit,\n fromHeight,\n toHeight,\n start,\n count,\n });\n }\n fromId(walletId) {\n const [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (walletType !== _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch) {\n throw Error(`fromId called on a ${walletType} wallet, expected a ${_enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch} wallet`);\n }\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n if (arg2) {\n return this.watchOnly(`${arg1}:${arg2}`);\n }\n return this.watchOnly(arg1);\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch;\n return this.initialize({ address, name: this.name });\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 if (!address?.length)\n throw Error(\"address is required to create a watch-only wallet\");\n return new this().watchOnly(address);\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 if (!address?.length)\n throw Error(\"address is required to create a watch-only wallet\");\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType).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 if (!address?.length)\n throw Error(\"address is required to create a watch-only wallet\");\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType).watchOnly(address);\n }\n /**\n * fromPublicKey - create a watch-only wallet in the network derived from the compressed or uncompressed public key\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 publicKey compressed or uncompressed public key\n *\n * @returns instantiated wallet\n */\n static async fromPublicKey(publicKey) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch;\n return new this(\"\", _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[this.networkPrefix]).initialize({\n publicKey: publicKey.length === 33 ? undefined : publicKey,\n publicKeyCompressed: publicKey.length === 33 ? publicKey : undefined,\n });\n }\n // Convenience wrapper to verify interface\n verify(message, sig, address, publicKey) {\n if (!address) {\n address = this.cashaddr;\n }\n return super.verify(message, sig, address, publicKey);\n }\n}\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends WatchWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.testnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch; }\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet) {\n super(name, network);\n }\n}\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends WatchWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.regtest; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch; }\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest) {\n super(name, network);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Watch.ts?");
627
+ 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 */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/combinations.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _history_getHistory_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../history/getHistory.js */ \"./src/history/getHistory.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _cache_walletCache_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../cache/walletCache.js */ \"./src/cache/walletCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_7__, _cache_walletCache_js__WEBPACK_IMPORTED_MODULE_10__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_13__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_14__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_7__, _cache_walletCache_js__WEBPACK_IMPORTED_MODULE_10__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_13__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_14__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n/**\n * Class to manage a mainnet watch wallet.\n */\nclass WatchWallet extends _Base_js__WEBPACK_IMPORTED_MODULE_0__.BaseWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.mainnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch; }\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch) {\n super(network);\n // Subscription-first infrastructure: single subscription shared by all watchers\n this.watchCallbacks = [];\n // Live state — updated by subscription notifications\n this.status = null;\n this.utxos = [];\n this.rawHistory = [];\n this.lastConfirmedHeight = 0;\n this.name = name;\n // @ts-ignore\n this.walletType = walletType;\n }\n /// Initialize the watch-only wallet given the options - publicKey variations\n /// This internal method is called by the various static constructors\n async initialize({ name = \"\", publicKey = undefined, publicKeyCompressed = undefined, publicKeyHash = undefined, address = undefined, } = {}) {\n if (publicKey?.length) {\n // @ts-ignore\n this.publicKey = publicKey;\n if (!publicKeyCompressed) {\n publicKeyCompressed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.secp256k1.compressPublicKey(publicKey));\n }\n }\n if (publicKeyCompressed?.length) {\n // @ts-ignore\n this.publicKeyCompressed = publicKeyCompressed;\n if (!publicKey) {\n publicKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.secp256k1.uncompressPublicKey(publicKeyCompressed));\n // @ts-ignore\n this.publicKey = publicKey;\n }\n publicKeyHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.hash160)(publicKeyCompressed);\n }\n if (publicKeyHash?.length) {\n // @ts-ignore\n this.publicKeyHash = publicKeyHash;\n address = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.encodeCashAddress)({\n prefix: _enum_js__WEBPACK_IMPORTED_MODULE_3__.prefixFromNetworkMap[this.network],\n type: \"p2pkh\",\n payload: publicKeyHash,\n }).address;\n }\n if (address?.length) {\n // derive prefix if not provided\n if (!address.includes(\":\")) {\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.decodeCashAddressFormatWithoutPrefix)(address));\n address = `${decoded.prefix}:${address}`;\n }\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.decodeCashAddress)(address));\n if (_enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[decoded.prefix] !== this.network) {\n throw Error(`a ${decoded.prefix} address cannot be watched from a ${this.network} Wallet`);\n }\n if (!this.publicKeyHash?.length) {\n if (decoded.type.includes(\"p2pkh\")) {\n // @ts-ignore\n this.publicKeyHash = decoded.payload;\n }\n }\n // @ts-ignore\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_7__.toCashaddr)(address);\n // @ts-ignore\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_7__.toTokenaddr)(address);\n }\n if (!this.cashaddr?.length || !this.tokenaddr?.length) {\n throw Error(\"Could not initialize wallet - insufficient parameters\");\n }\n this.name = name;\n // Initialize persistent cache and load saved state\n await this.initWalletCache();\n const cached = this.getCacheEntry();\n this.status = cached.status;\n this.utxos = cached.utxos;\n this.rawHistory = cached.rawHistory;\n this.lastConfirmedHeight = cached.lastConfirmedHeight;\n // Start subscription immediately (subscription-first approach)\n this.watchPromise = this.makeWatchPromise().catch(() => { });\n return this;\n }\n deriveWalletId() {\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.sha256.hash((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.utf8ToBin)(`${this.cashaddr}-${this.network}`)));\n }\n async initWalletCache() {\n const cache = new _cache_walletCache_js__WEBPACK_IMPORTED_MODULE_10__.SingleAddressWalletCache(this.deriveWalletId(), this.cashaddr, this.tokenaddr);\n await cache.init();\n const wallet = this;\n if (wallet.privateKey) {\n cache.get(this.cashaddr).privateKey = wallet.privateKey;\n }\n // @ts-ignore\n this.walletCache = cache;\n }\n getCacheEntry() {\n return this.walletCache.get(this.cashaddr);\n }\n /// Subscribe to the single address for status change notifications\n async makeWatchPromise() {\n const addr = this.cashaddr;\n let resolved = false;\n return new Promise(async (resolve) => {\n this.baseCancelFn = await this.provider.subscribeToAddress(addr, async (args) => {\n const [address, status] = args;\n if (address !== addr)\n return;\n if (status !== null && status !== this.status) {\n this.updatePromise = this.fetchData(status);\n }\n this.status = status;\n this.notifyWatchCallbacks(status, addr);\n if (!resolved) {\n resolved = true;\n resolve();\n }\n });\n });\n }\n async fetchData(status) {\n const addr = this.cashaddr;\n const fromHeight = this.lastConfirmedHeight;\n const [utxos, newHistory] = await Promise.all([\n this.provider.getUtxos(addr),\n this.provider.getHistory(addr, fromHeight),\n ]);\n // Merge: keep confirmed items below fromHeight, add new items\n const confirmedFromHistory = this.rawHistory.filter((tx) => tx.height > 0 && tx.height < fromHeight);\n const seen = new Set(confirmedFromHistory.map((tx) => tx.tx_hash));\n const merged = [...confirmedFromHistory];\n for (const tx of newHistory) {\n if (!seen.has(tx.tx_hash)) {\n seen.add(tx.tx_hash);\n merged.push(tx);\n }\n }\n this.lastConfirmedHeight = merged.reduce((max, tx) => (tx.height > 0 ? Math.max(max, tx.height) : max), fromHeight);\n // Update live state\n this.utxos = utxos;\n this.rawHistory = merged;\n // Persist to cache\n this.walletCache.setStatusAndUtxos(addr, status, utxos, merged, this.lastConfirmedHeight);\n }\n notifyWatchCallbacks(status, address) {\n for (const callback of this.watchCallbacks) {\n try {\n callback(status, address);\n }\n catch (_e) {\n // Ignore callback errors to not break other watchers\n }\n }\n }\n async watchStatus(callback) {\n await this.watchPromise;\n this.watchCallbacks.push(callback);\n return async () => {\n const index = this.watchCallbacks.indexOf(callback);\n if (index > -1) {\n this.watchCallbacks.splice(index, 1);\n }\n };\n }\n async waitForUpdate(options = {}) {\n const timeout = options.timeout ?? 100;\n let cancel;\n const statusChange = new Promise(async (resolve) => {\n cancel = await this.watchStatus(() => resolve());\n });\n const timer = new Promise((resolve) => setTimeout(resolve, timeout));\n await Promise.race([statusChange, timer]);\n await cancel();\n }\n async stop() {\n await super.stop();\n await this.baseCancelFn?.();\n this.baseCancelFn = undefined;\n this.watchCallbacks = [];\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.cashaddr;\n }\n /**\n * getChangeAddress - get a wallet change address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/changeAddress|/wallet/change_address} for REST endpoint\n *\n * @returns The change address as a string\n */\n getChangeAddress() {\n return this.cashaddr;\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 // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\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_8__.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_8__.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 // 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 publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.binToHex)(this.publicKeyHash),\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n await this.watchPromise;\n await this.updatePromise;\n return this._slpSemiAware\n ? this.utxos.filter((u) => u.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_11__.DUST_UTXO_THRESHOLD)\n : this.utxos;\n }\n // Gets balance by summing value in all utxos in sats\n // Balance includes DUST utxos which could be slp tokens and also cashtokens with BCH amounts\n async getBalance() {\n await this.watchPromise;\n await this.updatePromise;\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_12__.sumUtxoValue)(this.utxos);\n }\n // gets transaction history of this wallet\n async getRawHistory(fromHeight = 0, toHeight = -1) {\n await this.watchPromise;\n await this.updatePromise;\n let history = this.rawHistory;\n if (fromHeight > 0 || toHeight !== -1) {\n history = history.filter((tx) => {\n if (tx.height <= 0) {\n return toHeight === -1;\n }\n const aboveFrom = tx.height >= fromHeight;\n const belowTo = toHeight === -1 || tx.height <= toHeight;\n return aboveFrom && belowTo;\n });\n }\n return history;\n }\n /**\n * getHistory gets transaction history of this wallet with most data decoded and ready to present to user\n * @note balance calculations are valid only if querying to the blockchain tip (`toHeight` === -1, `count` === -1)\n * @note this method is heavy on network calls, if invoked in browser use of cache is advised, @see `Config.UseLocalStorageCache`\n * @note this method tries to recreate the history tab view of Electron Cash wallet, however, it may not be 100% accurate if the tnransaction value changes are the same in the same block (ordering)\n *\n * @param unit optional, BCH or currency unit to present balance and balance changes. If unit is currency like USD or EUR, balances will be subject to possible rounding errors. Default 0\n * @param fromHeight optional, if set, history will be limited. Default 0\n * @param toHeight optional, if set, history will be limited. Default -1, meaning that all history items will be returned, including mempool\n * @param start optional, if set, the result set will be paginated with offset `start`\n * @param count optional, if set, the result set will be paginated with `count`. Default -1, meaning that all history items will be returned\n *\n * @returns an array of transaction history items, with input values and addresses encoded in cashaddress format. @see `TransactionHistoryItem` type\n */\n async getHistory({ unit = \"sat\", fromHeight = 0, toHeight = -1, start = 0, count = -1, } = {}) {\n return (0,_history_getHistory_js__WEBPACK_IMPORTED_MODULE_13__.getHistory)({\n addresses: [this.cashaddr],\n provider: this.provider,\n unit,\n fromHeight,\n toHeight,\n start,\n count,\n });\n }\n fromId(walletId) {\n const [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (walletType !== _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch) {\n throw Error(`fromId called on a ${walletType} wallet, expected a ${_enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch} wallet`);\n }\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n if (arg2) {\n return this.watchOnly(`${arg1}:${arg2}`);\n }\n return this.watchOnly(arg1);\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch;\n return this.initialize({ address, name: this.name });\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 if (!address?.length)\n throw Error(\"address is required to create a watch-only wallet\");\n return new this().watchOnly(address);\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 if (!address?.length)\n throw Error(\"address is required to create a watch-only wallet\");\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_14__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType).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 if (!address?.length)\n throw Error(\"address is required to create a watch-only wallet\");\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_14__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType).watchOnly(address);\n }\n /**\n * fromPublicKey - create a watch-only wallet in the network derived from the compressed or uncompressed public key\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 publicKey compressed or uncompressed public key\n *\n * @returns instantiated wallet\n */\n static async fromPublicKey(publicKey) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch;\n return new this(\"\", _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[this.networkPrefix]).initialize({\n publicKey: publicKey.length === 33 ? undefined : publicKey,\n publicKeyCompressed: publicKey.length === 33 ? publicKey : undefined,\n });\n }\n // Convenience wrapper to verify interface\n verify(message, sig, address, publicKey) {\n if (!address) {\n address = this.cashaddr;\n }\n return super.verify(message, sig, address, publicKey);\n }\n}\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends WatchWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.testnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch; }\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet) {\n super(name, network);\n }\n}\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends WatchWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.CashAddressNetworkPrefix.regtest; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch; }\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest) {\n super(name, network);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Watch.ts?");
668
628
 
669
629
  /***/ }),
670
630
 
@@ -674,7 +634,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
674
634
  \***************************/
675
635
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
676
636
 
677
- 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 */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/bip39.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _Watch_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Watch.js */ \"./src/wallet/Watch.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Watch_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_11__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__, _model_js__WEBPACK_IMPORTED_MODULE_14__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__]);\n([_Watch_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_11__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__, _model_js__WEBPACK_IMPORTED_MODULE_14__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Watch_js__WEBPACK_IMPORTED_MODULE_0__.WatchWallet {\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Seed) {\n super(name, network);\n this.derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath + \"/0/0\";\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath;\n //#endregion Constructors\n //#region Protected implementations\n this.fromId = async (walletId) => {\n const [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (this.network !== networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n switch (walletType) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.PrivateKey:\n return this.fromPrivateKey(arg1);\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif:\n return this.fromWIF(arg1);\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.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 _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.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 _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.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 this.name = name;\n // @ts-ignore\n this.walletType = walletType;\n }\n /// Initialize the wallet given the options mnemonic, privateKey or publicKey variations\n /// If none provided, a new random mnemonic will be generated\n /// If mnemonic or private key provided, the wallet will be able to sign transactions\n /// Otherwise, the wallet will be watch-only\n /// This internal method is called by the various static constructors\n async initialize({ name = \"\", mnemonic = undefined, derivationPath = undefined, privateKey = undefined, privateKeyWif = undefined, publicKey = undefined, publicKeyCompressed = undefined, publicKeyHash = undefined, address = undefined, } = {}) {\n // seed wallet\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Seed && !mnemonic) {\n mnemonic = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.generateBip39Mnemonic)();\n }\n if (mnemonic?.length) {\n mnemonic = mnemonic.trim().toLowerCase();\n if (![12, 24].includes(mnemonic.split(\" \").length)) {\n throw Error(\"Invalid mnemonic, must be 12 or 24 words\");\n }\n if (derivationPath) {\n // @ts-ignore\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n const path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n // @ts-ignore\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n else {\n derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath + \"/0/0\";\n // @ts-ignore\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath;\n }\n // @ts-ignore\n this.mnemonic = mnemonic;\n // @ts-ignore\n this.derivationPath = derivationPath;\n const seed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.deriveSeedFromBip39Mnemonic)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_5__.checkForEmptySeed)(seed);\n const rootNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true,\n throwErrors: true,\n });\n const parentNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPath)(rootNode, this.parentDerivationPath);\n // @ts-ignore\n this.parentXPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.encodeHdPublicKey)({\n node: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPublicNode)(parentNode),\n network: this.network === _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\",\n })).hdPublicKey;\n const childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPath)(rootNode, this.derivationPath);\n privateKey = childNode.privateKey;\n }\n // privkey wallet\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.PrivateKey && !privateKey) {\n // @ts-ignore\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_9__.generateRandomBytes)(32));\n }\n if (privateKey?.length) {\n // @ts-ignore\n this.privateKey = privateKey;\n privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.encodePrivateKeyWif)(privateKey, this.network === _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Regtest\n ? _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Testnet\n : this.network);\n }\n // wif wallet\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif && !privateKeyWif) {\n // @ts-ignore\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_9__.generateRandomBytes)(32));\n privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.encodePrivateKeyWif)(this.privateKey, this.network === _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Regtest\n ? _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Testnet\n : this.network);\n }\n if (privateKeyWif?.length) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_11__.checkWifNetwork)(privateKeyWif, this.network);\n // @ts-ignore\n this.privateKeyWif = privateKeyWif;\n if (!this.privateKey) {\n // @ts-ignore\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.decodePrivateKeyWif)(privateKeyWif)).privateKey;\n }\n publicKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.secp256k1.derivePublicKeyUncompressed(this.privateKey));\n publicKeyCompressed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.secp256k1.compressPublicKey(publicKey));\n }\n // rest cases are for watch wallets\n await super.initialize({\n name,\n publicKey,\n publicKeyCompressed,\n publicKeyHash,\n address,\n });\n if (this.privateKey) {\n // @ts-ignore\n this.walletCache = new Map().set(this.cashaddr, { privateKey: this.privateKey });\n }\n return this;\n }\n //#endregion Constructors and Statics\n //#region Accessors\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 // 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_13__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__.binToHex)(this.privateKey) : undefined,\n privateKeyWif: this.privateKeyWif,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\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 const seed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.deriveSeedFromBip39Mnemonic)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_5__.checkForEmptySeed)(seed);\n const hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true, // TODO: we should switch to libauth's BIP39 implementation and set this to false\n throwErrors: true,\n });\n const 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 const childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n const node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n const xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n }, {\n throwErrors: true,\n }).hdPublicKey;\n const key = new _model_js__WEBPACK_IMPORTED_MODULE_14__.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 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_15__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n //#endregion\n //#region Statics\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 * fromPrivateKey - create a wallet using the private key supplied in hex or Uint8Array\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromPrivateKey(privateKey) {\n return new this().fromPrivateKey(privateKey);\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 * fromSeed - create a wallet using the seed phrase and derivation path\n *\n * unless specified the derivation path m/44'/0'/0'/0/0 will be used\n *\n * @param mnemonic 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(mnemonic, derivationPath) {\n return new this().fromSeed(mnemonic, 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 // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n if (!mnemonic.length) {\n throw Error(\"refusing to create wallet from empty mnemonic\");\n }\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Seed;\n await this.initialize({ mnemonic, derivationPath });\n return this;\n }\n // Initialize wallet from private key in hex or Uint8Array\n async fromPrivateKey(privateKey) {\n if (typeof privateKey === \"string\") {\n privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__.hexToBin)(privateKey);\n }\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.PrivateKey;\n await this.initialize({ privateKey });\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(privateKeyWif) {\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif;\n await this.initialize({ privateKeyWif });\n return this;\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 dbName = dbName ? dbName : this.networkPrefix;\n if (name.length > 0) {\n return this.named(name, dbName);\n }\n else {\n return this.initialize();\n }\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 if (this.name) {\n return `named:${this.network}:${this.name}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.PrivateKey) {\n return `${this.walletType}:${this.network}:${(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__.binToHex)(this.privateKey)}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch) {\n return super.toString();\n }\n throw Error(\"toString unsupported wallet type\");\n }\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_2__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.PrivateKey) {\n return `${this.walletType}:${this.network}:${(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__.binToHex)(this.privateKey)}`;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch) {\n return super.toDbString();\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\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 this.sendMaxRaw(cashaddr, options, this.privateKey);\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, privateKey) {\n privateKey = privateKey ?? this.privateKey;\n if (!privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Missing private key`);\n }\n return super.encodeTransaction(requests, discardChange, options, privateKey);\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_16__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n //#endregion Funds\n //#region Signing\n // Convenience wrapper to sign interface\n sign(message, privateKey = undefined) {\n return super.sign(message, privateKey ?? this.privateKey);\n }\n}\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.CashAddressNetworkPrefix.testnet; }\n static { this.faucetServer = \"https://rest-unstable.mainnet.cash\"; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Testnet);\n }\n}\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.CashAddressNetworkPrefix.regtest; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Regtest);\n }\n}\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.CashAddressNetworkPrefix.mainnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif);\n }\n}\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.CashAddressNetworkPrefix.testnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif);\n }\n}\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.CashAddressNetworkPrefix.regtest; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
637
+ 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 */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/bip39.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _Watch_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Watch.js */ \"./src/wallet/Watch.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Watch_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_11__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__, _model_js__WEBPACK_IMPORTED_MODULE_14__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__]);\n([_Watch_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_11__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__, _model_js__WEBPACK_IMPORTED_MODULE_14__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Watch_js__WEBPACK_IMPORTED_MODULE_0__.WatchWallet {\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Seed) {\n super(name, network);\n this.derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath + \"/0/0\";\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath;\n //#endregion Constructors\n //#region Protected implementations\n this.fromId = async (walletId) => {\n const [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (this.network !== networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n switch (walletType) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.PrivateKey:\n return this.fromPrivateKey(arg1);\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif:\n return this.fromWIF(arg1);\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.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 _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.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 _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.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 this.name = name;\n // @ts-ignore\n this.walletType = walletType;\n }\n /// Initialize the wallet given the options mnemonic, privateKey or publicKey variations\n /// If none provided, a new random mnemonic will be generated\n /// If mnemonic or private key provided, the wallet will be able to sign transactions\n /// Otherwise, the wallet will be watch-only\n /// This internal method is called by the various static constructors\n async initialize({ name = \"\", mnemonic = undefined, derivationPath = undefined, privateKey = undefined, privateKeyWif = undefined, publicKey = undefined, publicKeyCompressed = undefined, publicKeyHash = undefined, address = undefined, } = {}) {\n // seed wallet\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Seed && !mnemonic) {\n mnemonic = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.generateBip39Mnemonic)();\n }\n if (mnemonic?.length) {\n mnemonic = mnemonic.trim().toLowerCase();\n if (![12, 24].includes(mnemonic.split(\" \").length)) {\n throw Error(\"Invalid mnemonic, must be 12 or 24 words\");\n }\n if (derivationPath) {\n // @ts-ignore\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n const path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n // @ts-ignore\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n else {\n derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath + \"/0/0\";\n // @ts-ignore\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultParentDerivationPath;\n }\n // @ts-ignore\n this.mnemonic = mnemonic;\n // @ts-ignore\n this.derivationPath = derivationPath;\n const seed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.deriveSeedFromBip39Mnemonic)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_5__.checkForEmptySeed)(seed);\n const rootNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true,\n throwErrors: true,\n });\n const parentNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPath)(rootNode, this.parentDerivationPath);\n // @ts-ignore\n this.parentXPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.encodeHdPublicKey)({\n node: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPublicNode)(parentNode),\n network: this.network === _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Mainnet ? \"mainnet\" : \"testnet\",\n })).hdPublicKey;\n const childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPath)(rootNode, this.derivationPath);\n privateKey = childNode.privateKey;\n }\n // privkey wallet\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.PrivateKey && !privateKey) {\n // @ts-ignore\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_9__.generateRandomBytes)(32));\n }\n if (privateKey?.length) {\n // @ts-ignore\n this.privateKey = privateKey;\n privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.encodePrivateKeyWif)(privateKey, this.network === _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Regtest\n ? _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Testnet\n : this.network);\n }\n // wif wallet\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif && !privateKeyWif) {\n // @ts-ignore\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_9__.generateRandomBytes)(32));\n privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.encodePrivateKeyWif)(this.privateKey, this.network === _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Regtest\n ? _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Testnet\n : this.network);\n }\n if (privateKeyWif?.length) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_11__.checkWifNetwork)(privateKeyWif, this.network);\n // @ts-ignore\n this.privateKeyWif = privateKeyWif;\n if (!this.privateKey) {\n // @ts-ignore\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.decodePrivateKeyWif)(privateKeyWif)).privateKey;\n }\n publicKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.secp256k1.derivePublicKeyUncompressed(this.privateKey));\n publicKeyCompressed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.secp256k1.compressPublicKey(publicKey));\n }\n // rest cases are for watch wallets\n await super.initialize({\n name,\n publicKey,\n publicKeyCompressed,\n publicKeyHash,\n address,\n });\n return this;\n }\n //#endregion Constructors and Statics\n //#region Accessors\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 // 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_13__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__.binToHex)(this.privateKey) : undefined,\n privateKeyWif: this.privateKeyWif,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\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 const seed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.deriveSeedFromBip39Mnemonic)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_5__.checkForEmptySeed)(seed);\n const hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true, // TODO: we should switch to libauth's BIP39 implementation and set this to false\n throwErrors: true,\n });\n const 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 const childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n const node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n const xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n }, {\n throwErrors: true,\n }).hdPublicKey;\n const key = new _model_js__WEBPACK_IMPORTED_MODULE_14__.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 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_15__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n //#endregion\n //#region Statics\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 * fromPrivateKey - create a wallet using the private key supplied in hex or Uint8Array\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromPrivateKey(privateKey) {\n return new this().fromPrivateKey(privateKey);\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 * fromSeed - create a wallet using the seed phrase and derivation path\n *\n * unless specified the derivation path m/44'/0'/0'/0/0 will be used\n *\n * @param mnemonic 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(mnemonic, derivationPath) {\n return new this().fromSeed(mnemonic, 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 // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n if (!mnemonic.length) {\n throw Error(\"refusing to create wallet from empty mnemonic\");\n }\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Seed;\n await this.initialize({ mnemonic, derivationPath });\n return this;\n }\n // Initialize wallet from private key in hex or Uint8Array\n async fromPrivateKey(privateKey) {\n if (typeof privateKey === \"string\") {\n privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__.hexToBin)(privateKey);\n }\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.PrivateKey;\n await this.initialize({ privateKey });\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(privateKeyWif) {\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif;\n await this.initialize({ privateKeyWif });\n return this;\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 dbName = dbName ? dbName : this.networkPrefix;\n if (name.length > 0) {\n return this.named(name, dbName);\n }\n else {\n return this.initialize();\n }\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 if (this.name) {\n return `named:${this.network}:${this.name}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.PrivateKey) {\n return `${this.walletType}:${this.network}:${(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__.binToHex)(this.privateKey)}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch) {\n return super.toString();\n }\n throw Error(\"toString unsupported wallet type\");\n }\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_2__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.PrivateKey) {\n return `${this.walletType}:${this.network}:${(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_13__.binToHex)(this.privateKey)}`;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Watch) {\n return super.toDbString();\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\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 this.sendMaxRaw(cashaddr, options, this.privateKey);\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, privateKey) {\n privateKey = privateKey ?? this.privateKey;\n if (!privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Missing private key`);\n }\n return super.encodeTransaction(requests, discardChange, options, privateKey);\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_16__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n //#endregion Funds\n //#region Signing\n // Convenience wrapper to sign interface\n sign(message, privateKey = undefined) {\n return super.sign(message, privateKey ?? this.privateKey);\n }\n}\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.CashAddressNetworkPrefix.testnet; }\n static { this.faucetServer = \"https://rest-unstable.mainnet.cash\"; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Testnet);\n }\n}\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.CashAddressNetworkPrefix.regtest; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Regtest);\n }\n}\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.CashAddressNetworkPrefix.mainnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif);\n }\n}\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.CashAddressNetworkPrefix.testnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif);\n }\n}\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_17__.CashAddressNetworkPrefix.regtest; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_2__.WalletTypeEnum.Wif);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
678
638
 
679
639
  /***/ }),
680
640
 
@@ -1748,163 +1708,103 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
1748
1708
 
1749
1709
  /***/ }),
1750
1710
 
1751
- /***/ "../../node_modules/@electrum-cash/debug-logs/dist/index.mjs":
1752
- /*!*******************************************************************!*\
1753
- !*** ../../node_modules/@electrum-cash/debug-logs/dist/index.mjs ***!
1754
- \*******************************************************************/
1755
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1756
-
1757
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ $9de8c596df24b669$export$2e2bcd8739ae039)\n/* harmony export */ });\n/* harmony import */ var debug__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! debug */ \"../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/browser.js\");\n\n\n// Import 3rd party debug library.\n\n// Create the debugging log channels.\nconst $9de8c596df24b669$var$debug = {\n client: (0, debug__WEBPACK_IMPORTED_MODULE_0__)(\"electrum-cash:client \"),\n errors: (0, debug__WEBPACK_IMPORTED_MODULE_0__)(\"electrum-cash:error \"),\n warning: (0, debug__WEBPACK_IMPORTED_MODULE_0__)(\"electrum-cash:warning\"),\n network: (0, debug__WEBPACK_IMPORTED_MODULE_0__)(\"electrum-cash:network\"),\n ping: (0, debug__WEBPACK_IMPORTED_MODULE_0__)(\"electrum-cash:pulses \")\n};\n// Set log channel colors.\n$9de8c596df24b669$var$debug.client.color = \"2\";\n$9de8c596df24b669$var$debug.errors.color = \"9\";\n$9de8c596df24b669$var$debug.warning.color = \"13\";\n$9de8c596df24b669$var$debug.network.color = \"4\";\n$9de8c596df24b669$var$debug.ping.color = \"8\";\nvar // Export the logs channels.\n$9de8c596df24b669$export$2e2bcd8739ae039 = $9de8c596df24b669$var$debug;\n\n\n\n//# sourceMappingURL=index.mjs.map\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@electrum-cash/debug-logs/dist/index.mjs?");
1758
-
1759
- /***/ }),
1760
-
1761
- /***/ "../../node_modules/@electrum-cash/network/dist/index.mjs":
1762
- /*!****************************************************************!*\
1763
- !*** ../../node_modules/@electrum-cash/network/dist/index.mjs ***!
1764
- \****************************************************************/
1765
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1766
-
1767
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ConnectionStatus\": () => (/* binding */ ConnectionStatus),\n/* harmony export */ \"ElectrumClient\": () => (/* binding */ electrum_client_default)\n/* harmony export */ });\n/* unused harmony exports isRPCErrorResponse, isRPCNotification, isRPCRequest, isRPCStatement, isVersionNegotiated, isVersionRejected */\n/* harmony import */ var _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @electrum-cash/debug-logs */ \"../../node_modules/@electrum-cash/debug-logs/dist/index.mjs\");\n/* harmony import */ var _electrum_cash_web_socket__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @electrum-cash/web-socket */ \"../../node_modules/@electrum-cash/web-socket/dist/index.mjs\");\n/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! eventemitter3 */ \"../../node_modules/eventemitter3/index.mjs\");\n/* harmony import */ var lossless_json__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lossless-json */ \"../../node_modules/lossless-json/lib/esm/index.js\");\n/* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! async-mutex */ \"../../node_modules/async-mutex/index.mjs\");\n\n\n\n\n\n\n//#region source/electrum-protocol.ts\n/**\n* Grouping of utilities that simplifies implementation of the Electrum protocol.\n*\n* @ignore\n*/\nvar ElectrumProtocol = class {\n\t/**\n\t* Helper function that builds an Electrum request object.\n\t*\n\t* @param method - method to call.\n\t* @param parameters - method parameters for the call.\n\t* @param requestId - unique string or number referencing this request.\n\t*\n\t* @returns a properly formatted Electrum request string.\n\t*/\n\tstatic buildRequestObject(method, parameters, requestId) {\n\t\treturn JSON.stringify({\n\t\t\tmethod,\n\t\t\tparams: parameters,\n\t\t\tid: requestId\n\t\t});\n\t}\n\t/**\n\t* Constant used to verify if a provided string is a valid version number.\n\t*\n\t* @returns a regular expression that matches valid version numbers.\n\t*/\n\tstatic get versionRegexp() {\n\t\treturn /^\\d+(\\.\\d+)+$/;\n\t}\n\t/**\n\t* Constant used to separate statements/messages in a stream of data.\n\t*\n\t* @returns the delimiter used by Electrum to separate statements.\n\t*/\n\tstatic get statementDelimiter() {\n\t\treturn \"\\n\";\n\t}\n};\n\n//#endregion\n//#region source/rpc-interfaces.ts\nconst isRPCErrorResponse = function(message) {\n\treturn \"id\" in message && \"error\" in message;\n};\nconst isRPCStatement = function(message) {\n\treturn \"id\" in message && \"result\" in message;\n};\nconst isRPCNotification = function(message) {\n\treturn !(\"id\" in message) && \"method\" in message;\n};\nconst isRPCRequest = function(message) {\n\treturn \"id\" in message && \"method\" in message;\n};\n\n//#endregion\n//#region source/enums.ts\n/**\n* Enum that denotes the connection status of an ElectrumConnection.\n* @enum {number}\n* @property {0} DISCONNECTED The connection is disconnected.\n* @property {1} AVAILABLE The connection is connected.\n* @property {2} DISCONNECTING The connection is disconnecting.\n* @property {3} CONNECTING The connection is connecting.\n* @property {4} RECONNECTING The connection is restarting.\n*/\nlet ConnectionStatus = /* @__PURE__ */ function(ConnectionStatus$1) {\n\tConnectionStatus$1[ConnectionStatus$1[\"DISCONNECTED\"] = 0] = \"DISCONNECTED\";\n\tConnectionStatus$1[ConnectionStatus$1[\"CONNECTED\"] = 1] = \"CONNECTED\";\n\tConnectionStatus$1[ConnectionStatus$1[\"DISCONNECTING\"] = 2] = \"DISCONNECTING\";\n\tConnectionStatus$1[ConnectionStatus$1[\"CONNECTING\"] = 3] = \"CONNECTING\";\n\tConnectionStatus$1[ConnectionStatus$1[\"RECONNECTING\"] = 4] = \"RECONNECTING\";\n\treturn ConnectionStatus$1;\n}({});\n\n//#endregion\n//#region source/interfaces.ts\n/**\n* @ignore\n*/\nconst isVersionRejected = function(object) {\n\treturn \"error\" in object;\n};\n/**\n* @ignore\n*/\nconst isVersionNegotiated = function(object) {\n\treturn \"software\" in object && \"protocol\" in object;\n};\n\n//#endregion\n//#region source/electrum-connection.ts\n/**\n* Wrapper around TLS/WSS sockets that gracefully separates a network stream into Electrum protocol messages.\n*/\nvar ElectrumConnection = class extends eventemitter3__WEBPACK_IMPORTED_MODULE_2__.EventEmitter {\n\tstatus = ConnectionStatus.DISCONNECTED;\n\tlastReceivedTimestamp;\n\tsocket;\n\tkeepAliveTimer;\n\treconnectTimer;\n\tverifications = [];\n\tmessageBuffer = \"\";\n\t/**\n\t* Sets up network configuration for an Electrum client connection.\n\t*\n\t* @param application - your application name, used to identify to the electrum host.\n\t* @param version - protocol version to use with the host.\n\t* @param socketOrHostname - pre-configured electrum socket or fully qualified domain name or IP number of the host\n\t* @param options - ...\n\t*\n\t* @throws {Error} if `version` is not a valid version string.\n\t*/\n\tconstructor(application, version, socketOrHostname, options) {\n\t\tsuper();\n\t\tthis.application = application;\n\t\tthis.version = version;\n\t\tthis.socketOrHostname = socketOrHostname;\n\t\tthis.options = options;\n\t\tif (!ElectrumProtocol.versionRegexp.test(version)) throw /* @__PURE__ */ new Error(`Provided version string (${version}) is not a valid protocol version number.`);\n\t\tif (typeof socketOrHostname === \"string\") this.socket = new _electrum_cash_web_socket__WEBPACK_IMPORTED_MODULE_1__.ElectrumWebSocket(socketOrHostname, void 0, void 0, void 0, this.options);\n\t\telse this.socket = socketOrHostname;\n\t\tthis.socket.on(\"connected\", this.onSocketConnect.bind(this));\n\t\tthis.socket.on(\"disconnected\", this.onSocketDisconnect.bind(this));\n\t\tthis.socket.on(\"data\", this.parseMessageChunk.bind(this));\n\t}\n\tget hostIdentifier() {\n\t\treturn this.socket.hostIdentifier;\n\t}\n\tget encrypted() {\n\t\treturn this.socket.encrypted;\n\t}\n\t/**\n\t* Assembles incoming data into statements and hands them off to the message parser.\n\t*\n\t* @param data - data to append to the current message buffer, as a string.\n\t*\n\t* @throws {SyntaxError} if the passed statement parts are not valid JSON.\n\t*/\n\tparseMessageChunk(data) {\n\t\tthis.lastReceivedTimestamp = Date.now();\n\t\tthis.emit(\"received\");\n\t\tthis.verifications.forEach((timer) => clearTimeout(timer));\n\t\tthis.verifications.length = 0;\n\t\tthis.messageBuffer += data;\n\t\twhile (this.messageBuffer.includes(ElectrumProtocol.statementDelimiter)) {\n\t\t\tconst statementParts = this.messageBuffer.split(ElectrumProtocol.statementDelimiter);\n\t\t\twhile (statementParts.length > 1) {\n\t\t\t\tlet statementList = (0,lossless_json__WEBPACK_IMPORTED_MODULE_3__.parse)(String(statementParts.shift()), null, this.options.useBigInt ? lossless_json__WEBPACK_IMPORTED_MODULE_3__.parseNumberAndBigInt : parseFloat);\n\t\t\t\tif (!Array.isArray(statementList)) statementList = [statementList];\n\t\t\t\twhile (statementList.length > 0) {\n\t\t\t\t\tconst currentStatement = statementList.shift();\n\t\t\t\t\tif (isRPCNotification(currentStatement)) {\n\t\t\t\t\t\tthis.emit(\"response\", currentStatement);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (currentStatement.id === \"versionNegotiation\") {\n\t\t\t\t\t\tif (isRPCErrorResponse(currentStatement)) this.emit(\"version\", { error: currentStatement.error });\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconst [software, protocol] = currentStatement.result;\n\t\t\t\t\t\t\tthis.emit(\"version\", {\n\t\t\t\t\t\t\t\tsoftware,\n\t\t\t\t\t\t\t\tprotocol\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (currentStatement.id === \"keepAlive\") continue;\n\t\t\t\t\tthis.emit(\"response\", currentStatement);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.messageBuffer = statementParts.shift() || \"\";\n\t\t}\n\t}\n\t/**\n\t* Sends a keep-alive message to the host.\n\t*\n\t* @returns true if the ping message was fully flushed to the socket, false if\n\t* part of the message is queued in the user memory\n\t*/\n\tping() {\n\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].ping(`Sending keep-alive ping to '${this.hostIdentifier}'`);\n\t\tconst message = ElectrumProtocol.buildRequestObject(\"server.ping\", [], \"keepAlive\");\n\t\treturn this.send(message);\n\t}\n\t/**\n\t* Initiates the network connection negotiates a protocol version. Also emits the 'connect' signal if successful.\n\t*\n\t* @throws {Error} if the socket connection fails.\n\t* @returns a promise resolving when the connection is established\n\t*/\n\tasync connect() {\n\t\tif (this.status === ConnectionStatus.CONNECTED) return;\n\t\tthis.status = ConnectionStatus.CONNECTING;\n\t\tthis.emit(\"connecting\");\n\t\tconst connectionResolver = (resolve, reject) => {\n\t\t\tthis.once(\"connected\", () => {\n\t\t\t\tthis.removeListener(\"disconnected\", reject);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t\tthis.once(\"disconnected\", () => {\n\t\t\t\tthis.removeListener(\"connected\", resolve);\n\t\t\t\treject();\n\t\t\t});\n\t\t\tthis.socket.connect();\n\t\t};\n\t\tawait new Promise(connectionResolver);\n\t}\n\t/**\n\t* Restores the network connection.\n\t*/\n\tasync reconnect() {\n\t\tawait this.clearReconnectTimer();\n\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].network(`Trying to reconnect to '${this.hostIdentifier}'..`);\n\t\tthis.status = ConnectionStatus.RECONNECTING;\n\t\tthis.emit(\"reconnecting\");\n\t\tthis.socket.disconnect();\n\t\ttry {\n\t\t\tawait this.connect();\n\t\t} catch (_error) {}\n\t}\n\t/**\n\t* Removes the current reconnect timer.\n\t*/\n\tclearReconnectTimer() {\n\t\tif (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n\t\tthis.reconnectTimer = void 0;\n\t}\n\t/**\n\t* Removes the current keep-alive timer.\n\t*/\n\tclearKeepAliveTimer() {\n\t\tif (this.keepAliveTimer) clearTimeout(this.keepAliveTimer);\n\t\tthis.keepAliveTimer = void 0;\n\t}\n\t/**\n\t* Initializes the keep alive timer loop.\n\t*/\n\tsetupKeepAliveTimer() {\n\t\tif (!this.keepAliveTimer) this.keepAliveTimer = setTimeout(this.ping.bind(this), this.options.sendKeepAliveIntervalInMilliSeconds);\n\t}\n\t/**\n\t* Tears down the current connection and removes all event listeners on disconnect.\n\t*\n\t* @param force - disconnect even if the connection has not been fully established yet.\n\t* @param intentional - update connection state if disconnect is intentional.\n\t*\n\t* @returns true if successfully disconnected, or false if there was no connection.\n\t*/\n\tasync disconnect(force = false, intentional = true) {\n\t\tif (this.status === ConnectionStatus.DISCONNECTED && !force) return false;\n\t\tif (intentional) this.status = ConnectionStatus.DISCONNECTING;\n\t\tthis.emit(\"disconnecting\");\n\t\tawait this.clearKeepAliveTimer();\n\t\tawait this.clearReconnectTimer();\n\t\tconst disconnectResolver = (resolve) => {\n\t\t\tthis.once(\"disconnected\", () => resolve(true));\n\t\t\tthis.socket.disconnect();\n\t\t};\n\t\treturn new Promise(disconnectResolver);\n\t}\n\t/**\n\t* Sends an arbitrary message to the server.\n\t*\n\t* @param message - json encoded request object to send to the server, as a string.\n\t*\n\t* @returns true if the message was fully flushed to the socket, false if part of the message\n\t* is queued in the user memory\n\t*/\n\tsend(message) {\n\t\tthis.clearKeepAliveTimer();\n\t\tconst currentTime = Date.now();\n\t\tconst verificationTimer = setTimeout(this.verifySend.bind(this, currentTime), this.socket.timeout);\n\t\tthis.verifications.push(verificationTimer);\n\t\tthis.setupKeepAliveTimer();\n\t\treturn this.socket.write(message + ElectrumProtocol.statementDelimiter);\n\t}\n\t/**\n\t* Marks the connection as timed out and schedules reconnection if we have not\n\t* received data within the expected time frame.\n\t*/\n\tverifySend(sentTimestamp) {\n\t\tif (Number(this.lastReceivedTimestamp) < sentTimestamp) {\n\t\t\tif (this.status === ConnectionStatus.DISCONNECTED || this.status === ConnectionStatus.DISCONNECTING) return;\n\t\t\tthis.clearKeepAliveTimer();\n\t\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].network(`Connection to '${this.hostIdentifier}' timed out.`);\n\t\t\tthis.socket.disconnect();\n\t\t}\n\t}\n\t/**\n\t* Updates the connection status when a connection is confirmed.\n\t*/\n\tasync onSocketConnect() {\n\t\tthis.clearReconnectTimer();\n\t\tthis.lastReceivedTimestamp = Date.now();\n\t\tthis.setupKeepAliveTimer();\n\t\tawait new Promise(this.negotiateVersion.bind(this));\n\t\tthis.emit(\"connected\");\n\t\tthis.socket.removeAllListeners(\"error\");\n\t\tthis.socket.on(\"error\", this.onSocketError.bind(this));\n\t}\n\t/**\n\t* Updates the connection status when a connection is ended.\n\t*/\n\tonSocketDisconnect() {\n\t\tthis.clearKeepAliveTimer();\n\t\tif (this.status === ConnectionStatus.DISCONNECTING) {\n\t\t\tthis.status = ConnectionStatus.DISCONNECTED;\n\t\t\tthis.emit(\"disconnected\");\n\t\t\tthis.clearReconnectTimer();\n\t\t\tthis.removeAllListeners();\n\t\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].network(`Disconnected from '${this.hostIdentifier}'.`);\n\t\t} else {\n\t\t\tif (this.status === ConnectionStatus.CONNECTED) _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].errors(`Connection with '${this.hostIdentifier}' was closed, trying to reconnect in ${this.options.reconnectAfterMilliSeconds / 1e3} seconds.`);\n\t\t\tthis.status = ConnectionStatus.DISCONNECTED;\n\t\t\tthis.emit(\"disconnected\");\n\t\t\tif (!this.reconnectTimer) this.reconnectTimer = setTimeout(this.reconnect.bind(this), this.options.reconnectAfterMilliSeconds);\n\t\t}\n\t}\n\t/**\n\t* Notify administrator of any unexpected errors.\n\t*/\n\tonSocketError(error) {\n\t\tif (typeof error === \"undefined\") return;\n\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].errors(`Network error ('${this.hostIdentifier}'): `, error);\n\t}\n\t/**\n\t* Negotiate the protocol version with the server.\n\t* Disconnect the connection if the version negotiation fails.\n\t* @param resolve \n\t* @param reject \n\t*/\n\tasync negotiateVersion(resolve, reject) {\n\t\tconst rejector = (error) => {\n\t\t\tthis.status = ConnectionStatus.DISCONNECTED;\n\t\t\tthis.emit(\"disconnected\");\n\t\t\treject(error);\n\t\t};\n\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].network(`Requesting protocol version ${this.version} with '${this.hostIdentifier}'.`);\n\t\tthis.socket.once(\"error\", rejector);\n\t\tconst versionMessage = ElectrumProtocol.buildRequestObject(\"server.version\", [this.application, this.version], \"versionNegotiation\");\n\t\tconst versionValidator = (version) => {\n\t\t\tif (isVersionRejected(version)) {\n\t\t\t\tthis.disconnect(true);\n\t\t\t\tconst errorMessage = \"unsupported protocol version.\";\n\t\t\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].errors(`Failed to connect with ${this.hostIdentifier} due to ${errorMessage}`);\n\t\t\t\treject(errorMessage);\n\t\t\t} else if (version.protocol !== this.version && `${version.protocol}.0` !== this.version && `${version.protocol}.0.0` !== this.version) {\n\t\t\t\tthis.disconnect(true);\n\t\t\t\tconst errorMessage = `incompatible protocol version negotiated (${version.protocol} !== ${this.version}).`;\n\t\t\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].errors(`Failed to connect with ${this.hostIdentifier} due to ${errorMessage}`);\n\t\t\t\treject(errorMessage);\n\t\t\t} else {\n\t\t\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].network(`Negotiated protocol version ${version.protocol} with '${this.hostIdentifier}', powered by ${version.software}.`);\n\t\t\t\tthis.status = ConnectionStatus.CONNECTED;\n\t\t\t\tresolve();\n\t\t\t}\n\t\t};\n\t\tthis.once(\"version\", versionValidator);\n\t\tthis.send(versionMessage);\n\t}\n};\n\n//#endregion\n//#region source/constants.ts\nconst MILLI_SECONDS_PER_SECOND = 1e3;\n/**\n* Configure default options.\n*/\nconst defaultNetworkOptions = {\n\tuseBigInt: false,\n\tsendKeepAliveIntervalInMilliSeconds: 1 * MILLI_SECONDS_PER_SECOND,\n\treconnectAfterMilliSeconds: 5 * MILLI_SECONDS_PER_SECOND,\n\tverifyConnectionTimeoutInMilliSeconds: 5 * MILLI_SECONDS_PER_SECOND,\n\tdisableBrowserVisibilityHandling: false,\n\tdisableBrowserConnectivityHandling: false\n};\n\n//#endregion\n//#region source/electrum-client.ts\n/**\n* High-level Electrum client that lets applications send requests and subscribe to notification events from a server.\n*/\nvar ElectrumClient = class extends eventemitter3__WEBPACK_IMPORTED_MODULE_2__.EventEmitter {\n\t/**\n\t* The name and version of the server software indexing the blockchain.\n\t*/\n\tsoftware;\n\t/**\n\t* The genesis hash of the blockchain indexed by the server.\n\t* @remarks This is only available after a 'server.features' call.\n\t*/\n\tgenesisHash;\n\t/**\n\t* The chain height of the blockchain indexed by the server.\n\t* @remarks This is only available after a 'blockchain.headers.subscribe' call.\n\t*/\n\tchainHeight;\n\t/**\n\t* Timestamp of when we last received data from the server indexing the blockchain.\n\t*/\n\tlastReceivedTimestamp;\n\t/**\n\t* Number corresponding to the underlying connection status.\n\t*/\n\tget status() {\n\t\treturn this.connection.status;\n\t}\n\tconnection;\n\tsubscriptionMethods = {};\n\trequestId = 0;\n\trequestResolvers = {};\n\tconnectionLock = new async_mutex__WEBPACK_IMPORTED_MODULE_4__.Mutex();\n\t/**\n\t* Initializes an Electrum client.\n\t*\n\t* @param application - your application name, used to identify to the electrum host.\n\t* @param version - protocol version to use with the host.\n\t* @param socketOrHostname - pre-configured electrum socket or fully qualified domain name or IP number of the host\n\t* @param options - ...\n\t*\n\t* @throws {Error} if `version` is not a valid version string.\n\t*/\n\tconstructor(application, version, socketOrHostname, options = {}) {\n\t\tsuper();\n\t\tthis.application = application;\n\t\tthis.version = version;\n\t\tthis.socketOrHostname = socketOrHostname;\n\t\tthis.options = options;\n\t\tthis.connection = new ElectrumConnection(application, version, socketOrHostname, {\n\t\t\t...defaultNetworkOptions,\n\t\t\t...options\n\t\t});\n\t}\n\tget hostIdentifier() {\n\t\treturn this.connection.hostIdentifier;\n\t}\n\tget encrypted() {\n\t\treturn this.connection.encrypted;\n\t}\n\t/**\n\t* Connects to the remote server.\n\t*\n\t* @throws {Error} if the socket connection fails.\n\t* @returns a promise resolving when the connection is established.\n\t*/\n\tasync connect() {\n\t\tconst unlock = await this.connectionLock.acquire();\n\t\ttry {\n\t\t\tif (this.connection.status === ConnectionStatus.CONNECTED) return;\n\t\t\tthis.connection.on(\"response\", this.response.bind(this));\n\t\t\tthis.connection.on(\"connected\", this.resubscribeOnConnect.bind(this));\n\t\t\tthis.connection.on(\"disconnected\", this.onConnectionDisconnect.bind(this));\n\t\t\tthis.connection.on(\"connecting\", this.handleConnectionStatusChanges.bind(this, \"connecting\"));\n\t\t\tthis.connection.on(\"disconnecting\", this.handleConnectionStatusChanges.bind(this, \"disconnecting\"));\n\t\t\tthis.connection.on(\"reconnecting\", this.handleConnectionStatusChanges.bind(this, \"reconnecting\"));\n\t\t\tthis.connection.on(\"version\", this.storeSoftwareVersion.bind(this));\n\t\t\tthis.connection.on(\"received\", this.updateLastReceivedTimestamp.bind(this));\n\t\t\tthis.connection.on(\"error\", this.emit.bind(this, \"error\"));\n\t\t\tawait this.connection.connect();\n\t\t} finally {\n\t\t\tunlock();\n\t\t}\n\t}\n\t/**\n\t* Disconnects from the remote server and removes all event listeners/subscriptions and open requests.\n\t*\n\t* @param force - disconnect even if the connection has not been fully established yet.\n\t* @param retainSubscriptions - retain subscription data so they will be restored on reconnection.\n\t*\n\t* @returns true if successfully disconnected, or false if there was no connection.\n\t*/\n\tasync disconnect(force = false, retainSubscriptions = false) {\n\t\tif (!retainSubscriptions) {\n\t\t\tthis.removeAllListeners();\n\t\t\tthis.subscriptionMethods = {};\n\t\t}\n\t\treturn this.connection.disconnect(force);\n\t}\n\t/**\n\t* Calls a method on the remote server with the supplied parameters.\n\t*\n\t* @param method - name of the method to call.\n\t* @param parameters - one or more parameters for the method.\n\t*\n\t* @throws {Error} if the client is disconnected.\n\t* @returns a promise that resolves with the result of the method or an Error.\n\t*/\n\tasync request(method, ...parameters) {\n\t\tif (this.connection.status !== ConnectionStatus.CONNECTED) throw /* @__PURE__ */ new Error(`Unable to send request to a disconnected server '${this.hostIdentifier}'.`);\n\t\tthis.requestId += 1;\n\t\tconst id = this.requestId;\n\t\tconst message = ElectrumProtocol.buildRequestObject(method, parameters, id);\n\t\tconst requestResolver = (resolve) => {\n\t\t\tthis.requestResolvers[id] = (error, data) => {\n\t\t\t\tif (error) resolve(error);\n\t\t\t\telse resolve(data);\n\t\t\t};\n\t\t\tthis.connection.send(message);\n\t\t};\n\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].network(`Sending request '${method}' to '${this.hostIdentifier}'`);\n\t\treturn new Promise(requestResolver);\n\t}\n\t/**\n\t* Subscribes to the method and payload at the server.\n\t*\n\t* @remarks the response for the subscription request is issued as a notification event.\n\t*\n\t* @param method - one of the subscribable methods the server supports.\n\t* @param parameters - one or more parameters for the method.\n\t*\n\t* @throws {Error} if the client is disconnected.\n\t* @returns a promise resolving when the subscription is established.\n\t*/\n\tasync subscribe(method, ...parameters) {\n\t\tif (!this.subscriptionMethods[method]) this.subscriptionMethods[method] = /* @__PURE__ */ new Set();\n\t\tthis.subscriptionMethods[method].add(JSON.stringify(parameters));\n\t\tconst requestData = await this.request(method, ...parameters);\n\t\tif (requestData instanceof Error) throw requestData;\n\t\tif (Array.isArray(requestData)) throw /* @__PURE__ */ new Error(\"Subscription request returned an more than one data point.\");\n\t\tconst notification = {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tmethod,\n\t\t\tparams: [...parameters, requestData]\n\t\t};\n\t\tthis.emit(\"notification\", notification);\n\t\tthis.updateChainHeightFromHeadersNotifications(notification);\n\t}\n\t/**\n\t* Unsubscribes to the method at the server and removes any callback functions\n\t* when there are no more subscriptions for the method.\n\t*\n\t* @param method - a previously subscribed to method.\n\t* @param parameters - one or more parameters for the method.\n\t*\n\t* @throws {Error} if no subscriptions exist for the combination of the provided `method` and `parameters.\n\t* @throws {Error} if the client is disconnected.\n\t* @returns a promise resolving when the subscription is removed.\n\t*/\n\tasync unsubscribe(method, ...parameters) {\n\t\tif (this.connection.status !== ConnectionStatus.CONNECTED) throw /* @__PURE__ */ new Error(`Unable to send unsubscribe request to a disconnected server '${this.hostIdentifier}'.`);\n\t\tif (!this.subscriptionMethods[method]) throw /* @__PURE__ */ new Error(`Cannot unsubscribe from '${method}' since the method has no subscriptions.`);\n\t\tconst subscriptionParameters = JSON.stringify(parameters);\n\t\tif (!this.subscriptionMethods[method].has(subscriptionParameters)) throw /* @__PURE__ */ new Error(`Cannot unsubscribe from '${method}' since it has no subscription with the given parameters.`);\n\t\tthis.subscriptionMethods[method].delete(subscriptionParameters);\n\t\tawait this.request(method.replace(\".subscribe\", \".unsubscribe\"), ...parameters);\n\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].client(`Unsubscribed from '${String(method)}' for the '${subscriptionParameters}' parameters.`);\n\t}\n\t/**\n\t* Restores existing subscriptions without updating status or triggering manual callbacks.\n\t*\n\t* @throws {Error} if subscription data cannot be found for all stored event names.\n\t* @throws {Error} if the client is disconnected.\n\t* @returns a promise resolving to true when the subscriptions are restored.\n\t*\n\t* @ignore\n\t*/\n\tasync resubscribeOnConnect() {\n\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].client(`Connected to '${this.hostIdentifier}'.`);\n\t\tthis.handleConnectionStatusChanges(\"connected\");\n\t\tconst resubscriptionPromises = [];\n\t\tfor (const method in this.subscriptionMethods) {\n\t\t\tfor (const parameterJSON of this.subscriptionMethods[method].values()) {\n\t\t\t\tconst parameters = JSON.parse(parameterJSON);\n\t\t\t\tresubscriptionPromises.push(this.subscribe(method, ...parameters));\n\t\t\t}\n\t\t\tawait Promise.all(resubscriptionPromises);\n\t\t}\n\t\tif (resubscriptionPromises.length > 0) _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].client(`Restored ${resubscriptionPromises.length} previous subscriptions for '${this.hostIdentifier}'`);\n\t}\n\t/**\n\t* Parser messages from the remote server to resolve request promises and emit subscription events.\n\t*\n\t* @param message - the response message\n\t*\n\t* @throws {Error} if the message ID does not match an existing request.\n\t* @ignore\n\t*/\n\tresponse(message) {\n\t\tif (isRPCNotification(message)) {\n\t\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].client(`Received notification for '${message.method}' from '${this.hostIdentifier}'`);\n\t\t\tthis.emit(\"notification\", message);\n\t\t\tthis.updateChainHeightFromHeadersNotifications(message);\n\t\t\treturn;\n\t\t}\n\t\tif (message.id === null) throw /* @__PURE__ */ new Error(\"Internal error: Received an RPC response with ID null.\");\n\t\tconst requestResolver = this.requestResolvers[message.id];\n\t\tif (!requestResolver) {\n\t\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"].warning(`Ignoring response #${message.id} as the request has already been rejected.`);\n\t\t\treturn;\n\t\t}\n\t\tdelete this.requestResolvers[message.id];\n\t\tif (isRPCErrorResponse(message)) requestResolver(new Error(message.error.message));\n\t\telse {\n\t\t\trequestResolver(void 0, message.result);\n\t\t\tthis.storeGenesisHashFromFeaturesResponse(message);\n\t\t}\n\t}\n\t/**\n\t* Callback function that is called when connection to the Electrum server is lost.\n\t* Aborts all active requests with an error message indicating that connection was lost.\n\t*\n\t* @ignore\n\t*/\n\tasync onConnectionDisconnect() {\n\t\tfor (const resolverId in this.requestResolvers) {\n\t\t\tconst requestResolver = this.requestResolvers[resolverId];\n\t\t\trequestResolver(/* @__PURE__ */ new Error(\"Connection lost\"));\n\t\t\tdelete this.requestResolvers[resolverId];\n\t\t}\n\t\tthis.handleConnectionStatusChanges(\"disconnected\");\n\t}\n\t/**\n\t* Stores the server provider software version field on successful version negotiation.\n\t*\n\t* @ignore\n\t*/\n\tasync storeSoftwareVersion(versionStatement) {\n\t\tif (versionStatement.error) return;\n\t\tthis.software = versionStatement.software;\n\t}\n\t/**\n\t* Updates the last received timestamp.\n\t*\n\t* @ignore\n\t*/\n\tasync updateLastReceivedTimestamp() {\n\t\tthis.lastReceivedTimestamp = Date.now();\n\t}\n\t/**\n\t* Checks if the provided message is a response to a headers subscription,\n\t* and if so updates the locally stored chain height value for this client.\n\t*\n\t* @ignore\n\t*/\n\tasync updateChainHeightFromHeadersNotifications(message) {\n\t\tif (message.method === \"blockchain.headers.subscribe\") this.chainHeight = message.params[0].height;\n\t}\n\t/**\n\t* Checks if the provided message is a response to a server.features request,\n\t* and if so stores the genesis hash for this client locally.\n\t*\n\t* @ignore\n\t*/\n\tasync storeGenesisHashFromFeaturesResponse(message) {\n\t\ttry {\n\t\t\tif (typeof message.result.genesis_hash !== \"undefined\") this.genesisHash = message.result.genesis_hash;\n\t\t} catch (_ignored) {}\n\t}\n\t/**\n\t* Helper function to synchronize state and events with the underlying connection.\n\t*/\n\tasync handleConnectionStatusChanges(eventName) {\n\t\tthis.emit(eventName);\n\t}\n\tconnecting;\n\tconnected;\n\tdisconnecting;\n\tdisconnected;\n\treconnecting;\n\tnotification;\n\terror;\n};\nvar electrum_client_default = ElectrumClient;\n\n//#endregion\n\n//# sourceMappingURL=index.mjs.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@electrum-cash/network/dist/index.mjs?");
1768
-
1769
- /***/ }),
1770
-
1771
- /***/ "../../node_modules/@electrum-cash/web-socket/dist/index.mjs":
1772
- /*!*******************************************************************!*\
1773
- !*** ../../node_modules/@electrum-cash/web-socket/dist/index.mjs ***!
1774
- \*******************************************************************/
1775
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1776
-
1777
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ElectrumWebSocket\": () => (/* binding */ ElectrumWebSocket)\n/* harmony export */ });\n/* harmony import */ var _monsterbitar_isomorphic_ws__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @monsterbitar/isomorphic-ws */ \"../../node_modules/@monsterbitar/isomorphic-ws/browser.mjs\");\n/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! eventemitter3 */ \"../../node_modules/eventemitter3/index.mjs\");\n/* harmony import */ var _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @electrum-cash/debug-logs */ \"../../node_modules/@electrum-cash/debug-logs/dist/index.mjs\");\n\n\n\n\n//#region source/constants.ts\nconst defaultTimeout = 30 * 1e3;\n\n//#endregion\n//#region source/web.ts\n/**\n* Web Socket used when communicating with Electrum servers.\n*/\nvar ElectrumWebSocket = class extends eventemitter3__WEBPACK_IMPORTED_MODULE_1__.EventEmitter {\n\twebSocket;\n\tdisconnectTimer;\n\tonConnectHasRun = false;\n\teventForwarders = {\n\t\tdisconnect: () => this.emit(\"disconnected\"),\n\t\twsData: (event) => this.emit(\"data\", `${event.data}\\n`),\n\t\twsError: (event) => this.emit(\"error\", new Error(event.error))\n\t};\n\tboundHandleVisibilityChange = this.handleVisibilityChange.bind(this);\n\tboundHandleConnectivityChange = this.handleConnectivityChange.bind(this);\n\t/**\n\t* Creates a socket configured with connection information for a given Electrum server.\n\t*\n\t* @param host Fully qualified domain name or IP address of the host\n\t* @param port Network port for the host to connect to, defaults to the standard TLS port\n\t* @param encrypted If false, uses an unencrypted connection instead of the default on TLS\n\t* @param timeout If no connection is established after `timeout` ms, the connection is terminated\n\t* @param reconnectionOptions Options to disable the automatic reconnection behavior when browser visibility or connectivity changes\n\t*/\n\tconstructor(host, port = 50004, encrypted = true, timeout = defaultTimeout, reconnectionOptions = {\n\t\tdisableBrowserVisibilityHandling: false,\n\t\tdisableBrowserConnectivityHandling: false\n\t}) {\n\t\tsuper();\n\t\tthis.host = host;\n\t\tthis.port = port;\n\t\tthis.encrypted = encrypted;\n\t\tthis.timeout = timeout;\n\t\tthis.reconnectionOptions = reconnectionOptions;\n\t}\n\t/**\n\t* Returns a string for the host identifier for usage in debug messages.\n\t*/\n\tget hostIdentifier() {\n\t\treturn `${this.host}:${this.port}`;\n\t}\n\t/**\n\t* Connect to host:port using the specified transport\n\t*/\n\tconnect() {\n\t\tif (this.webSocket) throw /* @__PURE__ */ new Error(\"Cannot initiate a new socket connection when an existing connection exists\");\n\t\tthis.disconnectTimer = setTimeout(() => this.disconnectOnTimeout(), this.timeout);\n\t\tthis.once(\"connected\", this.clearDisconnectTimerOnTimeout);\n\t\tconst connectionType = this.encrypted ? \"an encrypted WebSocket\" : \"a WebSocket\";\n\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_2__[\"default\"].network(`Initiating ${connectionType} connection to '${this.host}:${this.port}'.`);\n\t\tif (this.encrypted) this.webSocket = new _monsterbitar_isomorphic_ws__WEBPACK_IMPORTED_MODULE_0__.WebSocket(`wss://${this.host}:${this.port}`);\n\t\telse this.webSocket = new _monsterbitar_isomorphic_ws__WEBPACK_IMPORTED_MODULE_0__.WebSocket(`ws://${this.host}:${this.port}`);\n\t\tthis.webSocket.addEventListener(\"open\", this.onConnect.bind(this));\n\t\tthis.webSocket.addEventListener(\"error\", this.eventForwarders.wsError);\n\t}\n\t/**\n\t* Enables handler for browser consistent behavior with regards to connectivity and visibility events.\n\t*\n\t* Note that some browser disconnect sockets when a tab or window loses focus in order to save battery.\n\t* Note that some browser disconnect sockets when the browser loses connectivity.\n\t*\n\t* This feature allows for consistent behavior across browsers by default, but can be disabled if needed.\n\t*/\n\tconfigureBehaviorConsistency() {\n\t\tconst { disableBrowserVisibilityHandling, disableBrowserConnectivityHandling } = this.reconnectionOptions;\n\t\tif (!disableBrowserVisibilityHandling) this.enforceConsistentVisibilityBehavior();\n\t\tif (!disableBrowserConnectivityHandling) this.enforceConsistentConnectivityBehavior();\n\t}\n\t/**\n\t* Disables all automation regarding browser connectivity and visibility states.\n\t*/\n\tdisableBehaviorConsistency() {\n\t\tthis.disableConsistentVisibilityBehavior();\n\t\tthis.disableConsistentConnectivityBehavior();\n\t}\n\t/**\n\t* Adds event handlers for automatic connection and disconnect on browser visibility changes.\n\t*/\n\tenforceConsistentVisibilityBehavior() {\n\t\tif (typeof document !== \"undefined\") {\n\t\t\tdocument.removeEventListener(\"visibilitychange\", this.boundHandleVisibilityChange);\n\t\t\tdocument.addEventListener(\"visibilitychange\", this.boundHandleVisibilityChange);\n\t\t}\n\t}\n\t/**\n\t* Removes event handlers for browser visibility events.\n\t*/\n\tdisableConsistentVisibilityBehavior() {\n\t\tif (typeof document !== \"undefined\") document.removeEventListener(\"visibilitychange\", this.boundHandleVisibilityChange);\n\t}\n\t/**\n\t* Adds event handlers for automatic connection and disconnect on browser connectivity changes.\n\t*/\n\tenforceConsistentConnectivityBehavior() {\n\t\tif (typeof window !== \"undefined\") {\n\t\t\twindow.removeEventListener(\"online\", this.boundHandleConnectivityChange);\n\t\t\twindow.removeEventListener(\"offline\", this.boundHandleConnectivityChange);\n\t\t\twindow.addEventListener(\"online\", this.boundHandleConnectivityChange);\n\t\t\twindow.addEventListener(\"offline\", this.boundHandleConnectivityChange);\n\t\t}\n\t}\n\t/**\n\t* Removes event handlers for browser connectivity events.\n\t*/\n\tdisableConsistentConnectivityBehavior() {\n\t\tif (typeof window !== \"undefined\") {\n\t\t\twindow.removeEventListener(\"online\", this.boundHandleConnectivityChange);\n\t\t\twindow.removeEventListener(\"offline\", this.boundHandleConnectivityChange);\n\t\t}\n\t}\n\t/**\n\t* Sets up forwarding of events related to the connection.\n\t*/\n\tonConnect() {\n\t\tif (this.onConnectHasRun) return;\n\t\tconst connectionType = this.encrypted ? \"an encrypted WebSocket\" : \"a WebSocket\";\n\t\t_electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_2__[\"default\"].network(`Established ${connectionType} connection with '${this.host}:${this.port}'.`);\n\t\tthis.webSocket.addEventListener(\"close\", this.eventForwarders.disconnect);\n\t\tthis.webSocket.addEventListener(\"message\", this.eventForwarders.wsData);\n\t\tthis.configureBehaviorConsistency();\n\t\tthis.onConnectHasRun = true;\n\t\tthis.emit(\"connected\");\n\t}\n\t/**\n\t* Clears the disconnect timer if it is still active.\n\t*/\n\tclearDisconnectTimerOnTimeout() {\n\t\tif (this.disconnectTimer) clearTimeout(this.disconnectTimer);\n\t}\n\t/**\n\t* Forcibly terminate the connection.\n\t*\n\t* @throws {Error} if no connection was found\n\t*/\n\tdisconnect() {\n\t\tthis.disableBehaviorConsistency();\n\t\tthis.closeAndRemoveSocket();\n\t}\n\tcloseAndRemoveSocket() {\n\t\tthis.clearDisconnectTimerOnTimeout();\n\t\ttry {\n\t\t\tthis.webSocket.removeEventListener(\"close\", this.eventForwarders.disconnect);\n\t\t\tthis.webSocket.removeEventListener(\"message\", this.eventForwarders.wsData);\n\t\t\tthis.webSocket.removeEventListener(\"error\", this.eventForwarders.wsError);\n\t\t\tthis.webSocket.addEventListener(\"error\", (_ignored) => {}, { once: true });\n\t\t\tthis.webSocket.close();\n\t\t} catch (_ignored) {} finally {\n\t\t\tthis.webSocket = void 0;\n\t\t}\n\t\tthis.onConnectHasRun = false;\n\t\tthis.emit(\"disconnected\");\n\t}\n\t/**\n\t* Write data to the socket\n\t*\n\t* @param data Data to be written to the socket\n\t* @param callback Callback function to be called when the write has completed\n\t*\n\t* @throws {Error} if no connection was found\n\t* @returns true if the message was fully flushed to the socket, false if part of the message\n\t* is queued in the user memory\n\t*/\n\twrite(data, callback) {\n\t\tif (!this.webSocket) throw /* @__PURE__ */ new Error(\"Cannot write to socket when there is no active connection\");\n\t\tthis.webSocket.send(data, callback);\n\t\treturn true;\n\t}\n\t/**\n\t* Force a disconnection if no connection is established after `timeout` milliseconds.\n\t*/\n\tdisconnectOnTimeout() {\n\t\tthis.removeListener(\"connected\", this.clearDisconnectTimerOnTimeout);\n\t\tthis.emit(\"error\", /* @__PURE__ */ new Error(`Connection to '${this.host}:${this.port}' timed out after ${this.timeout} milliseconds`));\n\t\tthis.closeAndRemoveSocket();\n\t}\n\t/**\n\t* Handles visibility changes when run in a browser environment.\n\t*/\n\thandleVisibilityChange() {\n\t\tif (document?.visibilityState === \"hidden\") {\n\t\t\tthis.closeAndRemoveSocket();\n\t\t\treturn;\n\t\t}\n\t\tif (this.webSocket) return;\n\t\treturn this.connect();\n\t}\n\t/**\n\t* Handles connectivity changes when run in a browser environment.\n\t*/\n\thandleConnectivityChange() {\n\t\tif (window.navigator.onLine === false) {\n\t\t\tthis.closeAndRemoveSocket();\n\t\t\treturn;\n\t\t}\n\t\tif (this.webSocket) return;\n\t\treturn this.connect();\n\t}\n\tconnected;\n\tdisconnected;\n\tdata;\n\terror;\n};\n\n//#endregion\n\n//# sourceMappingURL=index.mjs.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@electrum-cash/web-socket/dist/index.mjs?");
1778
-
1779
- /***/ }),
1780
-
1781
- /***/ "../../node_modules/@monsterbitar/isomorphic-ws/browser.mjs":
1782
- /*!******************************************************************!*\
1783
- !*** ../../node_modules/@monsterbitar/isomorphic-ws/browser.mjs ***!
1784
- \******************************************************************/
1711
+ /***/ "../../node_modules/@rpckit/core/dist/batch.js":
1712
+ /*!*****************************************************!*\
1713
+ !*** ../../node_modules/@rpckit/core/dist/batch.js ***!
1714
+ \*****************************************************/
1785
1715
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1786
1716
 
1787
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"WebSocket\": () => (/* binding */ ws)\n/* harmony export */ });\n// https://github.com/maxogden/websocket-stream/blob/48dc3ddf943e5ada668c31ccd94e9186f02fafbd/ws-fallback.js\n\nvar ws = null\n\nif (typeof WebSocket !== 'undefined') {\n ws = WebSocket\n} else if (typeof MozWebSocket !== 'undefined') {\n ws = MozWebSocket\n} else if (typeof global !== 'undefined') {\n ws = global.WebSocket || global.MozWebSocket\n} else if (typeof window !== 'undefined') {\n ws = window.WebSocket || window.MozWebSocket\n} else if (typeof self !== 'undefined') {\n ws = self.WebSocket || self.MozWebSocket\n}\n\n\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@monsterbitar/isomorphic-ws/browser.mjs?");
1717
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BatchScheduler\": () => (/* binding */ BatchScheduler)\n/* harmony export */ });\nfunction defaultIsBatchRejection(error) {\n if (typeof error === 'object' && error !== null) {\n const e = error;\n if (typeof e.code === 'number') {\n // -32700: Parse error, -32600: Invalid Request\n if (e.code === -32700 || e.code === -32600)\n return true;\n }\n if (typeof e.message === 'string') {\n const msg = e.message.toLowerCase();\n if (msg.includes('parse error') ||\n msg.includes('invalid request') ||\n msg.includes('batch timeout'))\n return true;\n }\n }\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n if (msg.includes('parse error') ||\n msg.includes('invalid request') ||\n msg.includes('batch timeout'))\n return true;\n }\n return false;\n}\nclass BatchScheduler {\n queue = [];\n timer = null;\n config;\n raw;\n send;\n sendSingle;\n checkBatchRejection;\n _disabled = false;\n disableTimer = null;\n constructor(config, send) {\n this.config = {\n batchSize: config.batchSize ?? 10,\n wait: config.wait ?? 0,\n disabledCooldown: config.disabledCooldown ?? 5_000,\n };\n this.raw = config.raw ?? false;\n this.send = send;\n this.sendSingle = config.sendSingle;\n this.checkBatchRejection =\n config.isBatchRejection ?? defaultIsBatchRejection;\n }\n get disabled() {\n return this._disabled;\n }\n enqueue(request) {\n if (this._disabled && this.sendSingle) {\n return this.sendSingle(request);\n }\n return new Promise((resolve, reject) => {\n this.queue.push({ request, resolve, reject });\n if (this.queue.length >= this.config.batchSize) {\n this.flush();\n }\n else if (!this.timer) {\n this.timer = setTimeout(() => this.flush(), this.config.wait);\n }\n });\n }\n async flush() {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this.queue.length === 0)\n return;\n const batch = this.queue.splice(0);\n try {\n const responses = await this.send(batch.map((p) => p.request));\n const byId = new Map(responses.map((r) => [r.id, r]));\n for (const pending of batch) {\n const response = byId.get(pending.request.id);\n if (!response) {\n pending.reject(new Error(`No response for request id ${pending.request.id}, try reducing batch size`));\n }\n else if (response.error) {\n if (this.raw) {\n pending.resolve(response);\n }\n else {\n pending.reject(response.error);\n }\n }\n else {\n pending.resolve(this.raw ? response : response.result);\n }\n }\n }\n catch (error) {\n if (this.sendSingle && this.checkBatchRejection(error)) {\n this.disableBatching();\n // Retry failed batch items individually\n for (const pending of batch) {\n this.sendSingle(pending.request).then((result) => pending.resolve(result), (err) => pending.reject(err));\n }\n // Drain any remaining queued items individually\n const remaining = this.queue.splice(0);\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n for (const pending of remaining) {\n this.sendSingle(pending.request).then((result) => pending.resolve(result), (err) => pending.reject(err));\n }\n }\n else {\n for (const pending of batch) {\n pending.reject(error);\n }\n }\n }\n }\n disableBatching() {\n this._disabled = true;\n if (this.disableTimer)\n clearTimeout(this.disableTimer);\n if (this.config.disabledCooldown > 0) {\n this.disableTimer = setTimeout(() => {\n this._disabled = false;\n this.disableTimer = null;\n }, this.config.disabledCooldown);\n }\n }\n}\n//# sourceMappingURL=batch.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@rpckit/core/dist/batch.js?");
1788
1718
 
1789
1719
  /***/ }),
1790
1720
 
1791
- /***/ "../../node_modules/async-mutex/index.mjs":
1792
- /*!************************************************!*\
1793
- !*** ../../node_modules/async-mutex/index.mjs ***!
1794
- \************************************************/
1721
+ /***/ "../../node_modules/@rpckit/core/dist/parse.js":
1722
+ /*!*****************************************************!*\
1723
+ !*** ../../node_modules/@rpckit/core/dist/parse.js ***!
1724
+ \*****************************************************/
1795
1725
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1796
1726
 
1797
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"Mutex\": () => (/* binding */ Mutex)\n/* harmony export */ });\n/* unused harmony exports E_ALREADY_LOCKED, E_CANCELED, E_TIMEOUT, Semaphore, tryAcquire, withTimeout */\nconst E_TIMEOUT = new Error('timeout while waiting for mutex to become available');\nconst E_ALREADY_LOCKED = new Error('mutex already locked');\nconst E_CANCELED = new Error('request for lock canceled');\n\nvar __awaiter$2 = ( false) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Semaphore {\n constructor(_value, _cancelError = E_CANCELED) {\n this._value = _value;\n this._cancelError = _cancelError;\n this._queue = [];\n this._weightedWaiters = [];\n }\n acquire(weight = 1, priority = 0) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n return new Promise((resolve, reject) => {\n const task = { resolve, reject, weight, priority };\n const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);\n if (i === -1 && weight <= this._value) {\n // Needs immediate dispatch, skip the queue\n this._dispatchItem(task);\n }\n else {\n this._queue.splice(i + 1, 0, task);\n }\n });\n }\n runExclusive(callback_1) {\n return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) {\n const [value, release] = yield this.acquire(weight, priority);\n try {\n return yield callback(value);\n }\n finally {\n release();\n }\n });\n }\n waitForUnlock(weight = 1, priority = 0) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n if (this._couldLockImmediately(weight, priority)) {\n return Promise.resolve();\n }\n else {\n return new Promise((resolve) => {\n if (!this._weightedWaiters[weight - 1])\n this._weightedWaiters[weight - 1] = [];\n insertSorted(this._weightedWaiters[weight - 1], { resolve, priority });\n });\n }\n }\n isLocked() {\n return this._value <= 0;\n }\n getValue() {\n return this._value;\n }\n setValue(value) {\n this._value = value;\n this._dispatchQueue();\n }\n release(weight = 1) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n this._value += weight;\n this._dispatchQueue();\n }\n cancel() {\n this._queue.forEach((entry) => entry.reject(this._cancelError));\n this._queue = [];\n }\n _dispatchQueue() {\n this._drainUnlockWaiters();\n while (this._queue.length > 0 && this._queue[0].weight <= this._value) {\n this._dispatchItem(this._queue.shift());\n this._drainUnlockWaiters();\n }\n }\n _dispatchItem(item) {\n const previousValue = this._value;\n this._value -= item.weight;\n item.resolve([previousValue, this._newReleaser(item.weight)]);\n }\n _newReleaser(weight) {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n this.release(weight);\n };\n }\n _drainUnlockWaiters() {\n if (this._queue.length === 0) {\n for (let weight = this._value; weight > 0; weight--) {\n const waiters = this._weightedWaiters[weight - 1];\n if (!waiters)\n continue;\n waiters.forEach((waiter) => waiter.resolve());\n this._weightedWaiters[weight - 1] = [];\n }\n }\n else {\n const queuedPriority = this._queue[0].priority;\n for (let weight = this._value; weight > 0; weight--) {\n const waiters = this._weightedWaiters[weight - 1];\n if (!waiters)\n continue;\n const i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority);\n (i === -1 ? waiters : waiters.splice(0, i))\n .forEach((waiter => waiter.resolve()));\n }\n }\n }\n _couldLockImmediately(weight, priority) {\n return (this._queue.length === 0 || this._queue[0].priority < priority) &&\n weight <= this._value;\n }\n}\nfunction insertSorted(a, v) {\n const i = findIndexFromEnd(a, (other) => v.priority <= other.priority);\n a.splice(i + 1, 0, v);\n}\nfunction findIndexFromEnd(a, predicate) {\n for (let i = a.length - 1; i >= 0; i--) {\n if (predicate(a[i])) {\n return i;\n }\n }\n return -1;\n}\n\nvar __awaiter$1 = ( false) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Mutex {\n constructor(cancelError) {\n this._semaphore = new Semaphore(1, cancelError);\n }\n acquire() {\n return __awaiter$1(this, arguments, void 0, function* (priority = 0) {\n const [, releaser] = yield this._semaphore.acquire(1, priority);\n return releaser;\n });\n }\n runExclusive(callback, priority = 0) {\n return this._semaphore.runExclusive(() => callback(), 1, priority);\n }\n isLocked() {\n return this._semaphore.isLocked();\n }\n waitForUnlock(priority = 0) {\n return this._semaphore.waitForUnlock(1, priority);\n }\n release() {\n if (this._semaphore.isLocked())\n this._semaphore.release();\n }\n cancel() {\n return this._semaphore.cancel();\n }\n}\n\nvar __awaiter = ( false) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nfunction withTimeout(sync, timeout, timeoutError = E_TIMEOUT) {\n return {\n acquire: (weightOrPriority, priority) => {\n let weight;\n if (isSemaphore(sync)) {\n weight = weightOrPriority;\n }\n else {\n weight = undefined;\n priority = weightOrPriority;\n }\n if (weight !== undefined && weight <= 0) {\n throw new Error(`invalid weight ${weight}: must be positive`);\n }\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n let isTimeout = false;\n const handle = setTimeout(() => {\n isTimeout = true;\n reject(timeoutError);\n }, timeout);\n try {\n const ticket = yield (isSemaphore(sync)\n ? sync.acquire(weight, priority)\n : sync.acquire(priority));\n if (isTimeout) {\n const release = Array.isArray(ticket) ? ticket[1] : ticket;\n release();\n }\n else {\n clearTimeout(handle);\n resolve(ticket);\n }\n }\n catch (e) {\n if (!isTimeout) {\n clearTimeout(handle);\n reject(e);\n }\n }\n }));\n },\n runExclusive(callback, weight, priority) {\n return __awaiter(this, void 0, void 0, function* () {\n let release = () => undefined;\n try {\n const ticket = yield this.acquire(weight, priority);\n if (Array.isArray(ticket)) {\n release = ticket[1];\n return yield callback(ticket[0]);\n }\n else {\n release = ticket;\n return yield callback();\n }\n }\n finally {\n release();\n }\n });\n },\n release(weight) {\n sync.release(weight);\n },\n cancel() {\n return sync.cancel();\n },\n waitForUnlock: (weightOrPriority, priority) => {\n let weight;\n if (isSemaphore(sync)) {\n weight = weightOrPriority;\n }\n else {\n weight = undefined;\n priority = weightOrPriority;\n }\n if (weight !== undefined && weight <= 0) {\n throw new Error(`invalid weight ${weight}: must be positive`);\n }\n return new Promise((resolve, reject) => {\n const handle = setTimeout(() => reject(timeoutError), timeout);\n (isSemaphore(sync)\n ? sync.waitForUnlock(weight, priority)\n : sync.waitForUnlock(priority)).then(() => {\n clearTimeout(handle);\n resolve();\n });\n });\n },\n isLocked: () => sync.isLocked(),\n getValue: () => sync.getValue(),\n setValue: (value) => sync.setValue(value),\n };\n}\nfunction isSemaphore(sync) {\n return sync.getValue !== undefined;\n}\n\n// eslint-disable-next-lisne @typescript-eslint/explicit-module-boundary-types\nfunction tryAcquire(sync, alreadyAcquiredError = E_ALREADY_LOCKED) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return withTimeout(sync, 0, alreadyAcquiredError);\n}\n\n\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/async-mutex/index.mjs?");
1727
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"createParseSync\": () => (/* binding */ createParseSync)\n/* harmony export */ });\n/* unused harmony exports createParse, parse */\nfunction parseOptions(query) {\n const options = {};\n if (!query)\n return options;\n for (const pair of query.split('&')) {\n const [key, value] = pair.split('=');\n if (key && value !== undefined) {\n options[key] = decodeURIComponent(value);\n }\n }\n return options;\n}\nfunction inferType(scheme) {\n switch (scheme) {\n case 'ws':\n case 'wss':\n return 'websocket';\n case 'tcp':\n case 'tcp+tls':\n return 'tcp';\n case 'http':\n case 'https':\n return 'http';\n default:\n throw new Error(`Unknown scheme: ${scheme}`);\n }\n}\nfunction findMatchingParen(str, start) {\n let depth = 1;\n for (let i = start; i < str.length; i++) {\n if (str[i] === '(')\n depth++;\n else if (str[i] === ')') {\n depth--;\n if (depth === 0)\n return i;\n }\n }\n return -1;\n}\nfunction splitArgs(str) {\n const args = [];\n let current = '';\n let depth = 0;\n for (const char of str) {\n if (char === '(') {\n depth++;\n current += char;\n }\n else if (char === ')') {\n depth--;\n current += char;\n }\n else if (char === ',' && depth === 0) {\n args.push(current.trim());\n current = '';\n }\n else {\n current += char;\n }\n }\n if (current.trim()) {\n args.push(current.trim());\n }\n return args;\n}\nfunction parseTransport(input) {\n input = input.trim();\n // Check for meta-transports: fallback(...) or cluster(...)\n const metaMatch = input.match(/^(fallback|cluster)\\(/);\n if (metaMatch) {\n const type = metaMatch[1];\n const argsStart = metaMatch[0].length;\n const argsEnd = findMatchingParen(input, argsStart);\n if (argsEnd === -1) {\n throw new Error(`Unmatched parenthesis in: ${input}`);\n }\n const argsStr = input.slice(argsStart, argsEnd);\n const afterParen = input.slice(argsEnd + 1);\n // Parse options after closing paren: cluster(...)?timeout=1000\n let options = {};\n if (afterParen.startsWith('?')) {\n options = parseOptions(afterParen.slice(1));\n }\n const args = splitArgs(argsStr);\n if (type === 'cluster') {\n // First arg is quorum number\n const quorum = Number.parseInt(args[0], 10);\n if (Number.isNaN(quorum) || quorum < 1) {\n throw new Error(`Invalid quorum value: ${args[0]}`);\n }\n const children = args.slice(1).map(parseTransport);\n return { type, options, children, quorum };\n }\n const children = args.map(parseTransport);\n return { type, options, children };\n }\n // Simple transport URL: wss://host:port?timeout=1000\n const urlMatch = input.match(/^([a-z+]+):\\/\\/([^?]+)(?:\\?(.*))?$/);\n if (!urlMatch) {\n throw new Error(`Invalid transport URL: ${input}`);\n }\n const [, scheme, rest, query] = urlMatch;\n const type = inferType(scheme);\n const url = `${scheme}://${rest}`;\n const options = parseOptions(query || '');\n return { type, url, options };\n}\nconst KEY_ALIASES = { webSocket: 'websocket' };\nfunction normalizeKeys(map) {\n const result = {};\n for (const [key, value] of Object.entries(map)) {\n result[KEY_ALIASES[key] ?? key] = value;\n }\n return result;\n}\nconst DEFAULT_PACKAGE_MAP = {\n websocket: '@rpckit/websocket',\n tcp: '@rpckit/tcp',\n http: '@rpckit/http',\n fallback: '@rpckit/fallback',\n cluster: '@rpckit/cluster',\n};\nconst EXPORT_MAP = {\n websocket: 'webSocket',\n tcp: 'tcp',\n http: 'http',\n fallback: 'fallback',\n cluster: 'cluster',\n};\nasync function loadFactory(type, packageMap) {\n const pkg = packageMap[type];\n const exportName = EXPORT_MAP[type];\n try {\n const module = await __webpack_require__(\"../../node_modules/@rpckit/core/dist lazy recursive\")(pkg);\n return module[exportName];\n }\n catch {\n throw new Error(`Package ${pkg} is not installed. Run: npm install ${pkg}`);\n }\n}\nfunction buildOptions(options) {\n const result = {};\n for (const [key, value] of Object.entries(options)) {\n // Parse numeric values\n if (key === 'timeout' ||\n key === 'connectTimeout' ||\n key === 'keepAlive' ||\n key === 'quorum' ||\n key === 'retryCount' ||\n key === 'retryDelay') {\n result[key] = Number.parseInt(value, 10);\n }\n // Parse boolean values\n else if (key === 'rank' || key === 'eagerConnect') {\n result[key] = value === 'true';\n }\n // batch can be boolean or will be built from batchSize/batchWait\n else if (key === 'batch') {\n result[key] = value === 'true';\n }\n // Skip batchSize/batchWait/disabledCooldown - handled below\n else if (key === 'batchSize' || key === 'batchWait' || key === 'disabledCooldown') {\n // handled after loop\n }\n // Keep strings as-is\n else {\n result[key] = value;\n }\n }\n // Build batch config from batchSize/batchWait/disabledCooldown\n if (options.batchSize || options.batchWait || options.disabledCooldown) {\n const batchConfig = {};\n if (options.batchSize) {\n batchConfig.batchSize = Number.parseInt(options.batchSize, 10);\n }\n if (options.batchWait) {\n batchConfig.wait = Number.parseInt(options.batchWait, 10);\n }\n if (options.disabledCooldown) {\n batchConfig.disabledCooldown = Number.parseInt(options.disabledCooldown, 10);\n }\n result.batch = batchConfig;\n }\n return result;\n}\nfunction createBuildTransport(packageMap) {\n async function buildTransport(parsed) {\n const factory = await loadFactory(parsed.type, packageMap);\n const options = buildOptions(parsed.options);\n if (parsed.type === 'fallback' && parsed.children) {\n const transports = await Promise.all(parsed.children.map(buildTransport));\n return factory(transports, options);\n }\n if (parsed.type === 'cluster' && parsed.children) {\n const transports = await Promise.all(parsed.children.map(buildTransport));\n return factory(transports, { quorum: parsed.quorum, ...options });\n }\n // Simple transport\n if (!parsed.url) {\n throw new Error(`Missing URL for ${parsed.type} transport`);\n }\n return factory(parsed.url, options);\n }\n return buildTransport;\n}\n/**\n * Create a `parse` function that uses a custom package map for dynamic imports.\n *\n * Override specific transport types while keeping defaults for the rest.\n * Useful for creating protocol-specific parse variants (e.g. electrum-cash).\n */\nfunction createParse(overrides) {\n const packageMap = { ...DEFAULT_PACKAGE_MAP, ...normalizeKeys(overrides) };\n const buildTransport = createBuildTransport(packageMap);\n return async (input) => {\n const parsed = parseTransport(input);\n const transport = await buildTransport(parsed);\n return transport;\n };\n}\n/**\n * Create a synchronous `parse` function using pre-imported factory functions.\n *\n * Unlike `createParse` which uses dynamic imports, this variant accepts\n * already-loaded factory functions, making it fully synchronous.\n *\n * @example\n * ```typescript\n * import { webSocket } from '@rpckit/websocket/electrum-cash'\n * import { fallback } from '@rpckit/fallback'\n * import { createParseSync } from '@rpckit/core'\n *\n * const parseSync = createParseSync({ webSocket, fallback })\n * const transport = parseSync('fallback(wss://a.com,wss://b.com)?eagerConnect=true')\n * ```\n */\nfunction createParseSync(factories) {\n const normalized = normalizeKeys(factories);\n function buildTransport(parsed) {\n const factory = normalized[parsed.type];\n if (!factory) {\n throw new Error(`No factory for transport type \"${parsed.type}\". Available: ${Object.keys(normalized).join(', ')}`);\n }\n const options = buildOptions(parsed.options);\n if (parsed.type === 'fallback' && parsed.children) {\n const transports = parsed.children.map(buildTransport);\n return factory(transports, options);\n }\n if (parsed.type === 'cluster' && parsed.children) {\n const transports = parsed.children.map(buildTransport);\n return factory(transports, { quorum: parsed.quorum, ...options });\n }\n if (!parsed.url) {\n throw new Error(`Missing URL for ${parsed.type} transport`);\n }\n return factory(parsed.url, options);\n }\n return (input) => {\n const parsed = parseTransport(input);\n const transport = buildTransport(parsed);\n return transport;\n };\n}\n/**\n * Parse a transport one-liner string into a Transport instance.\n *\n * @example\n * ```typescript\n * // Simple transports\n * const ws = await parse('wss://example.com')\n * const tcp = await parse('tcp+tls://host:50002?timeout=10000')\n *\n * // Meta-transports\n * const fb = await parse('fallback(wss://a.com,tcp://b.com)')\n * const cl = await parse('cluster(2,ws://1.com,ws://2.com,ws://3.com)')\n *\n * // Nested\n * const nested = await parse('fallback(wss://a.com,cluster(2,ws://1.com,ws://2.com))')\n *\n * // With options\n * const withOpts = await parse('wss://example.com?timeout=10000&keepAlive=30000')\n * const batched = await parse('wss://example.com?batchSize=10&batchWait=50')\n * const fbRanked = await parse('fallback(wss://a.com,tcp://b.com)?rank=true')\n * ```\n *\n * Supported schemes:\n * - `wss://`, `ws://` → @rpckit/websocket\n * - `tcp://`, `tcp+tls://` → @rpckit/tcp\n * - `http://`, `https://` → @rpckit/http\n * - `fallback(...)` → @rpckit/fallback\n * - `cluster(quorum,...)` → @rpckit/cluster\n *\n * Supported options (via query params):\n * - `timeout` - Request timeout in ms\n * - `keepAlive` - Keep-alive ping interval in ms\n * - `batch` - Enable batching (true/false)\n * - `batchSize` - Max requests per batch\n * - `batchWait` - Max wait time before flushing batch (ms)\n * - `disabledCooldown` - Cooldown in ms before re-enabling batching after server rejection (default: 5000)\n * - `rank` - Enable health ranking for fallback (true/false)\n * - `eagerConnect` - Connect all fallback transports in parallel (true/false)\n * - `clientName` - Client name for electrum-cash handshake (default: 'rpckit')\n * - `protocolVersion` - Protocol version for electrum-cash handshake (default: '1.6')\n *\n * Packages are loaded dynamically at runtime. Missing packages throw an error.\n */\nasync function parse(input) {\n const buildTransport = createBuildTransport(DEFAULT_PACKAGE_MAP);\n const parsed = parseTransport(input);\n const transport = await buildTransport(parsed);\n return transport;\n}\n//# sourceMappingURL=parse.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@rpckit/core/dist/parse.js?");
1798
1728
 
1799
1729
  /***/ }),
1800
1730
 
1801
- /***/ "../../node_modules/eventemitter3/index.mjs":
1802
- /*!**************************************************!*\
1803
- !*** ../../node_modules/eventemitter3/index.mjs ***!
1804
- \**************************************************/
1731
+ /***/ "../../node_modules/@rpckit/core/dist/retry.js":
1732
+ /*!*****************************************************!*\
1733
+ !*** ../../node_modules/@rpckit/core/dist/retry.js ***!
1734
+ \*****************************************************/
1805
1735
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1806
1736
 
1807
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"EventEmitter\": () => (/* reexport default export from named module */ _index_js__WEBPACK_IMPORTED_MODULE_0__)\n/* harmony export */ });\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./index.js */ \"../../node_modules/eventemitter3/index.js\");\n\n\n\n/* unused harmony default export */ var __WEBPACK_DEFAULT_EXPORT__ = (_index_js__WEBPACK_IMPORTED_MODULE_0__);\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/eventemitter3/index.mjs?");
1737
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"withRetry\": () => (/* binding */ withRetry)\n/* harmony export */ });\nconst DEFAULT_RETRY_COUNT = 3;\nconst DEFAULT_RETRY_DELAY = 150;\n/**\n * Execute an async function with exponential backoff retry.\n */\nasync function withRetry(fn, options = {}) {\n const maxAttempts = (options.retryCount ?? DEFAULT_RETRY_COUNT) + 1;\n const baseDelay = options.retryDelay ?? DEFAULT_RETRY_DELAY;\n let lastError;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn();\n }\n catch (error) {\n lastError = error;\n if (attempt === maxAttempts) {\n break;\n }\n // Exponential backoff: delay * 2^(attempt-1)\n const delay = baseDelay * 2 ** (attempt - 1);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n throw lastError;\n}\n//# sourceMappingURL=retry.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@rpckit/core/dist/retry.js?");
1808
1738
 
1809
1739
  /***/ }),
1810
1740
 
1811
- /***/ "../../node_modules/lossless-json/lib/esm/LosslessNumber.js":
1812
- /*!******************************************************************!*\
1813
- !*** ../../node_modules/lossless-json/lib/esm/LosslessNumber.js ***!
1814
- \******************************************************************/
1815
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1816
-
1817
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"LosslessNumber\": () => (/* binding */ LosslessNumber),\n/* harmony export */ \"isLosslessNumber\": () => (/* binding */ isLosslessNumber)\n/* harmony export */ });\n/* unused harmony exports toLosslessNumber, compareLosslessNumber */\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"../../node_modules/lossless-json/lib/esm/utils.js\");\n\n\n/**\n * A lossless number. Stores its numeric value as string\n */\nclass LosslessNumber {\n // numeric value as string\n\n // type information\n isLosslessNumber = true;\n constructor(value) {\n if (!(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.isNumber)(value)) {\n throw new Error(`Invalid number (value: \"${value}\")`);\n }\n this.value = value;\n }\n\n /**\n * Get the value of the LosslessNumber as number or bigint.\n *\n * - a number is returned for safe numbers and decimal values that only lose some insignificant digits\n * - a bigint is returned for big integer numbers\n * - an Error is thrown for values that will overflow or underflow\n *\n * Note that you can implement your own strategy for conversion by just getting the value as string\n * via .toString(), and using util functions like isInteger, isSafeNumber, getUnsafeNumberReason,\n * and toSafeNumberOrThrow to convert it to a numeric value.\n */\n valueOf() {\n const unsafeReason = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.getUnsafeNumberReason)(this.value);\n\n // safe or truncate_float\n if (unsafeReason === undefined || unsafeReason === _utils_js__WEBPACK_IMPORTED_MODULE_0__.UnsafeNumberReason.truncate_float) {\n return Number.parseFloat(this.value);\n }\n\n // truncate_integer\n if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.isInteger)(this.value)) {\n return BigInt(this.value);\n }\n\n // overflow or underflow\n throw new Error(`Cannot safely convert to number: the value '${this.value}' would ${unsafeReason} and become ${Number.parseFloat(this.value)}`);\n }\n\n /**\n * Get the value of the LosslessNumber as string.\n */\n toString() {\n return this.value;\n }\n\n // Note: we do NOT implement a .toJSON() method, and you should not implement\n // or use that, it cannot safely turn the numeric value in the string into\n // stringified JSON since it has to be parsed into a number first.\n}\n\n/**\n * Test whether a value is a LosslessNumber\n */\nfunction isLosslessNumber(value) {\n // @ts-ignore\n return value && typeof value === 'object' && value.isLosslessNumber || false;\n}\n\n/**\n * Convert a number into a LosslessNumber if this is possible in a safe way\n * If the value has too many digits, or is NaN or Infinity, an error will be thrown\n */\nfunction toLosslessNumber(value) {\n const maxDigits = 15;\n if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.countSignificantDigits)(String(value)) > maxDigits) {\n throw new Error(`Invalid number: contains more than 15 digits and is most likely truncated and unsafe by itself (value: ${value})`);\n }\n if (Number.isNaN(value)) {\n throw new Error('Invalid number: NaN');\n }\n if (!Number.isFinite(value)) {\n throw new Error(`Invalid number: ${value}`);\n }\n return new LosslessNumber(String(value));\n}\n\n/**\n * Compare two lossless numbers.\n * Returns 1 when a is larger than b, 0 when they are equal,\n * and -1 when a is smaller than b.\n */\nfunction compareLosslessNumber(a, b) {\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.compareNumber)(a.value, b.value);\n}\n//# sourceMappingURL=LosslessNumber.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/lossless-json/lib/esm/LosslessNumber.js?");
1818
-
1819
- /***/ }),
1820
-
1821
- /***/ "../../node_modules/lossless-json/lib/esm/config.js":
1822
- /*!**********************************************************!*\
1823
- !*** ../../node_modules/lossless-json/lib/esm/config.js ***!
1824
- \**********************************************************/
1825
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1826
-
1827
- eval("/* unused harmony export config */\n/**\n * Get and/or set configuration options\n * @deprecated There is no config anymore\n */\nfunction config(_options) {\n // Backward compatibility warning for v1.x\n throw new Error('config is deprecated, support for circularRefs is removed from the library. ' + 'If you encounter circular references in your data structures, ' + 'please rethink your datastructures: ' + 'better prevent circular references in the first place.');\n}\n//# sourceMappingURL=config.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/lossless-json/lib/esm/config.js?");
1828
-
1829
- /***/ }),
1830
-
1831
- /***/ "../../node_modules/lossless-json/lib/esm/index.js":
1832
- /*!*********************************************************!*\
1833
- !*** ../../node_modules/lossless-json/lib/esm/index.js ***!
1834
- \*********************************************************/
1741
+ /***/ "../../node_modules/@rpckit/fallback/dist/electrum-cash/fallback.js":
1742
+ /*!**************************************************************************!*\
1743
+ !*** ../../node_modules/@rpckit/fallback/dist/electrum-cash/fallback.js ***!
1744
+ \**************************************************************************/
1835
1745
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1836
1746
 
1837
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"parse\": () => (/* reexport safe */ _parse_js__WEBPACK_IMPORTED_MODULE_1__.parse),\n/* harmony export */ \"parseNumberAndBigInt\": () => (/* reexport safe */ _numberParsers_js__WEBPACK_IMPORTED_MODULE_5__.parseNumberAndBigInt)\n/* harmony export */ });\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./config.js */ \"../../node_modules/lossless-json/lib/esm/config.js\");\n/* harmony import */ var _parse_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./parse.js */ \"../../node_modules/lossless-json/lib/esm/parse.js\");\n/* harmony import */ var _stringify_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./stringify.js */ \"../../node_modules/lossless-json/lib/esm/stringify.js\");\n/* harmony import */ var _LosslessNumber_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LosslessNumber.js */ \"../../node_modules/lossless-json/lib/esm/LosslessNumber.js\");\n/* harmony import */ var _reviveDate_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./reviveDate.js */ \"../../node_modules/lossless-json/lib/esm/reviveDate.js\");\n/* harmony import */ var _numberParsers_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./numberParsers.js */ \"../../node_modules/lossless-json/lib/esm/numberParsers.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils.js */ \"../../node_modules/lossless-json/lib/esm/utils.js\");\n/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types.js */ \"../../node_modules/lossless-json/lib/esm/types.js\");\n\n\n\n\n\n\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/lossless-json/lib/esm/index.js?");
1747
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"fallback\": () => (/* binding */ fallback)\n/* harmony export */ });\n/* unused harmony export shouldThrow */\n/* harmony import */ var _fallback_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../fallback.js */ \"../../node_modules/@rpckit/fallback/dist/fallback.js\");\n\n/** Transient server-specific errors worth retrying on another server. */\nconst TRANSIENT_CODES = new Set([\n -32603, // RPC_INTERNAL_ERROR — server corruption/bug\n -7, // RPC_OUT_OF_MEMORY\n -20, // RPC_DATABASE_ERROR\n -28, // RPC_IN_WARMUP server still starting\n -9, // RPC_CLIENT_NOT_CONNECTED — server's node disconnected\n -10, // RPC_CLIENT_IN_INITIAL_DOWNLOAD — server still syncing\n]);\n/** Default shouldThrow for Electrum Cash / BCHN: throws for all deterministic\n * RPC errors (invalid params, bad address, verify rejected, etc.) and falls\n * through on transient server-health issues (internal error, OOM, warmup). */\nfunction shouldThrow(error) {\n if ('code' in error &&\n typeof error.code === 'number') {\n return !TRANSIENT_CODES.has(error.code);\n }\n return false;\n}\n// Implementation\nfunction fallback(transports, options = {}) {\n // biome-ignore lint/suspicious/noExplicitAny: overload forwarding requires type erasure\n return (0,_fallback_js__WEBPACK_IMPORTED_MODULE_0__.fallback)(transports, resolveOptions(options));\n}\nfunction resolveOptions(options) {\n const resolved = { ...options };\n if (!resolved.shouldThrow) {\n resolved.shouldThrow = shouldThrow;\n }\n if (resolved.rank) {\n const rankOpts = typeof resolved.rank === 'object' ? { ...resolved.rank } : {};\n if (!rankOpts.ping) {\n rankOpts.ping = (t) => t.request('server.ping');\n }\n resolved.rank = rankOpts;\n }\n return resolved;\n}\n//# sourceMappingURL=fallback.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@rpckit/fallback/dist/electrum-cash/fallback.js?");
1838
1748
 
1839
1749
  /***/ }),
1840
1750
 
1841
- /***/ "../../node_modules/lossless-json/lib/esm/numberParsers.js":
1842
- /*!*****************************************************************!*\
1843
- !*** ../../node_modules/lossless-json/lib/esm/numberParsers.js ***!
1844
- \*****************************************************************/
1751
+ /***/ "../../node_modules/@rpckit/fallback/dist/fallback.js":
1752
+ /*!************************************************************!*\
1753
+ !*** ../../node_modules/@rpckit/fallback/dist/fallback.js ***!
1754
+ \************************************************************/
1845
1755
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1846
1756
 
1847
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"parseLosslessNumber\": () => (/* binding */ parseLosslessNumber),\n/* harmony export */ \"parseNumberAndBigInt\": () => (/* binding */ parseNumberAndBigInt)\n/* harmony export */ });\n/* harmony import */ var _LosslessNumber_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./LosslessNumber.js */ \"../../node_modules/lossless-json/lib/esm/LosslessNumber.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"../../node_modules/lossless-json/lib/esm/utils.js\");\n\n\nfunction parseLosslessNumber(value) {\n return new _LosslessNumber_js__WEBPACK_IMPORTED_MODULE_0__.LosslessNumber(value);\n}\nfunction parseNumberAndBigInt(value) {\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.isInteger)(value) ? BigInt(value) : Number.parseFloat(value);\n}\n//# sourceMappingURL=numberParsers.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/lossless-json/lib/esm/numberParsers.js?");
1757
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"fallback\": () => (/* binding */ fallback)\n/* harmony export */ });\n/* unused harmony export shouldThrow */\n// Implementation\nfunction fallback(transports, options = {}) {\n // Single transport: no need to wrap\n if (transports.length === 1) {\n return transports[0];\n }\n let ranked = [...transports];\n const { shouldThrow: shouldThrow_ = shouldThrow } = options;\n let rankingTimer = null;\n let rankingStopped = false;\n let currentScores = transports.map((t) => ({\n transport: t,\n score: 0,\n latency: 0,\n stability: 0,\n }));\n const scoreListeners = new Set();\n const responseListeners = new Set();\n if (options.rank) {\n const rankOpts = typeof options.rank === 'object' ? options.rank : {};\n startRanking(transports, rankOpts);\n }\n function startRanking(transports, opts) {\n if (!opts.ping)\n return;\n const ping = opts.ping;\n const interval = opts.interval ?? 4000;\n const sampleCount = opts.sampleCount ?? 10;\n const timeout = opts.timeout ?? 1000;\n const latencyWeight = opts.weights?.latency ?? 0.3;\n const stabilityWeight = opts.weights?.stability ?? 0.7;\n const samples = [];\n async function sample() {\n if (rankingStopped)\n return;\n const results = await Promise.all(transports.map(async (transport) => {\n const start = performance.now();\n try {\n await Promise.race([\n ping(transport),\n new Promise((_, reject) => setTimeout(() => reject(new Error('ping timeout')), timeout)),\n ]);\n return { latency: performance.now() - start, success: 1 };\n }\n catch {\n return { latency: timeout, success: 0 };\n }\n }));\n samples.push(results);\n if (samples.length > sampleCount)\n samples.shift();\n const maxLatency = Math.max(...samples.flatMap((s) => s.map((r) => r.latency)));\n const scores = transports.map((transport, i) => {\n const latencies = samples.map((s) => s[i].latency);\n const meanLatency = latencies.reduce((a, b) => a + b, 0) / latencies.length;\n const latencyScore = maxLatency > 0 ? 1 - meanLatency / maxLatency : 0;\n const successes = samples.map((s) => s[i].success);\n const stabilityScore = successes.reduce((a, b) => a + b, 0) / successes.length;\n const score = stabilityScore === 0\n ? 0\n : latencyWeight * latencyScore + stabilityWeight * stabilityScore;\n return {\n transport,\n score,\n latency: meanLatency,\n stability: stabilityScore,\n };\n });\n scores.sort((a, b) => b.score - a.score);\n ranked = scores.map((s) => s.transport);\n currentScores = scores;\n for (const listener of scoreListeners) {\n listener(scores);\n }\n if (!rankingStopped) {\n rankingTimer = setTimeout(sample, interval);\n }\n }\n sample();\n }\n return {\n url: transports.map((t) => t.url).join(','),\n async connect() {\n if (options.eagerConnect) {\n const connectResults = ranked.map((t, i) => t.connect().then(() => i));\n const fastestIndex = await Promise.any(connectResults);\n // Move the fastest-connecting transport to front priority\n if (fastestIndex > 0) {\n const [fastest] = ranked.splice(fastestIndex, 1);\n ranked.unshift(fastest);\n }\n // Let remaining connections settle in background\n Promise.allSettled(connectResults);\n }\n else {\n await Promise.all(ranked.map((t) => t.connect()));\n }\n },\n get transports() {\n return ranked;\n },\n get scores() {\n return currentScores;\n },\n onScores(listener) {\n scoreListeners.add(listener);\n return () => {\n scoreListeners.delete(listener);\n };\n },\n onResponse(listener) {\n responseListeners.add(listener);\n return () => {\n responseListeners.delete(listener);\n };\n },\n async request(method, ...params) {\n let lastError;\n for (const transport of ranked) {\n try {\n // biome-ignore lint/suspicious/noExplicitAny: meta-transport delegates with erased types\n const response = await transport.request(method, ...params);\n for (const listener of responseListeners) {\n listener({\n method,\n params,\n transport,\n response,\n status: 'success',\n });\n }\n return response;\n }\n catch (error) {\n lastError = error;\n for (const listener of responseListeners) {\n listener({\n method,\n params,\n transport,\n error,\n status: 'error',\n });\n }\n if (shouldThrow_(error))\n throw error;\n }\n }\n throw lastError;\n },\n async subscribe(method, ...args) {\n const onData = args.pop();\n const params = args;\n let lastError;\n for (const transport of ranked) {\n try {\n // biome-ignore lint/suspicious/noExplicitAny: meta-transport delegates with erased types\n const result = await transport.subscribe(method, ...params, onData);\n for (const listener of responseListeners) {\n listener({\n method,\n params,\n transport,\n response: result,\n status: 'success',\n });\n }\n return result;\n }\n catch (error) {\n lastError = error;\n for (const listener of responseListeners) {\n listener({\n method,\n params,\n transport,\n error,\n status: 'error',\n });\n }\n }\n }\n throw lastError;\n },\n async close() {\n rankingStopped = true;\n if (rankingTimer)\n clearTimeout(rankingTimer);\n scoreListeners.clear();\n responseListeners.clear();\n await Promise.all(transports.map((t) => t.close()));\n },\n };\n}\n/** Default shouldThrow: stops fallback for deterministic JSON-RPC errors. */\nfunction shouldThrow(error) {\n if ('code' in error &&\n typeof error.code === 'number') {\n const code = error.code;\n if (code === -32700 || // Parse error\n code === -32600 || // Invalid Request\n code === -32602 // Invalid params\n )\n return true;\n }\n return false;\n}\n//# sourceMappingURL=fallback.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@rpckit/fallback/dist/fallback.js?");
1848
1758
 
1849
1759
  /***/ }),
1850
1760
 
1851
- /***/ "../../node_modules/lossless-json/lib/esm/parse.js":
1852
- /*!*********************************************************!*\
1853
- !*** ../../node_modules/lossless-json/lib/esm/parse.js ***!
1854
- \*********************************************************/
1761
+ /***/ "../../node_modules/@rpckit/http/dist/http.js":
1762
+ /*!****************************************************!*\
1763
+ !*** ../../node_modules/@rpckit/http/dist/http.js ***!
1764
+ \****************************************************/
1855
1765
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1856
1766
 
1857
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"parse\": () => (/* binding */ parse)\n/* harmony export */ });\n/* unused harmony exports isValidStringCharacter, isDeepEqual, codeUppercaseA, codeLowercaseA, codeUppercaseE, codeLowercaseE, codeUppercaseF, codeLowercaseF */\n/* harmony import */ var _numberParsers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./numberParsers.js */ \"../../node_modules/lossless-json/lib/esm/numberParsers.js\");\n/* harmony import */ var _revive_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./revive.js */ \"../../node_modules/lossless-json/lib/esm/revive.js\");\n\n\n/**\n * The LosslessJSON.parse() method parses a string as JSON, optionally transforming\n * the value produced by parsing.\n *\n * The parser is based on the parser of Tan Li Hou shared in\n * https://lihautan.com/json-parser-with-javascript/\n *\n * @param text\n * The string to parse as JSON. See the JSON object for a description of JSON syntax.\n *\n * @param [reviver]\n * If a function, prescribes how the value originally produced by parsing is\n * transformed, before being returned.\n *\n * @param [parseNumber=parseLosslessNumber]\n * Pass a custom number parser. Input is a string, and the output can be unknown\n * numeric value: number, bigint, LosslessNumber, or a custom BigNumber library.\n *\n * @returns Returns the Object corresponding to the given JSON text.\n *\n * @throws Throws a SyntaxError exception if the string to parse is not valid JSON.\n */\nfunction parse(text, reviver) {\n let parseNumber = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _numberParsers_js__WEBPACK_IMPORTED_MODULE_0__.parseLosslessNumber;\n let i = 0;\n const value = parseValue();\n expectValue(value);\n expectEndOfInput();\n return reviver ? (0,_revive_js__WEBPACK_IMPORTED_MODULE_1__.revive)(value, reviver) : value;\n function parseObject() {\n if (text.charCodeAt(i) === codeOpeningBrace) {\n i++;\n skipWhitespace();\n const object = {};\n let initial = true;\n while (i < text.length && text.charCodeAt(i) !== codeClosingBrace) {\n if (!initial) {\n eatComma();\n skipWhitespace();\n } else {\n initial = false;\n }\n const start = i;\n const key = parseString();\n if (key === undefined) {\n throwObjectKeyExpected();\n return; // To make TS happy\n }\n skipWhitespace();\n eatColon();\n const value = parseValue();\n if (value === undefined) {\n throwObjectValueExpected();\n return; // To make TS happy\n }\n\n // TODO: test deep equal instead of strict equal\n if (Object.prototype.hasOwnProperty.call(object, key) && !isDeepEqual(value, object[key])) {\n // Note that we could also test `if(key in object) {...}`\n // or `if (object[key] !== 'undefined') {...}`, but that is slower.\n throwDuplicateKey(key, start + 1);\n }\n object[key] = value;\n }\n if (text.charCodeAt(i) !== codeClosingBrace) {\n throwObjectKeyOrEndExpected();\n }\n i++;\n return object;\n }\n }\n function parseArray() {\n if (text.charCodeAt(i) === codeOpeningBracket) {\n i++;\n skipWhitespace();\n const array = [];\n let initial = true;\n while (i < text.length && text.charCodeAt(i) !== codeClosingBracket) {\n if (!initial) {\n eatComma();\n } else {\n initial = false;\n }\n const value = parseValue();\n expectArrayItem(value);\n array.push(value);\n }\n if (text.charCodeAt(i) !== codeClosingBracket) {\n throwArrayItemOrEndExpected();\n }\n i++;\n return array;\n }\n }\n function parseValue() {\n skipWhitespace();\n const value = parseString() ?? parseNumeric() ?? parseObject() ?? parseArray() ?? parseKeyword('true', true) ?? parseKeyword('false', false) ?? parseKeyword('null', null);\n skipWhitespace();\n return value;\n }\n function parseKeyword(name, value) {\n if (text.slice(i, i + name.length) === name) {\n i += name.length;\n return value;\n }\n }\n function skipWhitespace() {\n while (isWhitespace(text.charCodeAt(i))) {\n i++;\n }\n }\n function parseString() {\n if (text.charCodeAt(i) === codeDoubleQuote) {\n i++;\n let result = '';\n while (i < text.length && text.charCodeAt(i) !== codeDoubleQuote) {\n if (text.charCodeAt(i) === codeBackslash) {\n const char = text[i + 1];\n const escapeChar = escapeCharacters[char];\n if (escapeChar !== undefined) {\n result += escapeChar;\n i++;\n } else if (char === 'u') {\n if (isHex(text.charCodeAt(i + 2)) && isHex(text.charCodeAt(i + 3)) && isHex(text.charCodeAt(i + 4)) && isHex(text.charCodeAt(i + 5))) {\n result += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));\n i += 5;\n } else {\n throwInvalidUnicodeCharacter(i);\n }\n } else {\n throwInvalidEscapeCharacter(i);\n }\n } else {\n if (isValidStringCharacter(text.charCodeAt(i))) {\n result += text[i];\n } else {\n throwInvalidCharacter(text[i]);\n }\n }\n i++;\n }\n expectEndOfString();\n i++;\n return result;\n }\n }\n function parseNumeric() {\n const start = i;\n if (text.charCodeAt(i) === codeMinus) {\n i++;\n expectDigit(start);\n }\n if (text.charCodeAt(i) === codeZero) {\n i++;\n } else if (isNonZeroDigit(text.charCodeAt(i))) {\n i++;\n while (isDigit(text.charCodeAt(i))) {\n i++;\n }\n }\n if (text.charCodeAt(i) === codeDot) {\n i++;\n expectDigit(start);\n while (isDigit(text.charCodeAt(i))) {\n i++;\n }\n }\n if (text.charCodeAt(i) === codeLowercaseE || text.charCodeAt(i) === codeUppercaseE) {\n i++;\n if (text.charCodeAt(i) === codeMinus || text.charCodeAt(i) === codePlus) {\n i++;\n }\n expectDigit(start);\n while (isDigit(text.charCodeAt(i))) {\n i++;\n }\n }\n if (i > start) {\n return parseNumber(text.slice(start, i));\n }\n }\n function eatComma() {\n if (text.charCodeAt(i) !== codeComma) {\n throw new SyntaxError(`Comma ',' expected after value ${gotAt()}`);\n }\n i++;\n }\n function eatColon() {\n if (text.charCodeAt(i) !== codeColon) {\n throw new SyntaxError(`Colon ':' expected after property name ${gotAt()}`);\n }\n i++;\n }\n function expectValue(value) {\n if (value === undefined) {\n throw new SyntaxError(`JSON value expected ${gotAt()}`);\n }\n }\n function expectArrayItem(value) {\n if (value === undefined) {\n throw new SyntaxError(`Array item expected ${gotAt()}`);\n }\n }\n function expectEndOfInput() {\n if (i < text.length) {\n throw new SyntaxError(`Expected end of input ${gotAt()}`);\n }\n }\n function expectDigit(start) {\n if (!isDigit(text.charCodeAt(i))) {\n const numSoFar = text.slice(start, i);\n throw new SyntaxError(`Invalid number '${numSoFar}', expecting a digit ${gotAt()}`);\n }\n }\n function expectEndOfString() {\n if (text.charCodeAt(i) !== codeDoubleQuote) {\n throw new SyntaxError(`End of string '\"' expected ${gotAt()}`);\n }\n }\n function throwObjectKeyExpected() {\n throw new SyntaxError(`Quoted object key expected ${gotAt()}`);\n }\n function throwDuplicateKey(key, pos) {\n throw new SyntaxError(`Duplicate key '${key}' encountered at position ${pos}`);\n }\n function throwObjectKeyOrEndExpected() {\n throw new SyntaxError(`Quoted object key or end of object '}' expected ${gotAt()}`);\n }\n function throwArrayItemOrEndExpected() {\n throw new SyntaxError(`Array item or end of array ']' expected ${gotAt()}`);\n }\n function throwInvalidCharacter(char) {\n throw new SyntaxError(`Invalid character '${char}' ${pos()}`);\n }\n function throwInvalidEscapeCharacter(start) {\n const chars = text.slice(start, start + 2);\n throw new SyntaxError(`Invalid escape character '${chars}' ${pos()}`);\n }\n function throwObjectValueExpected() {\n throw new SyntaxError(`Object value expected after ':' ${pos()}`);\n }\n function throwInvalidUnicodeCharacter(start) {\n const chars = text.slice(start, start + 6);\n throw new SyntaxError(`Invalid unicode character '${chars}' ${pos()}`);\n }\n\n // zero based character position\n function pos() {\n return `at position ${i}`;\n }\n function got() {\n return i < text.length ? `but got '${text[i]}'` : 'but reached end of input';\n }\n function gotAt() {\n return `${got()} ${pos()}`;\n }\n}\nfunction isWhitespace(code) {\n return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn;\n}\nfunction isHex(code) {\n return code >= codeZero && code <= codeNine || code >= codeUppercaseA && code <= codeUppercaseF || code >= codeLowercaseA && code <= codeLowercaseF;\n}\nfunction isDigit(code) {\n return code >= codeZero && code <= codeNine;\n}\nfunction isNonZeroDigit(code) {\n return code >= codeOne && code <= codeNine;\n}\nfunction isValidStringCharacter(code) {\n return code >= 0x20 && code <= 0x10ffff;\n}\nfunction isDeepEqual(a, b) {\n if (a === b) {\n return true;\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => isDeepEqual(item, b[index]));\n }\n if (isObject(a) && isObject(b)) {\n const keys = [...new Set([...Object.keys(a), ...Object.keys(b)])];\n return keys.every(key => isDeepEqual(a[key], b[key]));\n }\n return false;\n}\nfunction isObject(value) {\n return typeof value === 'object' && value !== null;\n}\n\n// map with all escape characters\nconst escapeCharacters = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n // note that \\u is handled separately in parseString()\n};\nconst codeBackslash = 0x5c; // \"\\\"\nconst codeOpeningBrace = 0x7b; // \"{\"\nconst codeClosingBrace = 0x7d; // \"}\"\nconst codeOpeningBracket = 0x5b; // \"[\"\nconst codeClosingBracket = 0x5d; // \"]\"\nconst codeSpace = 0x20; // \" \"\nconst codeNewline = 0xa; // \"\\n\"\nconst codeTab = 0x9; // \"\\t\"\nconst codeReturn = 0xd; // \"\\r\"\nconst codeDoubleQuote = 0x0022; // \"\nconst codePlus = 0x2b; // \"+\"\nconst codeMinus = 0x2d; // \"-\"\nconst codeZero = 0x30;\nconst codeOne = 0x31;\nconst codeNine = 0x39;\nconst codeComma = 0x2c; // \",\"\nconst codeDot = 0x2e; // \".\" (dot, period)\nconst codeColon = 0x3a; // \":\"\nconst codeUppercaseA = 0x41; // \"A\"\nconst codeLowercaseA = 0x61; // \"a\"\nconst codeUppercaseE = 0x45; // \"E\"\nconst codeLowercaseE = 0x65; // \"e\"\nconst codeUppercaseF = 0x46; // \"F\"\nconst codeLowercaseF = 0x66; // \"f\"\n//# sourceMappingURL=parse.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/lossless-json/lib/esm/parse.js?");
1767
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"http\": () => (/* binding */ http)\n/* harmony export */ });\n/* harmony import */ var _rpckit_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @rpckit/core */ \"../../node_modules/@rpckit/core/dist/batch.js\");\n/* harmony import */ var _rpckit_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @rpckit/core */ \"../../node_modules/@rpckit/core/dist/retry.js\");\n\nfunction http(configOrUrl, options) {\n const config = typeof configOrUrl === 'string'\n ? { ...options, url: configOrUrl }\n : configOrUrl;\n let nextId = 1;\n const batchScheduler = new _rpckit_core__WEBPACK_IMPORTED_MODULE_0__.BatchScheduler({\n ...(typeof config.batch === 'object' ? config.batch : {}),\n raw: config.raw,\n }, sendBatch);\n const fetchFn = config.fetchFn ?? fetch;\n async function sendBatch(requests) {\n const body = requests.length === 1 ? requests[0] : requests;\n return (0,_rpckit_core__WEBPACK_IMPORTED_MODULE_1__.withRetry)(async () => {\n config.onRequest?.({ url: config.url, body });\n const res = await fetchFn(config.url, {\n ...config.fetchOptions,\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...config.headers },\n body: JSON.stringify(body),\n signal: config.timeout\n ? AbortSignal.timeout(config.timeout)\n : undefined,\n });\n if (!res.ok) {\n // Try to get error details from response body\n let errorBody = '';\n try {\n errorBody = await res.text();\n }\n catch {\n // Ignore if we can't read the body\n }\n throw new Error(`HTTP ${res.status}: ${res.statusText}${errorBody ? ` - ${errorBody}` : ''}`);\n }\n const json = await res.json();\n const responses = Array.isArray(json) ? json : [json];\n config.onResponse?.({ status: res.status, body: json });\n return responses;\n }, { retryCount: config.retryCount, retryDelay: config.retryDelay });\n }\n return {\n url: config.url,\n async connect() { },\n async request(method, ...params) {\n const id = nextId++;\n const request = { jsonrpc: '2.0', method, params, id };\n return batchScheduler.enqueue(request);\n },\n async subscribe() {\n throw new Error('HTTP transport does not support subscriptions');\n },\n async close() {\n await batchScheduler.flush();\n },\n };\n}\n//# sourceMappingURL=http.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@rpckit/http/dist/http.js?");
1858
1768
 
1859
1769
  /***/ }),
1860
1770
 
1861
- /***/ "../../node_modules/lossless-json/lib/esm/revive.js":
1862
- /*!**********************************************************!*\
1863
- !*** ../../node_modules/lossless-json/lib/esm/revive.js ***!
1864
- \**********************************************************/
1771
+ /***/ "../../node_modules/@rpckit/websocket/dist/electrum-cash/webSocket.js":
1772
+ /*!****************************************************************************!*\
1773
+ !*** ../../node_modules/@rpckit/websocket/dist/electrum-cash/webSocket.js ***!
1774
+ \****************************************************************************/
1865
1775
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1866
1776
 
1867
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"revive\": () => (/* binding */ revive)\n/* harmony export */ });\n/* harmony import */ var _LosslessNumber_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./LosslessNumber.js */ \"../../node_modules/lossless-json/lib/esm/LosslessNumber.js\");\n\n/**\n * Revive a json object.\n * Applies the reviver function recursively on all values in the JSON object.\n * @param json A JSON Object, Array, or value\n * @param reviver\n * A reviver function invoked with arguments `key` and `value`,\n * which must return a replacement value. The function context\n * (`this`) is the Object or Array that contains the currently\n * handled value.\n */\nfunction revive(json, reviver) {\n return reviveValue({\n '': json\n }, '', json, reviver);\n}\n\n/**\n * Revive a value\n */\nfunction reviveValue(context, key, value, reviver) {\n if (Array.isArray(value)) {\n return reviver.call(context, key, reviveArray(value, reviver));\n }\n if (value && typeof value === 'object' && !(0,_LosslessNumber_js__WEBPACK_IMPORTED_MODULE_0__.isLosslessNumber)(value)) {\n // note the special case for LosslessNumber,\n // we don't want to iterate over the internals of a LosslessNumber\n return reviver.call(context, key, reviveObject(value, reviver));\n }\n return reviver.call(context, key, value);\n}\n\n/**\n * Revive the properties of an object\n */\nfunction reviveObject(object, reviver) {\n for (const key of Object.keys(object)) {\n const value = reviveValue(object, key, object[key], reviver);\n if (value !== undefined) {\n object[key] = value;\n } else {\n delete object[key];\n }\n }\n return object;\n}\n\n/**\n * Revive the properties of an Array\n */\nfunction reviveArray(array, reviver) {\n for (let i = 0; i < array.length; i++) {\n array[i] = reviveValue(array, String(i), array[i], reviver);\n }\n return array;\n}\n//# sourceMappingURL=revive.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/lossless-json/lib/esm/revive.js?");
1777
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"webSocket\": () => (/* binding */ webSocket)\n/* harmony export */ });\n/* harmony import */ var _webSocket_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../webSocket.js */ \"../../node_modules/@rpckit/websocket/dist/webSocket.js\");\n\nfunction webSocket(configOrUrl, options) {\n const base = typeof configOrUrl === 'string'\n ? { ...options, url: configOrUrl }\n : configOrUrl;\n const { clientName = 'rpckit', protocolVersion = '1.6', ...rest } = base;\n const keepAlive = normalizeKeepAlive(rest.keepAlive);\n return (0,_webSocket_js__WEBPACK_IMPORTED_MODULE_0__.webSocket)({\n handshake: {\n method: 'server.version',\n params: [clientName, protocolVersion],\n },\n onUnsubscribe: ({ request, method, params }) => request(method.replace('subscribe', 'unsubscribe'), ...params),\n transformInitialResult: (_method, params, result) => [...params, ...result],\n notificationFilter: electrumParamsMatch,\n ...rest,\n ...(keepAlive !== undefined ? { keepAlive } : {}),\n });\n}\nfunction normalizeKeepAlive(ka) {\n if (ka === undefined)\n return undefined;\n if (typeof ka === 'number') {\n return { interval: ka, method: 'server.ping' };\n }\n const ping = { ...ka };\n if (!ping.method)\n ping.method = 'server.ping';\n return ping;\n}\n/**\n * Electrum protocol notification filter.\n * Notifications include subscription params as prefix: subscribe([address]) → notification([address, status])\n */\nfunction electrumParamsMatch(subscriptionParams, notificationParams) {\n return subscriptionParams.every((p, i) => {\n if (i >= notificationParams.length)\n return false;\n const np = notificationParams[i];\n // Simple types can be compared directly\n if (typeof p !== 'object' ||\n p === null ||\n typeof np !== 'object' ||\n np === null) {\n return p === np;\n }\n // Complex types need JSON comparison\n return JSON.stringify(p) === JSON.stringify(np);\n });\n}\n//# sourceMappingURL=webSocket.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@rpckit/websocket/dist/electrum-cash/webSocket.js?");
1868
1778
 
1869
1779
  /***/ }),
1870
1780
 
1871
- /***/ "../../node_modules/lossless-json/lib/esm/reviveDate.js":
1781
+ /***/ "../../node_modules/@rpckit/websocket/dist/webSocket.js":
1872
1782
  /*!**************************************************************!*\
1873
- !*** ../../node_modules/lossless-json/lib/esm/reviveDate.js ***!
1783
+ !*** ../../node_modules/@rpckit/websocket/dist/webSocket.js ***!
1874
1784
  \**************************************************************/
1875
1785
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1876
1786
 
1877
- eval("/* unused harmony export reviveDate */\n/**\n * Revive a string containing an ISO 8601 date string into a JavaScript `Date` object\n */\nfunction reviveDate(key, value) {\n return typeof value === 'string' && isoDateRegex.test(value) ? new Date(value) : value;\n}\n\n// Matches strings like \"2022-08-25T09:39:19.288Z\"\nconst isoDateRegex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/;\n//# sourceMappingURL=reviveDate.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/lossless-json/lib/esm/reviveDate.js?");
1787
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"webSocket\": () => (/* binding */ webSocket)\n/* harmony export */ });\n/* harmony import */ var _rpckit_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @rpckit/core */ \"../../node_modules/@rpckit/core/dist/batch.js\");\n/* harmony import */ var _rpckit_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @rpckit/core */ \"../../node_modules/@rpckit/core/dist/retry.js\");\n/* harmony import */ var isows__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! isows */ \"../../node_modules/isows/_esm/native.js\");\n\n\nconst socketCache = new Map();\nfunction getCacheKey(config) {\n return JSON.stringify({\n url: config.url,\n headers: config.headers,\n keepAlive: config.keepAlive,\n reconnect: config.reconnect,\n });\n}\nfunction getOrCreateSocketClient(config) {\n const cacheKey = getCacheKey(config);\n let client = socketCache.get(cacheKey);\n if (client) {\n client.refCount++;\n return client;\n }\n let ws = null;\n let nextId = 1;\n let closed = false;\n let connectPromise = null;\n let reconnectCount = 0;\n const pending = new Map();\n const subscriptions = new Map();\n // Track pending subscribe requests to prevent race conditions\n const pendingSubscriptions = new Map();\n let keepAliveTimer = null;\n let batchScheduler = null;\n async function sendSingle(req) {\n await connect();\n return new Promise((resolve, reject) => {\n const timer = config.timeout\n ? setTimeout(() => {\n pending.delete(req.id);\n reject(new Error('Request timeout'));\n }, config.timeout)\n : undefined;\n pending.set(req.id, { resolve, reject, timer });\n sendRaw(req);\n });\n }\n if (config.batch !== false) {\n batchScheduler = new _rpckit_core__WEBPACK_IMPORTED_MODULE_0__.BatchScheduler({\n ...(typeof config.batch === 'object' ? config.batch : {}),\n sendSingle,\n }, sendBatch);\n }\n function getSubscriptionKey(method, params) {\n return `${method}:${JSON.stringify(params)}`;\n }\n function connect() {\n if (connectPromise)\n return connectPromise;\n connectPromise = new Promise((resolve, reject) => {\n ws = config.headers\n ? // biome-ignore lint/suspicious/noExplicitAny: isows headers typing\n new isows__WEBPACK_IMPORTED_MODULE_1__.WebSocket(config.url, { headers: config.headers })\n : new isows__WEBPACK_IMPORTED_MODULE_1__.WebSocket(config.url);\n let connectTimer;\n if (config.connectTimeout) {\n connectTimer = setTimeout(() => {\n reject(new Error('Connection timeout'));\n ws?.close();\n void handleDisconnect();\n }, config.connectTimeout);\n }\n ws.onopen = async () => {\n try {\n reconnectCount = 0;\n if (config.handshake) {\n const id = nextId++;\n const req = {\n jsonrpc: '2.0',\n method: config.handshake.method,\n params: config.handshake.params ?? [],\n id,\n };\n await new Promise((res, rej) => {\n pending.set(id, { resolve: () => res(), reject: rej });\n sendRaw(req);\n });\n }\n startKeepAlive();\n // Restore subscriptions after reconnect\n if (subscriptions.size > 0) {\n for (const [_key, entry] of subscriptions) {\n const id = nextId++;\n const req = {\n jsonrpc: '2.0',\n method: entry.method,\n params: entry.params,\n id,\n };\n sendRaw(req);\n // We don't await the response - just re-establish\n }\n }\n if (connectTimer)\n clearTimeout(connectTimer);\n resolve();\n }\n catch (err) {\n reject(err);\n }\n };\n ws.onerror = (event) => {\n if (connectTimer)\n clearTimeout(connectTimer);\n const message = event && typeof event === 'object' && 'message' in event\n ? `WebSocket error: ${event.message}`\n : 'WebSocket error';\n reject(new Error(message));\n void handleDisconnect();\n };\n ws.onclose = () => {\n void handleDisconnect();\n };\n ws.onmessage = (event) => {\n const raw = String(event.data);\n if (!raw.trim())\n return;\n const messages = raw.startsWith('[') ? JSON.parse(raw) : [JSON.parse(raw)];\n for (const msg of messages) {\n if ('id' in msg && msg.id != null) {\n const p = pending.get(msg.id);\n if (p) {\n pending.delete(msg.id);\n if (p.timer)\n clearTimeout(p.timer);\n const resp = msg;\n if (resp.error)\n p.reject(resp.error);\n else\n p.resolve(resp.result);\n }\n }\n else {\n // Subscription notification\n const notif = msg;\n for (const [, entry] of subscriptions) {\n if (entry.method === notif.method) {\n // Apply notification filter if configured\n if (config.notificationFilter) {\n const notifParams = notif.params;\n if (!config.notificationFilter(entry.params, notifParams)) {\n continue;\n }\n }\n entry.lastNotification = notif.params;\n entry.dispatchChain = entry.dispatchChain.then(() => Promise.all(Array.from(entry.listeners, (handler) => Promise.resolve(handler(notif.params)).catch(() => { }))).then(() => { }));\n }\n }\n }\n }\n };\n });\n return connectPromise;\n }\n function startKeepAlive() {\n stopKeepAlive();\n const ka = config.keepAlive;\n if (!ka)\n return;\n const interval = typeof ka === 'number' ? ka : ka.interval;\n const method = typeof ka === 'number' ? undefined : ka.method;\n const params = typeof ka === 'number' ? [] : (ka.params ?? []);\n if (interval > 0 && method) {\n keepAliveTimer = setInterval(() => {\n sendRaw({ jsonrpc: '2.0', method, params, id: nextId++ });\n }, interval);\n }\n }\n function stopKeepAlive() {\n if (keepAliveTimer) {\n clearInterval(keepAliveTimer);\n keepAliveTimer = null;\n }\n }\n async function handleDisconnect() {\n stopKeepAlive();\n connectPromise = null;\n ws = null;\n // Reject all pending requests (but keep subscriptions for restore)\n for (const [, p] of pending) {\n if (p.timer)\n clearTimeout(p.timer);\n p.reject(new Error('WebSocket disconnected'));\n }\n pending.clear();\n if (!closed &&\n config.reconnect &&\n reconnectCount < config.reconnect.attempts) {\n reconnectCount++;\n await new Promise((r) => setTimeout(r, config.reconnect?.delay));\n if (!closed)\n await connect();\n }\n }\n function sendRaw(request) {\n ws?.send(JSON.stringify(request));\n }\n async function sendBatch(requests) {\n await connect();\n return new Promise((resolve, reject) => {\n const ids = new Set(requests.map((r) => r.id));\n const results = [];\n const timer = config.timeout\n ? setTimeout(() => {\n for (const id of ids)\n pending.delete(id);\n reject(new Error('Batch timeout'));\n }, config.timeout)\n : undefined;\n for (const req of requests) {\n pending.set(req.id, {\n resolve: (result) => {\n results.push({ jsonrpc: '2.0', result, id: req.id });\n ids.delete(req.id);\n if (ids.size === 0) {\n if (timer)\n clearTimeout(timer);\n resolve(results);\n }\n },\n reject: (error) => {\n for (const id of ids)\n pending.delete(id);\n if (timer)\n clearTimeout(timer);\n reject(error);\n },\n });\n }\n ws?.send(JSON.stringify(requests));\n });\n }\n async function request(method, params = []) {\n await connect();\n const id = nextId++;\n const req = { jsonrpc: '2.0', method, params, id };\n if (batchScheduler) {\n return batchScheduler.enqueue(req);\n }\n return sendSingle(req);\n }\n async function subscribe(method, params, onData) {\n await connect();\n const subKey = getSubscriptionKey(method, params);\n // Helper to create unsubscribe function for an entry\n const createUnsubscribe = (e) => async () => {\n e.listeners.delete(onData);\n if (e.listeners.size === 0) {\n subscriptions.delete(subKey);\n await e.dispatchChain;\n return true; // was the last listener\n }\n return false; // other listeners remain\n };\n // Check for existing subscription\n let entry = subscriptions.get(subKey);\n if (entry) {\n entry.listeners.add(onData);\n const hasNotification = entry.lastNotification !== undefined;\n return {\n initialResult: hasNotification\n ? entry.lastNotification\n : entry.initialResult,\n unsubscribe: createUnsubscribe(entry),\n fromNotification: hasNotification,\n };\n }\n // Check for pending subscription request (race condition prevention)\n const pendingPromise = pendingSubscriptions.get(subKey);\n if (pendingPromise) {\n // Wait for the in-flight subscription to complete, then tap in\n entry = await pendingPromise;\n entry.listeners.add(onData);\n const hasNotification = entry.lastNotification !== undefined;\n return {\n initialResult: hasNotification\n ? entry.lastNotification\n : entry.initialResult,\n unsubscribe: createUnsubscribe(entry),\n fromNotification: hasNotification,\n };\n }\n // Create new subscription - store promise to prevent race conditions\n const subscriptionPromise = (async () => {\n const id = nextId++;\n const req = { jsonrpc: '2.0', method, params, id };\n const initialResult = await new Promise((resolve, reject) => {\n const timer = config.timeout\n ? setTimeout(() => {\n pending.delete(id);\n reject(new Error('Request timeout'));\n }, config.timeout)\n : undefined;\n pending.set(id, { resolve, reject, timer });\n sendRaw(req);\n });\n const newEntry = {\n method,\n params,\n listeners: new Set([onData]),\n initialResult,\n lastNotification: undefined,\n dispatchChain: Promise.resolve(),\n };\n subscriptions.set(subKey, newEntry);\n return newEntry;\n })();\n pendingSubscriptions.set(subKey, subscriptionPromise);\n try {\n entry = await subscriptionPromise;\n return {\n initialResult: entry.initialResult,\n unsubscribe: createUnsubscribe(entry),\n fromNotification: false,\n };\n }\n finally {\n pendingSubscriptions.delete(subKey);\n }\n }\n async function close() {\n closed = true;\n stopKeepAlive();\n if (batchScheduler)\n await batchScheduler.flush();\n // Drain all in-flight dispatch chains before tearing down\n await Promise.all(Array.from(subscriptions.values(), (e) => e.dispatchChain));\n for (const [, p] of pending) {\n if (p.timer)\n clearTimeout(p.timer);\n p.reject(new Error('Transport closed'));\n }\n pending.clear();\n subscriptions.clear();\n ws?.close();\n ws = null;\n connectPromise = null;\n socketCache.delete(cacheKey);\n }\n client = {\n refCount: 1,\n get ws() {\n return ws;\n },\n nextId,\n connectPromise,\n reconnectCount,\n closed,\n pending,\n subscriptions,\n keepAliveTimer,\n batchScheduler,\n connect,\n sendRaw,\n request,\n subscribe,\n close,\n };\n socketCache.set(cacheKey, client);\n return client;\n}\nfunction webSocket(configOrUrl, options) {\n const config = typeof configOrUrl === 'string'\n ? { ...options, url: configOrUrl }\n : configOrUrl;\n // Lazy client initialization - only created on first use\n let client = null;\n const getClient = () => {\n if (!client)\n client = getOrCreateSocketClient(config);\n return client;\n };\n const retryOpts = {\n retryCount: config.retryCount,\n retryDelay: config.retryDelay,\n };\n const self = {\n url: config.url,\n connect: () => (0,_rpckit_core__WEBPACK_IMPORTED_MODULE_2__.withRetry)(() => getClient().connect(), retryOpts),\n request: (method, ...params) => (0,_rpckit_core__WEBPACK_IMPORTED_MODULE_2__.withRetry)(() => getClient().request(method, params), retryOpts),\n async subscribe(method, ...args) {\n const onData = args.pop();\n const params = args;\n const { initialResult, unsubscribe, fromNotification } = await (0,_rpckit_core__WEBPACK_IMPORTED_MODULE_2__.withRetry)(() => getClient().subscribe(method, params, onData), retryOpts);\n // Deliver initial result if we got one\n if (initialResult !== undefined) {\n if (fromNotification) {\n // Reused subscription: lastNotification is already in notification format\n onData(initialResult);\n }\n else {\n const transformed = config.transformInitialResult\n ? config.transformInitialResult(method, params, [initialResult])\n : initialResult;\n // Allow transformInitialResult to return undefined to suppress delivery\n if (transformed !== undefined) {\n onData(transformed);\n }\n }\n }\n const unsub = async (cleanup) => {\n const wasLastListener = await unsubscribe();\n // Only call onUnsubscribe when the last listener is removed\n if (wasLastListener) {\n const fn = cleanup ?? config.onUnsubscribe;\n if (fn) {\n await fn({ request: self.request, method, params, initialResult });\n }\n }\n };\n return unsub;\n },\n async close() {\n if (!client)\n return;\n client.refCount--;\n if (client.refCount <= 0) {\n await client.close();\n }\n },\n getSocket() {\n return client?.ws ?? null;\n },\n async getSocketAsync() {\n await getClient().connect();\n const c = getClient();\n if (!c.ws)\n throw new Error('WebSocket not connected');\n return c.ws;\n },\n };\n return self;\n}\n//# sourceMappingURL=webSocket.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@rpckit/websocket/dist/webSocket.js?");
1878
1788
 
1879
1789
  /***/ }),
1880
1790
 
1881
- /***/ "../../node_modules/lossless-json/lib/esm/stringify.js":
1882
- /*!*************************************************************!*\
1883
- !*** ../../node_modules/lossless-json/lib/esm/stringify.js ***!
1884
- \*************************************************************/
1791
+ /***/ "../../node_modules/isows/_esm/native.js":
1792
+ /*!***********************************************!*\
1793
+ !*** ../../node_modules/isows/_esm/native.js ***!
1794
+ \***********************************************/
1885
1795
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1886
1796
 
1887
- eval("/* unused harmony export stringify */\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"../../node_modules/lossless-json/lib/esm/utils.js\");\n\n\n/**\n * The LosslessJSON.stringify() method converts a JavaScript value to a JSON string,\n * optionally replacing values if a replacer function is specified, or\n * optionally including only the specified properties if a replacer array is specified.\n *\n * @param value\n * The value to convert to a JSON string.\n *\n * @param [replacer]\n * A function that alters the behavior of the stringification process,\n * or an array of String and Number objects that serve as a whitelist for\n * selecting the properties of the value object to be included in the JSON string.\n * If this value is null or not provided, all properties of the object are\n * included in the resulting JSON string.\n *\n * @param [space]\n * A String or Number object that's used to insert white space into the output\n * JSON string for readability purposes. If this is a Number, it indicates the\n * number of space characters to use as white space; this number is capped at 10\n * if it's larger than that. Values less than 1 indicate that no space should be\n * used. If this is a String, the string (or the first 10 characters of the string,\n * if it's longer than that) is used as white space. If this parameter is not\n * provided (or is null), no white space is used.\n *\n * @param [numberStringifiers]\n * An optional list with additional number stringifiers, for example to serialize\n * a BigNumber. The output of the function must be valid stringified JSON.\n * When `undefined` is returned, the property will be deleted from the object.\n * The difference with using a `replacer` is that the output of a `replacer`\n * must be JSON and will be stringified afterwards, whereas the output of the\n * `numberStringifiers` is already stringified JSON.\n *\n * @returns Returns the string representation of the JSON object.\n */\nfunction stringify(value, replacer, space, numberStringifiers) {\n const resolvedSpace = resolveSpace(space);\n const replacedValue = typeof replacer === 'function' ? replacer.call({\n '': value\n }, '', value) : value;\n return stringifyValue(replacedValue, '');\n\n /**\n * Stringify a value\n */\n function stringifyValue(value, indent) {\n if (Array.isArray(numberStringifiers)) {\n const stringifier = numberStringifiers.find(item => item.test(value));\n if (stringifier) {\n const str = stringifier.stringify(value);\n if (typeof str !== 'string' || !(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.isNumber)(str)) {\n throw new Error(`Invalid JSON number: output of a number stringifier must be a string containing a JSON number (output: ${str})`);\n }\n return str;\n }\n }\n\n // boolean, null, number, string, or date\n if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string' || value === null || value instanceof Date || value instanceof Boolean || value instanceof Number || value instanceof String) {\n return JSON.stringify(value);\n }\n\n // lossless number, the secret ingredient :)\n // @ts-ignore\n if (value?.isLosslessNumber) {\n return value.toString();\n }\n\n // BigInt\n if (typeof value === 'bigint') {\n return value.toString();\n }\n\n // Array\n if (Array.isArray(value)) {\n return stringifyArray(value, indent);\n }\n\n // Object (test lastly!)\n if (value && typeof value === 'object') {\n return stringifyObject(value, indent);\n }\n return undefined;\n }\n\n /**\n * Stringify an array\n */\n function stringifyArray(array, indent) {\n if (array.length === 0) {\n return '[]';\n }\n const childIndent = resolvedSpace ? indent + resolvedSpace : undefined;\n let str = resolvedSpace ? '[\\n' : '[';\n for (let i = 0; i < array.length; i++) {\n const item = typeof replacer === 'function' ? replacer.call(array, String(i), array[i]) : array[i];\n if (resolvedSpace) {\n str += childIndent;\n }\n if (typeof item !== 'undefined' && typeof item !== 'function') {\n str += stringifyValue(item, childIndent);\n } else {\n str += 'null';\n }\n if (i < array.length - 1) {\n str += resolvedSpace ? ',\\n' : ',';\n }\n }\n str += resolvedSpace ? `\\n${indent}]` : ']';\n return str;\n }\n\n /**\n * Stringify an object\n */\n function stringifyObject(object, indent) {\n if (typeof object.toJSON === 'function') {\n return stringify(object.toJSON(), replacer, space, undefined);\n }\n const keys = Array.isArray(replacer) ? replacer.map(String) : Object.keys(object);\n if (keys.length === 0) {\n return '{}';\n }\n const childIndent = resolvedSpace ? indent + resolvedSpace : undefined;\n let first = true;\n let str = resolvedSpace ? '{\\n' : '{';\n for (const key of keys) {\n const value = typeof replacer === 'function' ? replacer.call(object, key, object[key]) : object[key];\n if (includeProperty(key, value)) {\n if (first) {\n first = false;\n } else {\n str += resolvedSpace ? ',\\n' : ',';\n }\n const keyStr = JSON.stringify(key);\n str += resolvedSpace ? `${childIndent + keyStr}: ` : `${keyStr}:`;\n str += stringifyValue(value, childIndent);\n }\n }\n str += resolvedSpace ? `\\n${indent}}` : '}';\n return str;\n }\n\n /**\n * Test whether to include a property in a stringified object or not.\n */\n function includeProperty(_key, value) {\n return typeof value !== 'undefined' && typeof value !== 'function' && typeof value !== 'symbol';\n }\n}\n\n/**\n * Resolve a JSON stringify space:\n * replace a number with a string containing that number of spaces\n */\nfunction resolveSpace(space) {\n if (typeof space === 'number') {\n return ' '.repeat(space);\n }\n if (typeof space === 'string' && space !== '') {\n return space;\n }\n return undefined;\n}\n//# sourceMappingURL=stringify.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/lossless-json/lib/esm/stringify.js?");
1888
-
1889
- /***/ }),
1890
-
1891
- /***/ "../../node_modules/lossless-json/lib/esm/types.js":
1892
- /*!*********************************************************!*\
1893
- !*** ../../node_modules/lossless-json/lib/esm/types.js ***!
1894
- \*********************************************************/
1895
- /***/ (() => {
1896
-
1897
- eval("\n//# sourceMappingURL=types.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/lossless-json/lib/esm/types.js?");
1797
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"WebSocket\": () => (/* binding */ WebSocket)\n/* harmony export */ });\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"../../node_modules/isows/_esm/utils.js\");\n\nconst WebSocket = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.getNativeWebSocket)();\n//# sourceMappingURL=native.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/isows/_esm/native.js?");
1898
1798
 
1899
1799
  /***/ }),
1900
1800
 
1901
- /***/ "../../node_modules/lossless-json/lib/esm/utils.js":
1902
- /*!*********************************************************!*\
1903
- !*** ../../node_modules/lossless-json/lib/esm/utils.js ***!
1904
- \*********************************************************/
1801
+ /***/ "../../node_modules/isows/_esm/utils.js":
1802
+ /*!**********************************************!*\
1803
+ !*** ../../node_modules/isows/_esm/utils.js ***!
1804
+ \**********************************************/
1905
1805
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1906
1806
 
1907
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"UnsafeNumberReason\": () => (/* binding */ UnsafeNumberReason),\n/* harmony export */ \"compareNumber\": () => (/* binding */ compareNumber),\n/* harmony export */ \"countSignificantDigits\": () => (/* binding */ countSignificantDigits),\n/* harmony export */ \"getUnsafeNumberReason\": () => (/* binding */ getUnsafeNumberReason),\n/* harmony export */ \"isInteger\": () => (/* binding */ isInteger),\n/* harmony export */ \"isNumber\": () => (/* binding */ isNumber)\n/* harmony export */ });\n/* unused harmony exports isSafeNumber, toSafeNumberOrThrow, splitNumber, extractSignificantDigits */\n/**\n * Test whether a string contains an integer number\n */\nfunction isInteger(value) {\n return INTEGER_REGEX.test(value);\n}\nconst INTEGER_REGEX = /^-?[0-9]+$/;\n\n/**\n * Test whether a string contains a number\n * http://stackoverflow.com/questions/13340717/json-numbers-regular-expression\n */\nfunction isNumber(value) {\n return NUMBER_REGEX.test(value);\n}\nconst NUMBER_REGEX = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;\n\n/**\n * Test whether a string can be safely represented with a number\n * without information loss.\n *\n * When approx is true, floating point numbers that lose a few digits but\n * are still approximately equal in value are considered safe too.\n * Integer numbers must still be exactly equal.\n */\nfunction isSafeNumber(value, config) {\n const num = Number.parseFloat(value);\n const parsed = String(num);\n if (value === parsed) {\n return true;\n }\n const valueDigits = extractSignificantDigits(value);\n const parsedDigits = extractSignificantDigits(parsed);\n if (valueDigits === parsedDigits) {\n return true;\n }\n if (config?.approx === true) {\n // A value is approximately equal when:\n // 1. it is a floating point number, not an integer\n // 2. it has at least 14 digits\n // 3. the first 14 digits are equal\n const requiredDigits = 14;\n if (!isInteger(value) && parsedDigits.length >= requiredDigits && valueDigits.startsWith(parsedDigits.substring(0, requiredDigits))) {\n return true;\n }\n }\n return false;\n}\nlet UnsafeNumberReason = /*#__PURE__*/function (UnsafeNumberReason) {\n UnsafeNumberReason[\"underflow\"] = \"underflow\";\n UnsafeNumberReason[\"overflow\"] = \"overflow\";\n UnsafeNumberReason[\"truncate_integer\"] = \"truncate_integer\";\n UnsafeNumberReason[\"truncate_float\"] = \"truncate_float\";\n return UnsafeNumberReason;\n}({});\n\n/**\n * When the provided value is an unsafe number, describe what the reason is:\n * overflow, underflow, truncate_integer, or truncate_float.\n * Returns undefined when the value is safe.\n */\nfunction getUnsafeNumberReason(value) {\n if (isSafeNumber(value, {\n approx: false\n })) {\n return undefined;\n }\n if (isInteger(value)) {\n return UnsafeNumberReason.truncate_integer;\n }\n const num = Number.parseFloat(value);\n if (!Number.isFinite(num)) {\n return UnsafeNumberReason.overflow;\n }\n if (num === 0) {\n return UnsafeNumberReason.underflow;\n }\n return UnsafeNumberReason.truncate_float;\n}\n\n/**\n * Convert a string into a number when it is safe to do so.\n * Throws an error otherwise, explaining the reason.\n */\nfunction toSafeNumberOrThrow(value, config) {\n const number = Number.parseFloat(value);\n const unsafeReason = getUnsafeNumberReason(value);\n if (config?.approx === true ? unsafeReason && unsafeReason !== UnsafeNumberReason.truncate_float : unsafeReason) {\n const unsafeReasonText = unsafeReason?.replace(/_\\w+$/, '');\n throw new Error(`Cannot safely convert to number: the value '${value}' would ${unsafeReasonText} and become ${number}`);\n }\n return number;\n}\n\n/**\n * Split a number into sign, digits, and exponent.\n * The value can be constructed again from a split number by inserting a dot\n * at the second character of the digits if there is more than one digit,\n * prepending it with the sign, and appending the exponent like `e${exponent}`\n */\nfunction splitNumber(value) {\n const match = value.match(/^(-?)(\\d+\\.?\\d*)([eE]([+-]?\\d+))?$/);\n if (!match) {\n throw new SyntaxError(`Invalid number: ${value}`);\n }\n const sign = match[1];\n const digitsStr = match[2];\n let exponent = match[4] !== undefined ? Number.parseInt(match[4]) : 0;\n const dot = digitsStr.indexOf('.');\n exponent += dot !== -1 ? dot - 1 : digitsStr.length - 1;\n const digits = digitsStr.replace('.', '') // remove the dot (must be removed before removing leading zeros)\n .replace(/^0*/, zeros => {\n // remove leading zeros, add their count to the exponent\n exponent -= zeros.length;\n return '';\n }).replace(/0*$/, ''); // remove trailing zeros\n\n return digits.length > 0 ? {\n sign,\n digits,\n exponent\n } : {\n sign,\n digits: '0',\n exponent: exponent + 1\n };\n}\n\n/**\n * Compare two strings containing a numeric value\n * Returns 1 when a is larger than b, 0 when they are equal,\n * and -1 when a is smaller than b.\n */\nfunction compareNumber(a, b) {\n if (a === b) {\n return 0;\n }\n const aa = splitNumber(a);\n const bb = splitNumber(b);\n const sign = aa.sign === '-' ? -1 : 1;\n if (aa.sign !== bb.sign) {\n if (aa.digits === '0' && bb.digits === '0') {\n return 0;\n }\n return sign;\n }\n if (aa.exponent !== bb.exponent) {\n return aa.exponent > bb.exponent ? sign : aa.exponent < bb.exponent ? -sign : 0;\n }\n return aa.digits > bb.digits ? sign : aa.digits < bb.digits ? -sign : 0;\n}\n\n/**\n * Count the significant digits of a number.\n *\n * For example:\n * '2.34' returns 3\n * '-77' returns 2\n * '0.003400' returns 2\n * '120.5e+30' returns 4\n **/\nfunction countSignificantDigits(value) {\n const {\n start,\n end\n } = getSignificantDigitRange(value);\n const dot = value.indexOf('.');\n if (dot === -1 || dot < start || dot > end) {\n return end - start;\n }\n return end - start - 1;\n}\n\n/**\n * Get the significant digits of a number.\n *\n * For example:\n * '2.34' returns '234'\n * '-77' returns '77'\n * '0.003400' returns '34'\n * '120.5e+30' returns '1205'\n **/\nfunction extractSignificantDigits(value) {\n const {\n start,\n end\n } = getSignificantDigitRange(value);\n const digits = value.substring(start, end);\n const dot = digits.indexOf('.');\n if (dot === -1) {\n return digits;\n }\n return digits.substring(0, dot) + digits.substring(dot + 1);\n}\n\n/**\n * Returns the range (start to end) of the significant digits of a value.\n * Note that this range _may_ contain the decimal dot.\n *\n * For example:\n *\n * getSignificantDigitRange('0.0325900') // { start: 3, end: 7 }\n * getSignificantDigitRange('2.0300') // { start: 0, end: 3 }\n * getSignificantDigitRange('0.0') // { start: 3, end: 3 }\n *\n */\nfunction getSignificantDigitRange(value) {\n let start = 0;\n if (value[0] === '-') {\n start++;\n }\n while (value[start] === '0' || value[start] === '.') {\n start++;\n }\n let end = value.lastIndexOf('e');\n if (end === -1) {\n end = value.lastIndexOf('E');\n }\n if (end === -1) {\n end = value.length;\n }\n while ((value[end - 1] === '0' || value[end - 1] === '.') && end > start) {\n end--;\n }\n return {\n start,\n end\n };\n}\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/lossless-json/lib/esm/utils.js?");
1807
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getNativeWebSocket\": () => (/* binding */ getNativeWebSocket)\n/* harmony export */ });\nfunction getNativeWebSocket() {\n if (typeof WebSocket !== \"undefined\")\n return WebSocket;\n if (typeof global.WebSocket !== \"undefined\")\n return global.WebSocket;\n if (typeof window.WebSocket !== \"undefined\")\n return window.WebSocket;\n if (typeof self.WebSocket !== \"undefined\")\n return self.WebSocket;\n throw new Error(\"`WebSocket` is not supported in this environment\");\n}\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/isows/_esm/utils.js?");
1908
1808
 
1909
1809
  /***/ })
1910
1810