@mainnet-cash/bcmr 3.1.6 → 4.0.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -9,44 +9,13 @@
|
|
|
9
9
|
/******/ (() => { // webpackBootstrap
|
|
10
10
|
/******/ var __webpack_modules__ = ({
|
|
11
11
|
|
|
12
|
-
/***/ "../../node_modules/@
|
|
13
|
-
|
|
14
|
-
!*** ../../node_modules/@
|
|
15
|
-
|
|
16
|
-
/***/ ((module, exports, __webpack_require__) => {
|
|
17
|
-
|
|
18
|
-
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-cash/bcmr/../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/browser.js?");
|
|
19
|
-
|
|
20
|
-
/***/ }),
|
|
21
|
-
|
|
22
|
-
/***/ "../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/common.js":
|
|
23
|
-
/*!*************************************************************************************!*\
|
|
24
|
-
!*** ../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/common.js ***!
|
|
25
|
-
\*************************************************************************************/
|
|
26
|
-
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
|
|
27
|
-
|
|
28
|
-
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-cash/bcmr/../../node_modules/@electrum-cash/debug-logs/node_modules/debug/src/common.js?");
|
|
29
|
-
|
|
30
|
-
/***/ }),
|
|
31
|
-
|
|
32
|
-
/***/ "../../node_modules/eventemitter3/index.js":
|
|
33
|
-
/*!*************************************************!*\
|
|
34
|
-
!*** ../../node_modules/eventemitter3/index.js ***!
|
|
35
|
-
\*************************************************/
|
|
12
|
+
/***/ "../../node_modules/@rpckit/core/dist lazy recursive":
|
|
13
|
+
/*!**************************************************************************!*\
|
|
14
|
+
!*** ../../node_modules/@rpckit/core/dist/ lazy strict namespace object ***!
|
|
15
|
+
\**************************************************************************/
|
|
36
16
|
/***/ ((module) => {
|
|
37
17
|
|
|
38
|
-
"
|
|
39
|
-
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-cash/bcmr/../../node_modules/eventemitter3/index.js?");
|
|
40
|
-
|
|
41
|
-
/***/ }),
|
|
42
|
-
|
|
43
|
-
/***/ "../../node_modules/ms/index.js":
|
|
44
|
-
/*!**************************************!*\
|
|
45
|
-
!*** ../../node_modules/ms/index.js ***!
|
|
46
|
-
\**************************************/
|
|
47
|
-
/***/ ((module) => {
|
|
48
|
-
|
|
49
|
-
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-cash/bcmr/../../node_modules/ms/index.js?");
|
|
18
|
+
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-cash/bcmr/../../node_modules/@rpckit/core/dist/_lazy_strict_namespace_object?");
|
|
50
19
|
|
|
51
20
|
/***/ }),
|
|
52
21
|
|
|
@@ -369,179 +338,102 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
369
338
|
|
|
370
339
|
/***/ }),
|
|
371
340
|
|
|
372
|
-
/***/ "../../node_modules/@
|
|
373
|
-
|
|
374
|
-
!*** ../../node_modules/@
|
|
375
|
-
|
|
376
|
-
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
377
|
-
|
|
378
|
-
"use strict";
|
|
379
|
-
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-cash/bcmr/../../node_modules/@electrum-cash/debug-logs/dist/index.mjs?");
|
|
380
|
-
|
|
381
|
-
/***/ }),
|
|
382
|
-
|
|
383
|
-
/***/ "../../node_modules/@electrum-cash/network/dist/index.mjs":
|
|
384
|
-
/*!****************************************************************!*\
|
|
385
|
-
!*** ../../node_modules/@electrum-cash/network/dist/index.mjs ***!
|
|
386
|
-
\****************************************************************/
|
|
387
|
-
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
388
|
-
|
|
389
|
-
"use strict";
|
|
390
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ConnectionStatus\": () => (/* binding */ $db7c797e63383364$export$7516420eb880ab68),\n/* harmony export */ \"ElectrumClient\": () => (/* binding */ $558b46d3f899ced5$export$2e2bcd8739ae039)\n/* harmony export */ });\n/* unused harmony exports isVersionRejected, isVersionNegotiated */\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 eventemitter3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! eventemitter3 */ \"../../node_modules/eventemitter3/index.mjs\");\n/* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! async-mutex */ \"../../node_modules/async-mutex/index.mjs\");\n/* harmony import */ var _electrum_cash_web_socket__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @electrum-cash/web-socket */ \"../../node_modules/@electrum-cash/web-socket/dist/index.mjs\");\n/* harmony import */ var lossless_json__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lossless-json */ \"../../node_modules/lossless-json/lib/esm/index.js\");\n\n\n\n\n\n\n\nfunction $parcel$export(e, n, v, s) {\n Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});\n}\n\n\n\nclass $24139611f53a54b8$export$5d955335434540c6 {\n /**\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 */ static buildRequestObject(method, parameters, requestId) {\n // Return the formatted request object.\n // NOTE: Electrum either uses JsonRPC strictly or loosely.\n // If we specify protocol identifier without being 100% compliant, we risk being disconnected/blacklisted.\n // For this reason, we omit the protocol identifier to avoid issues.\n return JSON.stringify({\n method: method,\n params: parameters,\n id: requestId\n });\n }\n /**\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 */ static get versionRegexp() {\n return /^\\d+(\\.\\d+)+$/;\n }\n /**\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 */ static get statementDelimiter() {\n return \"\\n\";\n }\n}\n\n\nvar $e83d2e7688025acd$exports = {};\n\n$parcel$export($e83d2e7688025acd$exports, \"isVersionRejected\", () => $e83d2e7688025acd$export$e1f38ab2b4ebdde6);\n$parcel$export($e83d2e7688025acd$exports, \"isVersionNegotiated\", () => $e83d2e7688025acd$export$9598f0c76aa41d73);\nconst $e83d2e7688025acd$export$e1f38ab2b4ebdde6 = function(object) {\n return \"error\" in object;\n};\nconst $e83d2e7688025acd$export$9598f0c76aa41d73 = function(object) {\n return \"software\" in object && \"protocol\" in object;\n};\n\n\n// Acceptable parameter types for RPC messages\nconst $abcb763a48577a1e$export$d73a2e87a509880 = function(message) {\n return \"id\" in message && \"error\" in message;\n};\nconst $abcb763a48577a1e$export$81276773828ff315 = function(message) {\n return \"id\" in message && \"result\" in message;\n};\nconst $abcb763a48577a1e$export$280de919a0cf6928 = function(message) {\n return !(\"id\" in message) && \"method\" in message;\n};\nconst $abcb763a48577a1e$export$94e3360fcddccc76 = function(message) {\n return \"id\" in message && \"method\" in message;\n};\n\n\n\nvar $db7c797e63383364$exports = {};\n\n$parcel$export($db7c797e63383364$exports, \"ConnectionStatus\", () => $db7c797e63383364$export$7516420eb880ab68);\n// Disable indent rule for this file because it is broken (https://github.com/typescript-eslint/typescript-eslint/issues/1824)\n/* eslint-disable @typescript-eslint/indent */ /**\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 */ var $db7c797e63383364$export$7516420eb880ab68;\n(function(ConnectionStatus) {\n ConnectionStatus[ConnectionStatus[\"DISCONNECTED\"] = 0] = \"DISCONNECTED\";\n ConnectionStatus[ConnectionStatus[\"CONNECTED\"] = 1] = \"CONNECTED\";\n ConnectionStatus[ConnectionStatus[\"DISCONNECTING\"] = 2] = \"DISCONNECTING\";\n ConnectionStatus[ConnectionStatus[\"CONNECTING\"] = 3] = \"CONNECTING\";\n ConnectionStatus[ConnectionStatus[\"RECONNECTING\"] = 4] = \"RECONNECTING\";\n})($db7c797e63383364$export$7516420eb880ab68 || ($db7c797e63383364$export$7516420eb880ab68 = {}));\n\n\n\nclass $ff134c9a9e1f7361$export$de0f57fc22079b5e extends (0, eventemitter3__WEBPACK_IMPORTED_MODULE_1__.EventEmitter) {\n /**\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 */ constructor(application, version, socketOrHostname, options){\n // Initialize the event emitter.\n super();\n this.application = application;\n this.version = version;\n this.socketOrHostname = socketOrHostname;\n this.options = options;\n this.status = (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED;\n this.verifications = [];\n this.messageBuffer = \"\";\n // Check if the provided version is a valid version number.\n if (!(0, $24139611f53a54b8$export$5d955335434540c6).versionRegexp.test(version)) // Throw an error since the version number was not valid.\n throw new Error(`Provided version string (${version}) is not a valid protocol version number.`);\n // If a hostname was provided..\n if (typeof socketOrHostname === \"string\") // Use a web socket with default parameters.\n this.socket = new (0, _electrum_cash_web_socket__WEBPACK_IMPORTED_MODULE_3__.ElectrumWebSocket)(socketOrHostname);\n else // Use the provided socket.\n this.socket = socketOrHostname;\n // Set up handlers for connection and disconnection.\n this.socket.on(\"connected\", this.onSocketConnect.bind(this));\n this.socket.on(\"disconnected\", this.onSocketDisconnect.bind(this));\n // Set up handler for incoming data.\n this.socket.on(\"data\", this.parseMessageChunk.bind(this));\n // Handle visibility changes when run in a browser environment (if not explicitly disabled).\n if (typeof document !== \"undefined\" && !this.options.disableBrowserVisibilityHandling) document.addEventListener(\"visibilitychange\", this.handleVisibilityChange.bind(this));\n // Handle network connection changes when run in a browser environment (if not explicitly disabled).\n if (typeof window !== \"undefined\" && !this.options.disableBrowserConnectivityHandling) {\n window.addEventListener(\"online\", this.handleNetworkChange.bind(this));\n window.addEventListener(\"offline\", this.handleNetworkChange.bind(this));\n }\n }\n // Expose hostIdentifier from the socket.\n get hostIdentifier() {\n return this.socket.hostIdentifier;\n }\n // Expose port from the socket.\n get encrypted() {\n return this.socket.encrypted;\n }\n /**\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 */ parseMessageChunk(data) {\n // Update the timestamp for when we last received data.\n this.lastReceivedTimestamp = Date.now();\n // Emit a notification indicating that the connection has received data.\n this.emit(\"received\");\n // Clear and remove all verification timers.\n this.verifications.forEach((timer)=>clearTimeout(timer));\n this.verifications.length = 0;\n // Add the message to the current message buffer.\n this.messageBuffer += data;\n // Check if the new message buffer contains the statement delimiter.\n while(this.messageBuffer.includes((0, $24139611f53a54b8$export$5d955335434540c6).statementDelimiter)){\n // Split message buffer into statements.\n const statementParts = this.messageBuffer.split((0, $24139611f53a54b8$export$5d955335434540c6).statementDelimiter);\n // For as long as we still have statements to parse..\n while(statementParts.length > 1){\n // Move the first statement to its own variable.\n const currentStatementList = String(statementParts.shift());\n // Parse the statement into an object or list of objects.\n let statementList = (0, lossless_json__WEBPACK_IMPORTED_MODULE_4__.parse)(currentStatementList, null, this.options.useBigInt ? (0, lossless_json__WEBPACK_IMPORTED_MODULE_4__.parseNumberAndBigInt) : parseFloat);\n // Wrap the statement in an array if it is not already a batched statement list.\n if (!Array.isArray(statementList)) statementList = [\n statementList\n ];\n // For as long as there is statements in the result set..\n while(statementList.length > 0){\n // Move the first statement from the batch to its own variable.\n const currentStatement = statementList.shift();\n // If the current statement is a subscription notification..\n if ((0, $abcb763a48577a1e$export$280de919a0cf6928)(currentStatement)) {\n // Emit the notification for handling higher up in the stack.\n this.emit(\"response\", currentStatement);\n continue;\n }\n // If the current statement is a version negotiation response..\n if (currentStatement.id === \"versionNegotiation\") {\n if ((0, $abcb763a48577a1e$export$d73a2e87a509880)(currentStatement)) // Then emit a failed version negotiation response signal.\n this.emit(\"version\", {\n error: currentStatement.error\n });\n else {\n // Extract the software and protocol version reported.\n const [software, protocol] = currentStatement.result;\n // Emit a successful version negotiation response signal.\n this.emit(\"version\", {\n software: software,\n protocol: protocol\n });\n }\n continue;\n }\n // If the current statement is a keep-alive response..\n if (currentStatement.id === \"keepAlive\") continue;\n // Emit the statements for handling higher up in the stack.\n this.emit(\"response\", currentStatement);\n }\n }\n // Store the remaining statement as the current message buffer.\n this.messageBuffer = statementParts.shift() || \"\";\n }\n }\n /**\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 */ ping() {\n // Write a log message.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).ping(`Sending keep-alive ping to '${this.hostIdentifier}'`);\n // Craft a keep-alive message.\n const message = (0, $24139611f53a54b8$export$5d955335434540c6).buildRequestObject(\"server.ping\", [], \"keepAlive\");\n // Send the keep-alive message.\n const status = this.send(message);\n // Return the ping status.\n return status;\n }\n /**\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 */ async connect() {\n // If we are already connected return true.\n if (this.status === (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED) return;\n // Indicate that the connection is connecting\n this.status = (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTING;\n // Emit a connect event now that the connection is being set up.\n this.emit(\"connecting\");\n // Define a function to wrap connection as a promise.\n const connectionResolver = (resolve, reject)=>{\n const rejector = (error)=>{\n // Set the status back to disconnected\n this.status = (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED;\n // Emit a connect event indicating that we failed to connect.\n this.emit(\"disconnected\");\n // Reject with the error as reason\n reject(error);\n };\n // Replace previous error handlers to reject the promise on failure.\n this.socket.removeAllListeners(\"error\");\n this.socket.once(\"error\", rejector);\n // Define a function to wrap version negotiation as a callback.\n const versionNegotiator = ()=>{\n // Write a log message to show that we have started version negotiation.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).network(`Requesting protocol version ${this.version} with '${this.hostIdentifier}'.`);\n // remove the one-time error handler since no error was detected.\n this.socket.removeListener(\"error\", rejector);\n // Build a version negotiation message.\n const versionMessage = (0, $24139611f53a54b8$export$5d955335434540c6).buildRequestObject(\"server.version\", [\n this.application,\n this.version\n ], \"versionNegotiation\");\n // Define a function to wrap version validation as a function.\n const versionValidator = (version)=>{\n // Check if version negotiation failed.\n if ((0, $e83d2e7688025acd$export$e1f38ab2b4ebdde6)(version)) {\n // Disconnect from the host.\n this.disconnect(true);\n // Declare an error message.\n const errorMessage = \"unsupported protocol version.\";\n // Log the error.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).errors(`Failed to connect with ${this.hostIdentifier} due to ${errorMessage}`);\n // Reject the connection with false since version negotiation failed.\n reject(errorMessage);\n } else if (version.protocol !== this.version && `${version.protocol}.0` !== this.version && `${version.protocol}.0.0` !== this.version) {\n // Disconnect from the host.\n this.disconnect(true);\n // Declare an error message.\n const errorMessage = `incompatible protocol version negotiated (${version.protocol} !== ${this.version}).`;\n // Log the error.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).errors(`Failed to connect with ${this.hostIdentifier} due to ${errorMessage}`);\n // Reject the connection with false since version negotiation failed.\n reject(errorMessage);\n } else {\n // Write a log message.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).network(`Negotiated protocol version ${version.protocol} with '${this.hostIdentifier}', powered by ${version.software}.`);\n // Set connection status to connected\n this.status = (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED;\n // Emit a connect event now that the connection is usable.\n this.emit(\"connected\");\n // Resolve the connection promise since we successfully connected and negotiated protocol version.\n resolve();\n }\n };\n // Listen for version negotiation once.\n this.once(\"version\", versionValidator);\n // Send the version negotiation message.\n this.send(versionMessage);\n };\n // Prepare the version negotiation.\n this.socket.once(\"connected\", versionNegotiator);\n // Set up handler for network errors.\n this.socket.on(\"error\", this.onSocketError.bind(this));\n // Connect to the server.\n this.socket.connect();\n };\n // Wait until connection is established and version negotiation succeeds.\n await new Promise(connectionResolver);\n }\n /**\n\t * Restores the network connection.\n\t */ async reconnect() {\n // If a reconnect timer is set, remove it\n await this.clearReconnectTimer();\n // Write a log message.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).network(`Trying to reconnect to '${this.hostIdentifier}'..`);\n // Set the status to reconnecting for more accurate log messages.\n this.status = (0, $db7c797e63383364$export$7516420eb880ab68).RECONNECTING;\n // Emit a connect event now that the connection is usable.\n this.emit(\"reconnecting\");\n // Disconnect the underlying socket.\n this.socket.disconnect();\n try {\n // Try to connect again.\n await this.connect();\n } catch (error) {\n // Do nothing as the error should be handled via the disconnect and error signals.\n }\n }\n /**\n\t * Removes the current reconnect timer.\n\t */ clearReconnectTimer() {\n // If a reconnect timer is set, remove it\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n // Reset the timer reference.\n this.reconnectTimer = undefined;\n }\n /**\n\t * Removes the current keep-alive timer.\n\t */ clearKeepAliveTimer() {\n // If a keep-alive timer is set, remove it\n if (this.keepAliveTimer) clearTimeout(this.keepAliveTimer);\n // Reset the timer reference.\n this.keepAliveTimer = undefined;\n }\n /**\n\t * Initializes the keep alive timer loop.\n\t */ setupKeepAliveTimer() {\n // If the keep-alive timer loop is not currently set up..\n if (!this.keepAliveTimer) // Set a new keep-alive timer.\n this.keepAliveTimer = setTimeout(this.ping.bind(this), this.options.sendKeepAliveIntervalInMilliSeconds);\n }\n /**\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 */ async disconnect(force = false, intentional = true) {\n // Return early when there is nothing to disconnect from\n if (this.status === (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED && !force) // Return false to indicate that there was nothing to disconnect from.\n return false;\n // Update connection state if the disconnection is intentional.\n // NOTE: The state is meant to represent what the client is requesting, but\n // is used internally to handle visibility changes in browsers to ensure functional reconnection.\n if (intentional) // Set connection status to null to indicate tear-down is currently happening.\n this.status = (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTING;\n // Emit a connect event to indicate that we are disconnecting.\n this.emit(\"disconnecting\");\n // If a keep-alive timer is set, remove it.\n await this.clearKeepAliveTimer();\n // If a reconnect timer is set, remove it\n await this.clearReconnectTimer();\n const disconnectResolver = (resolve)=>{\n // Resolve to true after the connection emits a disconnect\n this.once(\"disconnected\", ()=>resolve(true));\n // Close the connection on the socket level.\n this.socket.disconnect();\n };\n // Return true to indicate that we disconnected.\n return new Promise(disconnectResolver);\n }\n /**\n\t * Updates the connection state based on browser reported connectivity.\n\t *\n\t * Most modern browsers are able to provide information on the connection state\n\t * which allows for significantly faster response times to network changes compared\n\t * to waiting for network requests to fail.\n\t *\n\t * When available, we make use of this to fail early to provide a better user experience.\n\t */ async handleNetworkChange() {\n // Do nothing if we do not have the navigator available.\n if (typeof window.navigator === \"undefined\") return;\n // Attempt to reconnect to the network now that we may be online again.\n if (window.navigator.onLine === true) this.reconnect();\n // Disconnected from the network so that cleanup can happen while we're offline.\n if (window.navigator.onLine !== true) {\n const forceDisconnect = true;\n const isIntentional = true;\n this.disconnect(forceDisconnect, isIntentional);\n }\n }\n /**\n\t * Updates connection state based on application visibility.\n\t *\n\t * Some browsers will disconnect network connections when the browser is out of focus,\n\t * which would normally cause our reconnect-on-timeout routines to trigger, but that\n\t * results in a poor user experience since the events are not handled consistently\n\t * and sometimes it can take some time after restoring focus to the browser.\n\t *\n\t * By manually disconnecting when this happens we prevent the default reconnection routines\n\t * and make the behavior consistent across browsers.\n\t */ async handleVisibilityChange() {\n // Disconnect when application is removed from focus.\n if (document.visibilityState === \"hidden\") {\n const forceDisconnect = true;\n const isIntentional = true;\n this.disconnect(forceDisconnect, isIntentional);\n }\n // Reconnect when application is returned to focus.\n if (document.visibilityState === \"visible\") this.reconnect();\n }\n /**\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 */ send(message) {\n // Remove the current keep-alive timer if it exists.\n this.clearKeepAliveTimer();\n // Get the current timestamp in milliseconds.\n const currentTime = Date.now();\n // Follow up and verify that the message got sent..\n const verificationTimer = setTimeout(this.verifySend.bind(this, currentTime), this.socket.timeout);\n // Store the verification timer locally so that it can be cleared when data has been received.\n this.verifications.push(verificationTimer);\n // Set a new keep-alive timer.\n this.setupKeepAliveTimer();\n // Write the message to the network socket.\n return this.socket.write(message + (0, $24139611f53a54b8$export$5d955335434540c6).statementDelimiter);\n }\n // --- Event managers. --- //\n /**\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 */ verifySend(sentTimestamp) {\n // If we haven't received any data since we last sent data out..\n if (Number(this.lastReceivedTimestamp) < sentTimestamp) {\n // If this connection is already disconnected, we do not change anything\n if (this.status === (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED || this.status === (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTING) // debug.warning(`Tried to verify already disconnected connection to '${this.hostIdentifier}'`);\n return;\n // Remove the current keep-alive timer if it exists.\n this.clearKeepAliveTimer();\n // Write a notification to the logs.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).network(`Connection to '${this.hostIdentifier}' timed out.`);\n // Close the connection to avoid re-use.\n // NOTE: This initiates reconnection routines if the connection has not\n // been marked as intentionally disconnected.\n this.socket.disconnect();\n }\n }\n /**\n\t * Updates the connection status when a connection is confirmed.\n\t */ onSocketConnect() {\n // If a reconnect timer is set, remove it.\n this.clearReconnectTimer();\n // Set up the initial timestamp for when we last received data from the server.\n this.lastReceivedTimestamp = Date.now();\n // Set up the initial keep-alive timer.\n this.setupKeepAliveTimer();\n // Clear all temporary error listeners.\n this.socket.removeAllListeners(\"error\");\n // Set up handler for network errors.\n this.socket.on(\"error\", this.onSocketError.bind(this));\n }\n /**\n\t * Updates the connection status when a connection is ended.\n\t */ onSocketDisconnect() {\n // Remove the current keep-alive timer if it exists.\n this.clearKeepAliveTimer();\n // If this is a connection we're trying to tear down..\n if (this.status === (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTING) {\n // Mark the connection as disconnected.\n this.status = (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED;\n // Send a disconnect signal higher up the stack.\n this.emit(\"disconnected\");\n // If a reconnect timer is set, remove it.\n this.clearReconnectTimer();\n // Remove all event listeners\n this.removeAllListeners();\n // Write a log message.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).network(`Disconnected from '${this.hostIdentifier}'.`);\n } else {\n // If this is for an established connection..\n if (this.status === (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED) // Write a notification to the logs.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).errors(`Connection with '${this.hostIdentifier}' was closed, trying to reconnect in ${this.options.reconnectAfterMilliSeconds / 1000} seconds.`);\n // Mark the connection as disconnected for now..\n this.status = (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED;\n // Send a disconnect signal higher up the stack.\n this.emit(\"disconnected\");\n // If we don't have a pending reconnection timer..\n if (!this.reconnectTimer) // Attempt to reconnect after one keep-alive duration.\n this.reconnectTimer = setTimeout(this.reconnect.bind(this), this.options.reconnectAfterMilliSeconds);\n }\n }\n /**\n\t * Notify administrator of any unexpected errors.\n\t */ onSocketError(error) {\n // Report a generic error if no error information is present.\n // NOTE: When using WSS, the error event explicitly\n // only allows to send a \"simple\" event without data.\n // https://stackoverflow.com/a/18804298\n if (typeof error === \"undefined\") // Do nothing, and instead rely on the socket disconnect event for further information.\n return;\n // Log the error, as there is nothing we can do to actually handle it.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).errors(`Network error ('${this.hostIdentifier}'): `, error);\n }\n}\n\n\n\n// Define number of milliseconds per second for legibility.\nconst $d801b1f9b7fc3074$var$MILLI_SECONDS_PER_SECOND = 1000;\nconst $d801b1f9b7fc3074$export$5ba3a4134d0d751d = {\n // By default, all numbers including integers are parsed as regular JavaScript numbers.\n useBigInt: false,\n // Send a ping message every seconds, to detect network problem as early as possible.\n sendKeepAliveIntervalInMilliSeconds: 1 * $d801b1f9b7fc3074$var$MILLI_SECONDS_PER_SECOND,\n // Try to reconnect 5 seconds after unintentional disconnects.\n reconnectAfterMilliSeconds: 5 * $d801b1f9b7fc3074$var$MILLI_SECONDS_PER_SECOND,\n // Try to detect stale connections 5 seconds after every send.\n verifyConnectionTimeoutInMilliSeconds: 5 * $d801b1f9b7fc3074$var$MILLI_SECONDS_PER_SECOND,\n // Automatically manage the connection for a consistent behavior across browsers and devices.\n disableBrowserVisibilityHandling: false,\n disableBrowserConnectivityHandling: false\n};\n\n\n\n\n\n\n/**\n * High-level Electrum client that lets applications send requests and subscribe to notification events from a server.\n */ class $558b46d3f899ced5$var$ElectrumClient extends (0, eventemitter3__WEBPACK_IMPORTED_MODULE_1__.EventEmitter) {\n /**\n\t * Number corresponding to the underlying connection status.\n\t */ get status() {\n return this.connection.status;\n }\n /**\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 */ constructor(application, version, socketOrHostname, options = {}){\n // Initialize the event emitter.\n super();\n this.application = application;\n this.version = version;\n this.socketOrHostname = socketOrHostname;\n this.options = options;\n this.subscriptionMethods = {};\n this.requestId = 0;\n this.requestResolvers = {};\n this.connectionLock = new (0, async_mutex__WEBPACK_IMPORTED_MODULE_2__.Mutex)();\n // Update default options with the provided values.\n const networkOptions = {\n ...(0, $d801b1f9b7fc3074$export$5ba3a4134d0d751d),\n ...options\n };\n // Set up a connection to an electrum server.\n this.connection = new (0, $ff134c9a9e1f7361$export$de0f57fc22079b5e)(application, version, socketOrHostname, networkOptions);\n }\n // Expose hostIdentifier from the connection.\n get hostIdentifier() {\n return this.connection.hostIdentifier;\n }\n // Expose port from the connection.\n get encrypted() {\n return this.connection.encrypted;\n }\n /**\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 */ async connect() {\n // Create a lock so that multiple connects/disconnects cannot race each other.\n const unlock = await this.connectionLock.acquire();\n try {\n // If we are already connected, do not attempt to connect again.\n if (this.connection.status === (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED) return;\n // Listen for parsed statements.\n this.connection.on(\"response\", this.response.bind(this));\n // Hook up handles for the connected and disconnected events.\n this.connection.on(\"connected\", this.resubscribeOnConnect.bind(this));\n this.connection.on(\"disconnected\", this.onConnectionDisconnect.bind(this));\n // Relay connecting and reconnecting events.\n this.connection.on(\"connecting\", this.handleConnectionStatusChanges.bind(this, \"connecting\"));\n this.connection.on(\"disconnecting\", this.handleConnectionStatusChanges.bind(this, \"disconnecting\"));\n this.connection.on(\"reconnecting\", this.handleConnectionStatusChanges.bind(this, \"reconnecting\"));\n // Hook up client metadata gathering functions.\n this.connection.on(\"version\", this.storeSoftwareVersion.bind(this));\n this.connection.on(\"received\", this.updateLastReceivedTimestamp.bind(this));\n // Relay error events.\n this.connection.on(\"error\", this.emit.bind(this, \"error\"));\n // Connect with the server.\n await this.connection.connect();\n } finally{\n unlock();\n }\n }\n /**\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 */ async disconnect(force = false, retainSubscriptions = false) {\n if (!retainSubscriptions) {\n // Cancel all event listeners.\n this.removeAllListeners();\n // Remove all subscription data\n this.subscriptionMethods = {};\n }\n // Disconnect from the remote server.\n return this.connection.disconnect(force);\n }\n /**\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 */ async request(method, ...parameters) {\n // If we are not connected to a server..\n if (this.connection.status !== (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED) // Reject the request with a disconnected error message.\n throw new Error(`Unable to send request to a disconnected server '${this.hostIdentifier}'.`);\n // Increase the request ID by one.\n this.requestId += 1;\n // Store a copy of the request id.\n const id = this.requestId;\n // Format the arguments as an electrum request object.\n const message = (0, $24139611f53a54b8$export$5d955335434540c6).buildRequestObject(method, parameters, id);\n // Define a function to wrap the request in a promise.\n const requestResolver = (resolve)=>{\n // Add a request resolver for this promise to the list of requests.\n this.requestResolvers[id] = (error, data)=>{\n // If the resolution failed..\n if (error) // Resolve the promise with the error for the application to handle.\n resolve(error);\n else // Resolve the promise with the request results.\n resolve(data);\n };\n // Send the request message to the remote server.\n this.connection.send(message);\n };\n // Write a log message.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).network(`Sending request '${method}' to '${this.hostIdentifier}'`);\n // return a promise to deliver results later.\n return new Promise(requestResolver);\n }\n /**\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 */ async subscribe(method, ...parameters) {\n // Initialize an empty list of subscription payloads, if needed.\n if (!this.subscriptionMethods[method]) this.subscriptionMethods[method] = new Set();\n // Store the subscription parameters to track what data we have subscribed to.\n this.subscriptionMethods[method].add(JSON.stringify(parameters));\n // Send initial subscription request.\n const requestData = await this.request(method, ...parameters);\n // If the request failed, throw it as an error.\n if (requestData instanceof Error) throw requestData;\n // If the request returned more than one data point..\n if (Array.isArray(requestData)) // .. throw an error, as this breaks our expectation for subscriptions.\n throw new Error(\"Subscription request returned an more than one data point.\");\n // Construct a notification structure to package the initial result as a notification.\n const notification = {\n jsonrpc: \"2.0\",\n method: method,\n params: [\n ...parameters,\n requestData\n ]\n };\n // Manually emit an event for the initial response.\n this.emit(\"notification\", notification);\n // Try to update the chain height.\n this.updateChainHeightFromHeadersNotifications(notification);\n }\n /**\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 */ async unsubscribe(method, ...parameters) {\n // Throw an error if the client is disconnected.\n if (this.connection.status !== (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED) throw new Error(`Unable to send unsubscribe request to a disconnected server '${this.hostIdentifier}'.`);\n // If this method has no subscriptions..\n if (!this.subscriptionMethods[method]) // Reject this promise with an explanation.\n throw new Error(`Cannot unsubscribe from '${method}' since the method has no subscriptions.`);\n // Pack up the parameters as a long string.\n const subscriptionParameters = JSON.stringify(parameters);\n // If the method payload could not be located..\n if (!this.subscriptionMethods[method].has(subscriptionParameters)) // Reject this promise with an explanation.\n throw new Error(`Cannot unsubscribe from '${method}' since it has no subscription with the given parameters.`);\n // Remove this specific subscription payload from internal tracking.\n this.subscriptionMethods[method].delete(subscriptionParameters);\n // Send unsubscription request to the server\n // NOTE: As a convenience we allow users to define the method as the subscribe or unsubscribe version.\n await this.request(method.replace(\".subscribe\", \".unsubscribe\"), ...parameters);\n // Write a log message.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).client(`Unsubscribed from '${String(method)}' for the '${subscriptionParameters}' parameters.`);\n }\n /**\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 */ async resubscribeOnConnect() {\n // Write a log message.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).client(`Connected to '${this.hostIdentifier}'.`);\n // Synchronize with the underlying connection status.\n this.handleConnectionStatusChanges(\"connected\");\n // Initialize an empty list of resubscription promises.\n const resubscriptionPromises = [];\n // For each method we have a subscription for..\n for(const method in this.subscriptionMethods){\n // .. and for each parameter we have previously been subscribed to..\n for (const parameterJSON of this.subscriptionMethods[method].values()){\n // restore the parameters from JSON.\n const parameters = JSON.parse(parameterJSON);\n // Send a subscription request.\n resubscriptionPromises.push(this.subscribe(method, ...parameters));\n }\n // Wait for all re-subscriptions to complete.\n await Promise.all(resubscriptionPromises);\n }\n // Write a log message if there was any subscriptions to restore.\n if (resubscriptionPromises.length > 0) (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).client(`Restored ${resubscriptionPromises.length} previous subscriptions for '${this.hostIdentifier}'`);\n }\n /**\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 */ response(message) {\n // If the received message is a notification, we forward it to all event listeners\n if ((0, $abcb763a48577a1e$export$280de919a0cf6928)(message)) {\n // Write a log message.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).client(`Received notification for '${message.method}' from '${this.hostIdentifier}'`);\n // Forward the message content to all event listeners.\n this.emit(\"notification\", message);\n // Try to update the chain height.\n this.updateChainHeightFromHeadersNotifications(message);\n // Return since it does not have an associated request resolver\n return;\n }\n // If the response ID is null we cannot use it to index our request resolvers\n if (message.id === null) // Throw an internal error, this should not happen.\n throw new Error(\"Internal error: Received an RPC response with ID null.\");\n // Look up which request promise we should resolve this.\n const requestResolver = this.requestResolvers[message.id];\n // If we do not have a request resolver for this response message..\n if (!requestResolver) {\n // Log that a message was ignored since the request has already been rejected.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_0__[\"default\"]).warning(`Ignoring response #${message.id} as the request has already been rejected.`);\n // Return as this has now been fully handled.\n return;\n }\n // Remove the promise from the request list.\n delete this.requestResolvers[message.id];\n // If the message contains an error..\n if ((0, $abcb763a48577a1e$export$d73a2e87a509880)(message)) // Forward the message error to the request resolver and omit the `result` parameter.\n requestResolver(new Error(message.error.message));\n else {\n // Forward the message content to the request resolver and omit the `error` parameter\n // (by setting it to undefined).\n requestResolver(undefined, message.result);\n // Attempt to extract genesis hash from feature requests.\n this.storeGenesisHashFromFeaturesResponse(message);\n }\n }\n /**\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 */ async onConnectionDisconnect() {\n // Loop over active requests\n for(const resolverId in this.requestResolvers){\n // Extract request resolver for readability\n const requestResolver = this.requestResolvers[resolverId];\n // Resolve the active request with an error indicating that the connection was lost.\n requestResolver(new Error(\"Connection lost\"));\n // Remove the promise from the request list.\n delete this.requestResolvers[resolverId];\n }\n // Synchronize with the underlying connection status.\n this.handleConnectionStatusChanges(\"disconnected\");\n }\n /**\n\t * Stores the server provider software version field on successful version negotiation.\n\t *\n\t * @ignore\n\t */ async storeSoftwareVersion(versionStatement) {\n // TODO: handle failed version negotiation better.\n if (versionStatement.error) // Do nothing.\n return;\n // Store the software version.\n this.software = versionStatement.software;\n }\n /**\n\t * Updates the last received timestamp.\n\t *\n\t * @ignore\n\t */ async updateLastReceivedTimestamp() {\n // Update the timestamp for when we last received data.\n this.lastReceivedTimestamp = Date.now();\n }\n /**\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 */ async updateChainHeightFromHeadersNotifications(message) {\n // If the message is a notification for a new chain height..\n if (message.method === \"blockchain.headers.subscribe\") // ..also store the updated chain height locally.\n this.chainHeight = message.params[0].height;\n }\n /**\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 */ async storeGenesisHashFromFeaturesResponse(message) {\n try {\n // If the message is a response to a features request..\n if (typeof message.result.genesis_hash !== \"undefined\") // ..store the genesis hash locally.\n this.genesisHash = message.result.genesis_hash;\n } catch (error) {\n // Do nothing.\n }\n }\n /**\n\t * Helper function to synchronize state and events with the underlying connection.\n\t */ async handleConnectionStatusChanges(eventName) {\n // Re-emit the event.\n this.emit(eventName);\n }\n}\nvar // Export the client.\n$558b46d3f899ced5$export$2e2bcd8739ae039 = $558b46d3f899ced5$var$ElectrumClient;\n\n\n\n\n\n\n\n//# sourceMappingURL=index.mjs.map\n\n\n//# sourceURL=webpack://@mainnet-cash/bcmr/../../node_modules/@electrum-cash/network/dist/index.mjs?");
|
|
391
|
-
|
|
392
|
-
/***/ }),
|
|
393
|
-
|
|
394
|
-
/***/ "../../node_modules/@electrum-cash/web-socket/dist/index.mjs":
|
|
395
|
-
/*!*******************************************************************!*\
|
|
396
|
-
!*** ../../node_modules/@electrum-cash/web-socket/dist/index.mjs ***!
|
|
397
|
-
\*******************************************************************/
|
|
398
|
-
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
399
|
-
|
|
400
|
-
"use strict";
|
|
401
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ElectrumWebSocket\": () => (/* binding */ $05743633fea447d4$export$25b4633f61498e1)\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\nfunction $parcel$export(e, n, v, s) {\n Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});\n}\nvar $05743633fea447d4$exports = {};\n\n$parcel$export($05743633fea447d4$exports, \"ElectrumWebSocket\", () => $05743633fea447d4$export$25b4633f61498e1);\n\n\n\n// Export a default timeout value of 30 seconds.\nconst $d801b1f9b7fc3074$export$1bddf2b96e25d075 = 30000;\n\n\nclass $05743633fea447d4$export$25b4633f61498e1 extends (0, eventemitter3__WEBPACK_IMPORTED_MODULE_1__.EventEmitter) {\n host;\n port;\n encrypted;\n timeout;\n // Declare an empty WebSocket.\n webSocket;\n // Used to disconnect after some time if initial connection is too slow.\n disconnectTimer;\n // Initialize boolean that indicates whether the onConnect function has run (initialize to false).\n onConnectHasRun;\n // Initialize event forwarding functions.\n eventForwarders;\n /**\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 */ constructor(host, port = 50004, encrypted = true, timeout = (0, $d801b1f9b7fc3074$export$1bddf2b96e25d075)){\n // Initialize the event emitter.\n super();\n this.host = host;\n this.port = port;\n this.encrypted = encrypted;\n this.timeout = timeout;\n this.onConnectHasRun = false;\n this.eventForwarders = {\n disconnect: ()=>this.emit(\"disconnected\"),\n wsData: (event)=>this.emit(\"data\", `${event.data}\\n`),\n wsError: (event)=>this.emit(\"error\", new Error(event.error))\n };\n }\n /**\n\t * Returns a string for the host identifier for usage in debug messages.\n\t */ get hostIdentifier() {\n return `${this.host}:${this.port}`;\n }\n /**\n\t * Connect to host:port using the specified transport\n\t */ connect() {\n // Check that no existing socket exists before initiating a new connection.\n if (this.webSocket) throw new Error(\"Cannot initiate a new socket connection when an existing connection exists\");\n // Set a timer to force disconnect after `timeout` seconds\n this.disconnectTimer = setTimeout(()=>this.disconnectOnTimeout(), this.timeout);\n // Remove the timer if a connection is successfully established\n this.once(\"connected\", this.clearDisconnectTimerOnTimeout);\n // Set a named connection type for logging purposes.\n const connectionType = this.encrypted ? \"an encrypted WebSocket\" : \"a WebSocket\";\n // Log that we are trying to establish a connection.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_2__[\"default\"]).network(`Initiating ${connectionType} connection to '${this.host}:${this.port}'.`);\n if (this.encrypted) // Initialize this.webSocket (rejecting self-signed certificates).\n // We reject self-signed certificates to match functionality of browsers.\n this.webSocket = new (0, _monsterbitar_isomorphic_ws__WEBPACK_IMPORTED_MODULE_0__.WebSocket)(`wss://${this.host}:${this.port}`);\n else // Initialize this.webSocket.\n this.webSocket = new (0, _monsterbitar_isomorphic_ws__WEBPACK_IMPORTED_MODULE_0__.WebSocket)(`ws://${this.host}:${this.port}`);\n // Trigger successful connection events.\n this.webSocket.addEventListener(\"open\", this.onConnect.bind(this));\n // Forward the encountered errors.\n this.webSocket.addEventListener(\"error\", this.eventForwarders.wsError);\n }\n /**\n\t * Sets up forwarding of events related to the connection.\n\t */ onConnect() {\n // If the onConnect function has already run, do not execute it again.\n if (this.onConnectHasRun) return;\n // Set a named connection type for logging purposes.\n const connectionType = this.encrypted ? \"an encrypted WebSocket\" : \"a WebSocket\";\n // Log that the connection has been established.\n (0, _electrum_cash_debug_logs__WEBPACK_IMPORTED_MODULE_2__[\"default\"]).network(`Established ${connectionType} connection with '${this.host}:${this.port}'.`);\n // Forward the socket events\n this.webSocket.addEventListener(\"close\", this.eventForwarders.disconnect);\n this.webSocket.addEventListener(\"message\", this.eventForwarders.wsData);\n // Indicate that the onConnect function has run.\n this.onConnectHasRun = true;\n // Emit the connect event.\n this.emit(\"connected\");\n }\n /**\n\t * Clears the disconnect timer if it is still active.\n\t */ clearDisconnectTimerOnTimeout() {\n // Clear the retry timer if it is still active.\n if (this.disconnectTimer) clearTimeout(this.disconnectTimer);\n }\n /**\n\t * Forcibly terminate the connection.\n\t *\n\t * @throws {Error} if no connection was found\n\t */ disconnect() {\n // Clear the disconnect timer so that the socket does not try to disconnect again later.\n this.clearDisconnectTimerOnTimeout();\n try {\n // Remove all event forwarders.\n this.webSocket.removeEventListener(\"close\", this.eventForwarders.disconnect);\n this.webSocket.removeEventListener(\"message\", this.eventForwarders.wsData);\n this.webSocket.removeEventListener(\"error\", this.eventForwarders.wsError);\n // Gracefully terminate the connection.\n this.webSocket.close();\n } catch (ignored) {\n // close() will throw an error if the connection has not been established yet.\n // We ignore this error, since no similar error gets thrown in the TLS Socket.\n } finally{\n // Remove the stored socket regardless of any thrown errors.\n this.webSocket = undefined;\n }\n // Indicate that the onConnect function has not run and it has to be run again.\n this.onConnectHasRun = false;\n // Emit a disconnect event\n this.emit(\"disconnected\");\n }\n /**\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 */ write(data, callback) {\n // Throw an error if no active connection is found\n if (!this.webSocket) throw new Error(\"Cannot write to socket when there is no active connection\");\n // Write data to the WebSocket\n this.webSocket.send(data, callback);\n // WebSockets always fit everything in a single request, so we return true\n return true;\n }\n /**\n\t * Force a disconnection if no connection is established after `timeout` milliseconds.\n\t */ disconnectOnTimeout() {\n // Remove the connect listener.\n this.removeListener(\"connected\", this.clearDisconnectTimerOnTimeout);\n // Emit an error event so that connect is rejected upstream.\n this.emit(\"error\", new Error(`Connection to '${this.host}:${this.port}' timed out after ${this.timeout} milliseconds`));\n // Forcibly disconnect to clean up the connection on timeout\n this.disconnect();\n }\n // Add magic glue that makes typedoc happy so that we can have the events listed on the class.\n connected;\n disconnected;\n data;\n error;\n}\n\n\n\n\n\n//# sourceMappingURL=index.mjs.map\n\n\n//# sourceURL=webpack://@mainnet-cash/bcmr/../../node_modules/@electrum-cash/web-socket/dist/index.mjs?");
|
|
402
|
-
|
|
403
|
-
/***/ }),
|
|
404
|
-
|
|
405
|
-
/***/ "../../node_modules/@monsterbitar/isomorphic-ws/browser.mjs":
|
|
406
|
-
/*!******************************************************************!*\
|
|
407
|
-
!*** ../../node_modules/@monsterbitar/isomorphic-ws/browser.mjs ***!
|
|
408
|
-
\******************************************************************/
|
|
409
|
-
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
410
|
-
|
|
411
|
-
"use strict";
|
|
412
|
-
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-cash/bcmr/../../node_modules/@monsterbitar/isomorphic-ws/browser.mjs?");
|
|
413
|
-
|
|
414
|
-
/***/ }),
|
|
415
|
-
|
|
416
|
-
/***/ "../../node_modules/async-mutex/index.mjs":
|
|
417
|
-
/*!************************************************!*\
|
|
418
|
-
!*** ../../node_modules/async-mutex/index.mjs ***!
|
|
419
|
-
\************************************************/
|
|
420
|
-
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
421
|
-
|
|
422
|
-
"use strict";
|
|
423
|
-
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-cash/bcmr/../../node_modules/async-mutex/index.mjs?");
|
|
424
|
-
|
|
425
|
-
/***/ }),
|
|
426
|
-
|
|
427
|
-
/***/ "../../node_modules/eventemitter3/index.mjs":
|
|
428
|
-
/*!**************************************************!*\
|
|
429
|
-
!*** ../../node_modules/eventemitter3/index.mjs ***!
|
|
430
|
-
\**************************************************/
|
|
431
|
-
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
432
|
-
|
|
433
|
-
"use strict";
|
|
434
|
-
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-cash/bcmr/../../node_modules/eventemitter3/index.mjs?");
|
|
435
|
-
|
|
436
|
-
/***/ }),
|
|
437
|
-
|
|
438
|
-
/***/ "../../node_modules/lossless-json/lib/esm/LosslessNumber.js":
|
|
439
|
-
/*!******************************************************************!*\
|
|
440
|
-
!*** ../../node_modules/lossless-json/lib/esm/LosslessNumber.js ***!
|
|
441
|
-
\******************************************************************/
|
|
341
|
+
/***/ "../../node_modules/@rpckit/core/dist/batch.js":
|
|
342
|
+
/*!*****************************************************!*\
|
|
343
|
+
!*** ../../node_modules/@rpckit/core/dist/batch.js ***!
|
|
344
|
+
\*****************************************************/
|
|
442
345
|
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
443
346
|
|
|
444
347
|
"use strict";
|
|
445
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"
|
|
348
|
+
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BatchScheduler\": () => (/* binding */ BatchScheduler)\n/* harmony export */ });\nclass BatchScheduler {\n queue = [];\n timer = null;\n config;\n raw;\n send;\n constructor(config, send) {\n this.config = { batchSize: config.batchSize ?? 10, wait: config.wait ?? 0 };\n this.raw = config.raw ?? false;\n this.send = send;\n }\n enqueue(request) {\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 for (const pending of batch) {\n pending.reject(error);\n }\n }\n }\n}\n//# sourceMappingURL=batch.js.map\n\n//# sourceURL=webpack://@mainnet-cash/bcmr/../../node_modules/@rpckit/core/dist/batch.js?");
|
|
446
349
|
|
|
447
350
|
/***/ }),
|
|
448
351
|
|
|
449
|
-
/***/ "../../node_modules/
|
|
450
|
-
|
|
451
|
-
!*** ../../node_modules/
|
|
452
|
-
|
|
352
|
+
/***/ "../../node_modules/@rpckit/core/dist/parse.js":
|
|
353
|
+
/*!*****************************************************!*\
|
|
354
|
+
!*** ../../node_modules/@rpckit/core/dist/parse.js ***!
|
|
355
|
+
\*****************************************************/
|
|
453
356
|
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
454
357
|
|
|
455
358
|
"use strict";
|
|
456
|
-
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-cash/bcmr/../../node_modules/lossless-json/lib/esm/config.js?");
|
|
359
|
+
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 - handled below\n else if (key === 'batchSize' || key === 'batchWait') {\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\n if (options.batchSize || options.batchWait) {\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 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 * - `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-cash/bcmr/../../node_modules/@rpckit/core/dist/parse.js?");
|
|
457
360
|
|
|
458
361
|
/***/ }),
|
|
459
362
|
|
|
460
|
-
/***/ "../../node_modules/
|
|
461
|
-
|
|
462
|
-
!*** ../../node_modules/
|
|
463
|
-
|
|
363
|
+
/***/ "../../node_modules/@rpckit/core/dist/retry.js":
|
|
364
|
+
/*!*****************************************************!*\
|
|
365
|
+
!*** ../../node_modules/@rpckit/core/dist/retry.js ***!
|
|
366
|
+
\*****************************************************/
|
|
464
367
|
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
465
368
|
|
|
466
369
|
"use strict";
|
|
467
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"
|
|
370
|
+
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-cash/bcmr/../../node_modules/@rpckit/core/dist/retry.js?");
|
|
468
371
|
|
|
469
372
|
/***/ }),
|
|
470
373
|
|
|
471
|
-
/***/ "../../node_modules/
|
|
472
|
-
|
|
473
|
-
!*** ../../node_modules/
|
|
474
|
-
|
|
374
|
+
/***/ "../../node_modules/@rpckit/fallback/dist/electrum-cash/fallback.js":
|
|
375
|
+
/*!**************************************************************************!*\
|
|
376
|
+
!*** ../../node_modules/@rpckit/fallback/dist/electrum-cash/fallback.js ***!
|
|
377
|
+
\**************************************************************************/
|
|
475
378
|
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
476
379
|
|
|
477
380
|
"use strict";
|
|
478
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"
|
|
381
|
+
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-cash/bcmr/../../node_modules/@rpckit/fallback/dist/electrum-cash/fallback.js?");
|
|
479
382
|
|
|
480
383
|
/***/ }),
|
|
481
384
|
|
|
482
|
-
/***/ "../../node_modules/
|
|
483
|
-
|
|
484
|
-
!*** ../../node_modules/
|
|
485
|
-
|
|
385
|
+
/***/ "../../node_modules/@rpckit/fallback/dist/fallback.js":
|
|
386
|
+
/*!************************************************************!*\
|
|
387
|
+
!*** ../../node_modules/@rpckit/fallback/dist/fallback.js ***!
|
|
388
|
+
\************************************************************/
|
|
486
389
|
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
487
390
|
|
|
488
391
|
"use strict";
|
|
489
|
-
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-cash/bcmr/../../node_modules/lossless-json/lib/esm/parse.js?");
|
|
392
|
+
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-cash/bcmr/../../node_modules/@rpckit/fallback/dist/fallback.js?");
|
|
490
393
|
|
|
491
394
|
/***/ }),
|
|
492
395
|
|
|
493
|
-
/***/ "../../node_modules/
|
|
494
|
-
|
|
495
|
-
!*** ../../node_modules/
|
|
496
|
-
|
|
396
|
+
/***/ "../../node_modules/@rpckit/websocket/dist/electrum-cash/webSocket.js":
|
|
397
|
+
/*!****************************************************************************!*\
|
|
398
|
+
!*** ../../node_modules/@rpckit/websocket/dist/electrum-cash/webSocket.js ***!
|
|
399
|
+
\****************************************************************************/
|
|
497
400
|
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
498
401
|
|
|
499
402
|
"use strict";
|
|
500
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"
|
|
403
|
+
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-cash/bcmr/../../node_modules/@rpckit/websocket/dist/electrum-cash/webSocket.js?");
|
|
501
404
|
|
|
502
405
|
/***/ }),
|
|
503
406
|
|
|
504
|
-
/***/ "../../node_modules/
|
|
407
|
+
/***/ "../../node_modules/@rpckit/websocket/dist/webSocket.js":
|
|
505
408
|
/*!**************************************************************!*\
|
|
506
|
-
!*** ../../node_modules/
|
|
409
|
+
!*** ../../node_modules/@rpckit/websocket/dist/webSocket.js ***!
|
|
507
410
|
\**************************************************************/
|
|
508
411
|
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
509
412
|
|
|
510
413
|
"use strict";
|
|
511
|
-
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-cash/bcmr/../../node_modules/lossless-json/lib/esm/reviveDate.js?");
|
|
414
|
+
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 if (config.batch !== false) {\n batchScheduler = new _rpckit_core__WEBPACK_IMPORTED_MODULE_0__.BatchScheduler(typeof config.batch === 'object' ? config.batch : {}, 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 for (const handler of entry.listeners)\n handler(notif.params);\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 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 }\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) => () => {\n e.listeners.delete(onData);\n if (e.listeners.size === 0) {\n subscriptions.delete(subKey);\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 };\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 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 = 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-cash/bcmr/../../node_modules/@rpckit/websocket/dist/webSocket.js?");
|
|
512
415
|
|
|
513
416
|
/***/ }),
|
|
514
417
|
|
|
515
|
-
/***/ "../../node_modules/
|
|
516
|
-
|
|
517
|
-
!*** ../../node_modules/
|
|
518
|
-
|
|
418
|
+
/***/ "../../node_modules/isows/_esm/native.js":
|
|
419
|
+
/*!***********************************************!*\
|
|
420
|
+
!*** ../../node_modules/isows/_esm/native.js ***!
|
|
421
|
+
\***********************************************/
|
|
519
422
|
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
520
423
|
|
|
521
424
|
"use strict";
|
|
522
|
-
eval("/*
|
|
523
|
-
|
|
524
|
-
/***/ }),
|
|
525
|
-
|
|
526
|
-
/***/ "../../node_modules/lossless-json/lib/esm/types.js":
|
|
527
|
-
/*!*********************************************************!*\
|
|
528
|
-
!*** ../../node_modules/lossless-json/lib/esm/types.js ***!
|
|
529
|
-
\*********************************************************/
|
|
530
|
-
/***/ (() => {
|
|
531
|
-
|
|
532
|
-
"use strict";
|
|
533
|
-
eval("\n//# sourceMappingURL=types.js.map\n\n//# sourceURL=webpack://@mainnet-cash/bcmr/../../node_modules/lossless-json/lib/esm/types.js?");
|
|
425
|
+
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-cash/bcmr/../../node_modules/isows/_esm/native.js?");
|
|
534
426
|
|
|
535
427
|
/***/ }),
|
|
536
428
|
|
|
537
|
-
/***/ "../../node_modules/
|
|
538
|
-
|
|
539
|
-
!*** ../../node_modules/
|
|
540
|
-
|
|
429
|
+
/***/ "../../node_modules/isows/_esm/utils.js":
|
|
430
|
+
/*!**********************************************!*\
|
|
431
|
+
!*** ../../node_modules/isows/_esm/utils.js ***!
|
|
432
|
+
\**********************************************/
|
|
541
433
|
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
542
434
|
|
|
543
435
|
"use strict";
|
|
544
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"
|
|
436
|
+
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-cash/bcmr/../../node_modules/isows/_esm/utils.js?");
|
|
545
437
|
|
|
546
438
|
/***/ }),
|
|
547
439
|
|
|
@@ -629,7 +521,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
629
521
|
/***/ ((__webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
630
522
|
|
|
631
523
|
"use strict";
|
|
632
|
-
eval("__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"initProvider\": () => (/* binding */ initProvider)\n/* harmony export */ });\n/* unused harmony exports initProviders, disconnectProviders
|
|
524
|
+
eval("__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"initProvider\": () => (/* binding */ initProvider)\n/* harmony export */ });\n/* unused harmony exports initProviders, disconnectProviders */\n/* harmony import */ var _default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./default.js */ \"../mainnet-js/dist/module/network/default.js\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constant.js */ \"../mainnet-js/dist/module/network/constant.js\");\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//# sourceMappingURL=Connection.js.map\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://@mainnet-cash/bcmr/../mainnet-js/dist/module/network/Connection.js?");
|
|
633
525
|
|
|
634
526
|
/***/ }),
|
|
635
527
|
|
|
@@ -640,7 +532,7 @@ eval("__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_de
|
|
|
640
532
|
/***/ ((__webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
641
533
|
|
|
642
534
|
"use strict";
|
|
643
|
-
eval("__webpack_require__.a(__webpack_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 */ \"../mainnet-js/dist/module/interface.js\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/transaction.js */ \"../mainnet-js/dist/module/util/transaction.js\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"../mainnet-js/dist/module/config.js\");\n/* harmony import */ var _util_header_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/header.js */ \"../mainnet-js/dist/module/util/header.js\");\n/* harmony import */ var _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../cache/IndexedDbCache.js */ \"../mainnet-js/dist/module/cache/IndexedDbCache.js\");\n/* harmony import */ var _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../cache/WebStorageCache.js */ \"../mainnet-js/dist/module/cache/WebStorageCache.js\");\n/* harmony import */ var _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../cache/MemoryCache.js */ \"../mainnet-js/dist/module/cache/MemoryCache.js\");\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//# sourceMappingURL=ElectrumNetworkProvider.js.map\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://@mainnet-cash/bcmr/../mainnet-js/dist/module/network/ElectrumNetworkProvider.js?");
|
|
535
|
+
eval("__webpack_require__.a(__webpack_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 */ \"../mainnet-js/dist/module/interface.js\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/transaction.js */ \"../mainnet-js/dist/module/util/transaction.js\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../config.js */ \"../mainnet-js/dist/module/config.js\");\n/* harmony import */ var _util_header_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/header.js */ \"../mainnet-js/dist/module/util/header.js\");\n/* harmony import */ var _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../cache/IndexedDbCache.js */ \"../mainnet-js/dist/module/cache/IndexedDbCache.js\");\n/* harmony import */ var _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../cache/WebStorageCache.js */ \"../mainnet-js/dist/module/cache/WebStorageCache.js\");\n/* harmony import */ var _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../cache/MemoryCache.js */ \"../mainnet-js/dist/module/cache/MemoryCache.js\");\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//# sourceMappingURL=ElectrumNetworkProvider.js.map\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://@mainnet-cash/bcmr/../mainnet-js/dist/module/network/ElectrumNetworkProvider.js?");
|
|
644
536
|
|
|
645
537
|
/***/ }),
|
|
646
538
|
|
|
@@ -651,7 +543,7 @@ eval("__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_de
|
|
|
651
543
|
/***/ ((__webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
652
544
|
|
|
653
545
|
"use strict";
|
|
654
|
-
eval("__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getDefaultServers\": () => (/* binding */ getDefaultServers)
|
|
546
|
+
eval("__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getDefaultServers\": () => (/* binding */ getDefaultServers)\n/* harmony export */ });\n/* unused harmony export DefaultProvider */\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/index.js */ \"../mainnet-js/dist/module/util/getRuntimePlatform.js\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constant.js */ \"../mainnet-js/dist/module/network/constant.js\");\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//# sourceMappingURL=configuration.js.map\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://@mainnet-cash/bcmr/../mainnet-js/dist/module/network/configuration.js?");
|
|
655
547
|
|
|
656
548
|
/***/ }),
|
|
657
549
|
|
|
@@ -662,7 +554,7 @@ eval("__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_de
|
|
|
662
554
|
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
663
555
|
|
|
664
556
|
"use strict";
|
|
665
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"
|
|
557
|
+
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=25\";\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//# sourceMappingURL=constant.js.map\n\n//# sourceURL=webpack://@mainnet-cash/bcmr/../mainnet-js/dist/module/network/constant.js?");
|
|
666
558
|
|
|
667
559
|
/***/ }),
|
|
668
560
|
|
|
@@ -673,18 +565,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
673
565
|
/***/ ((__webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
674
566
|
|
|
675
567
|
"use strict";
|
|
676
|
-
eval("__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"
|
|
677
|
-
|
|
678
|
-
/***/ }),
|
|
679
|
-
|
|
680
|
-
/***/ "../mainnet-js/dist/module/network/util.js":
|
|
681
|
-
/*!*************************************************!*\
|
|
682
|
-
!*** ../mainnet-js/dist/module/network/util.js ***!
|
|
683
|
-
\*************************************************/
|
|
684
|
-
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
685
|
-
|
|
686
|
-
"use strict";
|
|
687
|
-
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//# sourceMappingURL=util.js.map\n\n//# sourceURL=webpack://@mainnet-cash/bcmr/../mainnet-js/dist/module/network/util.js?");
|
|
568
|
+
eval("__webpack_require__.a(__webpack_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 */ \"removeGlobalProvider\": () => (/* binding */ removeGlobalProvider),\n/* harmony export */ \"setGlobalProvider\": () => (/* binding */ setGlobalProvider)\n/* harmony export */ });\n/* unused harmony export getNetworkProvider */\n/* harmony import */ var _ElectrumNetworkProvider_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ElectrumNetworkProvider.js */ \"../mainnet-js/dist/module/network/ElectrumNetworkProvider.js\");\n/* harmony import */ var _configuration_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./configuration.js */ \"../mainnet-js/dist/module/network/configuration.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../interface.js */ \"../mainnet-js/dist/module/interface.js\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constant.js */ \"../mainnet-js/dist/module/network/constant.js\");\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//# sourceMappingURL=default.js.map\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://@mainnet-cash/bcmr/../mainnet-js/dist/module/network/default.js?");
|
|
688
569
|
|
|
689
570
|
/***/ }),
|
|
690
571
|
|