(self["webpackChunkntent_web3"] = self["webpackChunkntent_web3"] || []).push([["vendor"],{ /***/ 1934: /*!************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3/package.json ***! \************************************************************************/ /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"name":"web3","version":"1.6.0","description":"Ethereum JavaScript API","repository":"https://github.com/ethereum/web3.js","license":"LGPL-3.0","engines":{"node":">=8.0.0"},"main":"lib/index.js","bugs":{"url":"https://github.com/ethereum/web3.js/issues"},"keywords":["Ethereum","JavaScript","API"],"author":"ethereum.org","types":"types/index.d.ts","scripts":{"compile":"tsc -b tsconfig.json","dtslint":"dtslint --localTs ../../node_modules/typescript/lib types","postinstall":"echo \\"WARNING: the web3-shh and web3-bzz api will be deprecated in the next version\\""},"authors":[{"name":"Fabian Vogelsteller","email":"fabian@ethereum.org","homepage":"http://frozeman.de"},{"name":"Marek Kotewicz","email":"marek@parity.io","url":"https://github.com/debris"},{"name":"Marian Oancea","url":"https://github.com/cubedro"},{"name":"Gav Wood","email":"g@parity.io","homepage":"http://gavwood.com"},{"name":"Jeffery Wilcke","email":"jeffrey.wilcke@ethereum.org","url":"https://github.com/obscuren"}],"dependencies":{"web3-bzz":"1.6.0","web3-core":"1.6.0","web3-eth":"1.6.0","web3-eth-personal":"1.6.0","web3-net":"1.6.0","web3-shh":"1.6.0","web3-utils":"1.6.0"},"devDependencies":{"@types/node":"^12.12.6","dtslint":"^3.4.1","typescript":"^3.9.5","web3-core-helpers":"1.6.0"},"gitHead":"a34afae56647615d7cbdfa227af8a1389476e2d6"}'); /***/ }), /***/ 82210: /*!***********************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/index.js ***! \***********************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "createAlchemyWeb3": () => (/* binding */ createAlchemyWeb3) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! tslib */ 64762); /* harmony import */ var web3__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! web3 */ 88912); /* harmony import */ var web3__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(web3__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var web3_core_subscriptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! web3-core-subscriptions */ 54923); /* harmony import */ var web3_core_subscriptions__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(web3_core_subscriptions__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var web3_eth_abi__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! web3-eth-abi */ 74241); /* harmony import */ var web3_eth_abi__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(web3_eth_abi__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var web3_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! web3-utils */ 60819); /* harmony import */ var web3_utils__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(web3_utils__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var _util_hex__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./util/hex */ 23164); /* harmony import */ var _util_promises__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./util/promises */ 21857); /* harmony import */ var _web3_adapter_alchemyContext__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./web3-adapter/alchemyContext */ 173); /* harmony import */ var _web3_adapter_customRPC__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./web3-adapter/customRPC */ 55916); /* harmony import */ var _web3_adapter_eth_feeHistory__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./web3-adapter/eth_feeHistory */ 82925); /* harmony import */ var _web3_adapter_eth_maxPriorityFeePerGas__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./web3-adapter/eth_maxPriorityFeePerGas */ 73517); /* provided dependency */ var console = __webpack_require__(/*! console-browserify */ 88883); var DEFAULT_MAX_RETRIES = 3; var DEFAULT_RETRY_INTERVAL = 1000; var DEFAULT_RETRY_JITTER = 250; function createAlchemyWeb3(alchemyUrl, config) { var fullConfig = fillInConfigDefaults(config); var _a = (0,_web3_adapter_alchemyContext__WEBPACK_IMPORTED_MODULE_4__.makeAlchemyContext)(alchemyUrl, fullConfig), provider = _a.provider, jsonRpcSenders = _a.jsonRpcSenders, restSender = _a.restSender, setWriteProvider = _a.setWriteProvider; var alchemyWeb3 = new (web3__WEBPACK_IMPORTED_MODULE_0___default())(provider); alchemyWeb3.setProvider = function () { throw new Error("setProvider is not supported in Alchemy Web3. To change the provider used for writes, use setWriteProvider() instead."); }; alchemyWeb3.setWriteProvider = setWriteProvider; alchemyWeb3.alchemy = { getTokenAllowance: function (params, callback) { return callAlchemyJsonRpcMethod({ jsonRpcSenders: jsonRpcSenders, callback: callback, method: "alchemy_getTokenAllowance", params: [params], }); }, getTokenBalances: function (address, contractAddresses, callback) { return callAlchemyJsonRpcMethod({ jsonRpcSenders: jsonRpcSenders, callback: callback, method: "alchemy_getTokenBalances", params: [address, contractAddresses], processResponse: processTokenBalanceResponse, }); }, getTokenMetadata: function (address, callback) { return callAlchemyJsonRpcMethod({ jsonRpcSenders: jsonRpcSenders, callback: callback, params: [address], method: "alchemy_getTokenMetadata", }); }, getAssetTransfers: function (params, callback) { return callAlchemyJsonRpcMethod({ jsonRpcSenders: jsonRpcSenders, callback: callback, params: [ (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_5__.__assign)({}, params), { fromBlock: params.fromBlock != null ? (0,_util_hex__WEBPACK_IMPORTED_MODULE_6__.formatBlock)(params.fromBlock) : undefined, toBlock: params.toBlock != null ? (0,_util_hex__WEBPACK_IMPORTED_MODULE_6__.formatBlock)(params.toBlock) : undefined, maxCount: params.maxCount != null ? (0,web3_utils__WEBPACK_IMPORTED_MODULE_3__.toHex)(params.maxCount) : undefined }), ], method: "alchemy_getAssetTransfers", }); }, getNftMetadata: function (params, callback) { return callAlchemyRestEndpoint({ restSender: restSender, callback: callback, params: params, path: "/v1/getNFTMetadata/", }); }, getNfts: function (params, callback) { return callAlchemyRestEndpoint({ restSender: restSender, callback: callback, params: params, path: "/v1/getNFTs/", }); }, }; patchSubscriptions(alchemyWeb3); (0,_web3_adapter_customRPC__WEBPACK_IMPORTED_MODULE_7__.patchEnableCustomRPC)(alchemyWeb3); (0,_web3_adapter_eth_feeHistory__WEBPACK_IMPORTED_MODULE_8__.patchEthFeeHistoryMethod)(alchemyWeb3); (0,_web3_adapter_eth_maxPriorityFeePerGas__WEBPACK_IMPORTED_MODULE_9__.patchEthMaxPriorityFeePerGasMethod)(alchemyWeb3); return alchemyWeb3; } function fillInConfigDefaults(_a) { var _b = _a === void 0 ? {} : _a, _c = _b.writeProvider, writeProvider = _c === void 0 ? getWindowProvider() : _c, _d = _b.maxRetries, maxRetries = _d === void 0 ? DEFAULT_MAX_RETRIES : _d, _e = _b.retryInterval, retryInterval = _e === void 0 ? DEFAULT_RETRY_INTERVAL : _e, _f = _b.retryJitter, retryJitter = _f === void 0 ? DEFAULT_RETRY_JITTER : _f; return { writeProvider: writeProvider, maxRetries: maxRetries, retryInterval: retryInterval, retryJitter: retryJitter }; } function getWindowProvider() { return typeof window !== "undefined" ? window.ethereum : null; } function callAlchemyJsonRpcMethod(_a) { var _this = this; var jsonRpcSenders = _a.jsonRpcSenders, method = _a.method, params = _a.params, _b = _a.callback, callback = _b === void 0 ? noop : _b, _c = _a.processResponse, processResponse = _c === void 0 ? identity : _c; var promise = (function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(_this, void 0, void 0, function () { var result; return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, jsonRpcSenders.send(method, params)]; case 1: result = _a.sent(); return [2 /*return*/, processResponse(result)]; } }); }); })(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_10__.callWhenDone)(promise, callback); return promise; } function callAlchemyRestEndpoint(_a) { var _this = this; var restSender = _a.restSender, path = _a.path, params = _a.params, _b = _a.callback, callback = _b === void 0 ? noop : _b, _c = _a.processResponse, processResponse = _c === void 0 ? identity : _c; var promise = (function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(_this, void 0, void 0, function () { var result; return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, restSender.sendRestPayload(path, params)]; case 1: result = _a.sent(); return [2 /*return*/, processResponse(result)]; } }); }); })(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_10__.callWhenDone)(promise, callback); return promise; } function processTokenBalanceResponse(rawResponse) { // Convert token balance fields from hex-string to decimal-string. var fixedTokenBalances = rawResponse.tokenBalances.map(function (balance) { return balance.tokenBalance != null ? (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_5__.__assign)({}, balance), { tokenBalance: (0,web3_eth_abi__WEBPACK_IMPORTED_MODULE_2__.decodeParameter)("uint256", balance.tokenBalance) }) : balance; }); return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_5__.__assign)({}, rawResponse), { tokenBalances: fixedTokenBalances }); } /** * Updates Web3's internal subscription architecture to also handle Alchemy * specific subscriptions. */ function patchSubscriptions(web3) { var eth = web3.eth; var oldSubscribe = eth.subscribe.bind(eth); eth.subscribe = (function (type) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } if (type === "alchemy_fullPendingTransactions" || type === "alchemy_newFullPendingTransactions") { return suppressNoSubscriptionExistsWarning(function () { return oldSubscribe.apply(void 0, (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__spreadArray)(["alchemy_newFullPendingTransactions"], (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__read)(rest))); }); } if (type === "alchemy_filteredNewFullPendingTransactions" || type === "alchemy_filteredPendingTransactions" || type === "alchemy_filteredFullPendingTransactions") { return suppressNoSubscriptionExistsWarning(function () { return oldSubscribe.apply(void 0, (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__spreadArray)(["alchemy_filteredNewFullPendingTransactions"], (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__read)(rest))); }); } return oldSubscribe.apply(void 0, (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__spreadArray)([type], (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__read)(rest))); }); } /** * VERY hacky wrapper to suppress a spurious warning when subscribing to an * Alchemy subscription that isn't built into Web3. */ function suppressNoSubscriptionExistsWarning(f) { var oldConsoleWarn = console.warn; console.warn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (typeof args[0] === "string" && args[0].includes(" doesn't exist. Subscribing anyway.")) { return; } return oldConsoleWarn.apply(console, args); }; try { return f(); } finally { console.warn = oldConsoleWarn; } } /** * Another VERY hacky monkeypatch to make sure that we can take extra parameters to certain alchemy subscriptions * I hate doing this, but the other option is to fork web3-core and I think for now this is better */ var subscription = (web3_core_subscriptions__WEBPACK_IMPORTED_MODULE_1___default().subscription); var oldSubscriptionPrototypeValidateArgs = subscription.prototype._validateArgs; subscription.prototype._validateArgs = function (args) { if ([ "alchemy_filteredNewFullPendingTransactions", "alchemy_filteredPendingTransactions", "alchemy_filteredFullPendingTransactions", ].includes(this.subscriptionMethod)) { // This particular subscription type is allowed to have additional parameters } else { if ([ "alchemy_fullPendingTransactions", "alchemy_newFullPendingTransactions", ].includes(this.subscriptionMethod)) { if (this.options.subscription) { this.options.subscription.subscriptionName = this.subscriptionMethod; } } var validator = oldSubscriptionPrototypeValidateArgs.bind(this); validator(args); } }; function noop() { // Nothing. } function identity(x) { return x; } //# sourceMappingURL=index.js.map /***/ }), /***/ 19397: /*!****************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/subscriptions/subscriptionBackfill.js ***! \****************************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "makeBackfiller": () => (/* binding */ makeBackfiller), /* harmony export */ "dedupeNewHeads": () => (/* binding */ dedupeNewHeads), /* harmony export */ "dedupeLogs": () => (/* binding */ dedupeLogs) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ 64762); /* harmony import */ var _util_hex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/hex */ 23164); /* harmony import */ var _util_promises__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/promises */ 21857); /** * The maximum number of blocks to backfill. If more than this many blocks have * been missed, then we'll sadly miss data, but we want to make sure we don't * end up requesting thousands of blocks if somebody left their laptop closed * for a week. */ var MAX_BACKFILL_BLOCKS = 120; function makeBackfiller(jsonRpcSenders) { return { getNewHeadsBackfill: getNewHeadsBackfill, getLogsBackfill: getLogsBackfill }; function getNewHeadsBackfill(isCancelled, previousHeads, fromBlockNumber) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var toBlockNumber, lastSeenBlockNumber, minBlockNumber, reorgHeads, intermediateHeads; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.throwIfCancelled)(isCancelled); return [4 /*yield*/, getBlockNumber()]; case 1: toBlockNumber = _a.sent(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.throwIfCancelled)(isCancelled); if (previousHeads.length === 0) { return [2 /*return*/, getHeadEventsInRange(Math.max(fromBlockNumber, toBlockNumber - MAX_BACKFILL_BLOCKS) + 1, toBlockNumber + 1)]; } lastSeenBlockNumber = (0,_util_hex__WEBPACK_IMPORTED_MODULE_2__.fromHex)(previousHeads[previousHeads.length - 1].number); minBlockNumber = Math.max(0, lastSeenBlockNumber - MAX_BACKFILL_BLOCKS); if (lastSeenBlockNumber < minBlockNumber) { return [2 /*return*/, getHeadEventsInRange(minBlockNumber, toBlockNumber + 1)]; } return [4 /*yield*/, getReorgHeads(isCancelled, previousHeads)]; case 2: reorgHeads = _a.sent(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.throwIfCancelled)(isCancelled); return [4 /*yield*/, getHeadEventsInRange(lastSeenBlockNumber + 1, toBlockNumber + 1)]; case 3: intermediateHeads = _a.sent(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.throwIfCancelled)(isCancelled); return [2 /*return*/, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(reorgHeads)), (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(intermediateHeads))]; } }); }); } function getReorgHeads(isCancelled, previousHeads) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var result, i, oldEvent, blockHead; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: result = []; i = previousHeads.length - 1; _a.label = 1; case 1: if (!(i >= 0)) return [3 /*break*/, 4]; oldEvent = previousHeads[i]; return [4 /*yield*/, getBlockByNumber((0,_util_hex__WEBPACK_IMPORTED_MODULE_2__.fromHex)(oldEvent.number))]; case 2: blockHead = _a.sent(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.throwIfCancelled)(isCancelled); if (oldEvent.hash === blockHead.hash) { return [3 /*break*/, 4]; } result.push(toNewHeadsEvent(blockHead)); _a.label = 3; case 3: i--; return [3 /*break*/, 1]; case 4: return [2 /*return*/, result.reverse()]; } }); }); } function getHeadEventsInRange(fromBlockInclusive, toBlockExclusive) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var batchParts, i, heads; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: if (fromBlockInclusive >= toBlockExclusive) { return [2 /*return*/, []]; } batchParts = []; for (i = fromBlockInclusive; i < toBlockExclusive; i++) { batchParts.push({ method: "eth_getBlockByNumber", params: [(0,_util_hex__WEBPACK_IMPORTED_MODULE_2__.toHex)(i), false], }); } return [4 /*yield*/, jsonRpcSenders.sendBatch(batchParts)]; case 1: heads = _a.sent(); return [2 /*return*/, heads.map(toNewHeadsEvent)]; } }); }); } function getBlockByNumber(blockNumber) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { return [2 /*return*/, jsonRpcSenders.send("eth_getBlockByNumber", [ (0,_util_hex__WEBPACK_IMPORTED_MODULE_2__.toHex)(blockNumber), false, ])]; }); }); } function getLogsBackfill(isCancelled, filter, previousLogs, fromBlockNumber) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var toBlockNumber, lastSeenBlockNumber, minBlockNumber, commonAncestorNumber, removedLogs, addedLogs; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.throwIfCancelled)(isCancelled); return [4 /*yield*/, getBlockNumber()]; case 1: toBlockNumber = _a.sent(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.throwIfCancelled)(isCancelled); if (previousLogs.length === 0) { return [2 /*return*/, getLogsInRange(filter, Math.max(fromBlockNumber, toBlockNumber - MAX_BACKFILL_BLOCKS) + 1, toBlockNumber + 1)]; } lastSeenBlockNumber = (0,_util_hex__WEBPACK_IMPORTED_MODULE_2__.fromHex)(previousLogs[previousLogs.length - 1].blockNumber); minBlockNumber = Math.max(0, lastSeenBlockNumber - MAX_BACKFILL_BLOCKS); if (lastSeenBlockNumber < minBlockNumber) { return [2 /*return*/, getLogsInRange(filter, minBlockNumber, toBlockNumber + 1)]; } return [4 /*yield*/, getCommonAncestorNumber(isCancelled, previousLogs)]; case 2: commonAncestorNumber = _a.sent(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.throwIfCancelled)(isCancelled); removedLogs = previousLogs .filter(function (log) { return (0,_util_hex__WEBPACK_IMPORTED_MODULE_2__.fromHex)(log.blockNumber) > commonAncestorNumber; }) .map(function (log) { return ((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, log), { removed: true })); }); return [4 /*yield*/, getLogsInRange(filter, commonAncestorNumber + 1, toBlockNumber + 1)]; case 3: addedLogs = _a.sent(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.throwIfCancelled)(isCancelled); return [2 /*return*/, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(removedLogs)), (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(addedLogs))]; } }); }); } function getCommonAncestorNumber(isCancelled, previousLogs) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var i, _a, blockHash, blockNumber, hash; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_b) { switch (_b.label) { case 0: i = previousLogs.length - 1; _b.label = 1; case 1: if (!(i >= 0)) return [3 /*break*/, 4]; _a = previousLogs[i], blockHash = _a.blockHash, blockNumber = _a.blockNumber; return [4 /*yield*/, getBlockByNumber((0,_util_hex__WEBPACK_IMPORTED_MODULE_2__.fromHex)(blockNumber))]; case 2: hash = (_b.sent()).hash; (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.throwIfCancelled)(isCancelled); if (blockHash === hash) { return [2 /*return*/, (0,_util_hex__WEBPACK_IMPORTED_MODULE_2__.fromHex)(blockNumber)]; } _b.label = 3; case 3: i--; return [3 /*break*/, 1]; case 4: return [2 /*return*/, Number.NEGATIVE_INFINITY]; } }); }); } function getLogsInRange(filter, fromBlockInclusive, toBlockExclusive) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var rangeFilter; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { if (fromBlockInclusive >= toBlockExclusive) { return [2 /*return*/, []]; } rangeFilter = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, filter), { fromBlock: (0,_util_hex__WEBPACK_IMPORTED_MODULE_2__.toHex)(fromBlockInclusive), toBlock: (0,_util_hex__WEBPACK_IMPORTED_MODULE_2__.toHex)(toBlockExclusive - 1) }); return [2 /*return*/, jsonRpcSenders.send("eth_getLogs", [rangeFilter])]; }); }); } function getBlockNumber() { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var blockNumberHex; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, jsonRpcSenders.send("eth_blockNumber")]; case 1: blockNumberHex = _a.sent(); return [2 /*return*/, (0,_util_hex__WEBPACK_IMPORTED_MODULE_2__.fromHex)(blockNumberHex)]; } }); }); } } function toNewHeadsEvent(head) { var result = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, head); delete result.totalDifficulty; delete result.transactions; delete result.uncles; return result; } function dedupeNewHeads(events) { return dedupe(events, function (event) { return event.hash; }); } function dedupeLogs(events) { return dedupe(events, function (event) { return event.blockHash + "/" + event.logIndex; }); } function dedupe(items, getKey) { var keysSeen = new Set(); var result = []; items.forEach(function (item) { var key = getKey(item); if (!keysSeen.has(key)) { keysSeen.add(key); result.push(item); } }); return result; } //# sourceMappingURL=subscriptionBackfill.js.map /***/ }), /***/ 51348: /*!***********************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/types.js ***! \***********************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "isResponse": () => (/* binding */ isResponse), /* harmony export */ "isSubscriptionEvent": () => (/* binding */ isSubscriptionEvent) /* harmony export */ }); // The JSON-RPC types in Web3 definitions aren't quite right. Use these instead. function isResponse(message) { return (Array.isArray(message) || (message.jsonrpc === "2.0" && message.id !== undefined)); } function isSubscriptionEvent(message) { return !isResponse(message); } //# sourceMappingURL=types.js.map /***/ }), /***/ 23164: /*!**************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/util/hex.js ***! \**************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "toHex": () => (/* binding */ toHex), /* harmony export */ "fromHex": () => (/* binding */ fromHex), /* harmony export */ "formatBlock": () => (/* binding */ formatBlock) /* harmony export */ }); function toHex(n) { return "0x" + n.toString(16); } function fromHex(hexString) { return Number.parseInt(hexString, 16); } function formatBlock(block) { if (typeof block === "string") { return block; } else if (typeof block === "number" && Number.isInteger(block)) { return toHex(block); } return block.toString(); } //# sourceMappingURL=hex.js.map /***/ }), /***/ 49885: /*!******************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/util/jsonRpc.js ***! \******************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "makeJsonRpcPayloadFactory": () => (/* binding */ makeJsonRpcPayloadFactory), /* harmony export */ "makeJsonRpcSenders": () => (/* binding */ makeJsonRpcSenders), /* harmony export */ "makeResponse": () => (/* binding */ makeResponse) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ 64762); function makeJsonRpcPayloadFactory() { var nextId = 0; return function (method, params) { return ({ method: method, params: params, jsonrpc: "2.0", id: "alc-web3:" + nextId++, }); }; } function makeJsonRpcSenders(sendJsonRpcPayload, makeJsonRpcPayload) { var _this = this; var send = function (method, params) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(_this, void 0, void 0, function () { var response; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, sendJsonRpcPayload(makeJsonRpcPayload(method, params))]; case 1: response = _a.sent(); if (response.error) { throw new Error(response.error.message); } return [2 /*return*/, response.result]; } }); }); }; function sendBatch(parts) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var payload, response, message, errorResponse; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: payload = parts.map(function (_a) { var method = _a.method, params = _a.params; return makeJsonRpcPayload(method, params); }); return [4 /*yield*/, sendJsonRpcPayload(payload)]; case 1: response = _a.sent(); if (!Array.isArray(response)) { message = response.error ? response.error.message : "Batch request failed"; throw new Error(message); } errorResponse = response.find(function (r) { return !!r.error; }); if (errorResponse) { throw new Error(errorResponse.error.message); } // The ids are ascending numbers because that's what Payload Factories do. return [2 /*return*/, response .sort(function (r1, r2) { return r1.id - r2.id; }) .map(function (r) { return r.result; })]; } }); }); } return { send: send, sendBatch: sendBatch }; } function makeResponse(id, result) { return { jsonrpc: "2.0", id: id, result: result }; } //# sourceMappingURL=jsonRpc.js.map /***/ }), /***/ 21857: /*!*******************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/util/promises.js ***! \*******************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "promisify": () => (/* binding */ promisify), /* harmony export */ "callWhenDone": () => (/* binding */ callWhenDone), /* harmony export */ "delay": () => (/* binding */ delay), /* harmony export */ "withTimeout": () => (/* binding */ withTimeout), /* harmony export */ "withBackoffRetries": () => (/* binding */ withBackoffRetries), /* harmony export */ "makeCancelToken": () => (/* binding */ makeCancelToken), /* harmony export */ "throwIfCancelled": () => (/* binding */ throwIfCancelled), /* harmony export */ "CANCELLED": () => (/* binding */ CANCELLED) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ 64762); /** * Helper for converting functions which take a callback as their final argument * to functions which return a promise. */ function promisify(f) { return new Promise(function (resolve, reject) { return f(function (error, result) { if (error != null) { reject(error); } else { resolve(result); } }); }); } /** * Helper for converting functions which return a promise to functions which * take a callback as their final argument. */ function callWhenDone(promise, callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } function delay(ms) { return new Promise(function (resolve) { return setTimeout(resolve, ms); }); } function withTimeout(promise, ms) { return Promise.race([ promise, new Promise(function (_, reject) { return setTimeout(function () { return reject(new Error("Timeout")); }, ms); }), ]); } var MIN_RETRY_DELAY = 1000; var RETRY_BACKOFF_FACTOR = 2; var MAX_RETRY_DELAY = 30000; function withBackoffRetries(f, retryCount, shouldRetry) { if (shouldRetry === void 0) { shouldRetry = function () { return true; }; } return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var nextWaitTime, i, error_1; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: nextWaitTime = 0; i = 0; _a.label = 1; case 1: if (false) {} _a.label = 2; case 2: _a.trys.push([2, 4, , 6]); return [4 /*yield*/, f()]; case 3: return [2 /*return*/, _a.sent()]; case 4: error_1 = _a.sent(); i++; if (i >= retryCount || !shouldRetry(error_1)) { throw error_1; } return [4 /*yield*/, delay(nextWaitTime)]; case 5: _a.sent(); if (!shouldRetry(error_1)) { throw error_1; } nextWaitTime = nextWaitTime === 0 ? MIN_RETRY_DELAY : Math.min(MAX_RETRY_DELAY, RETRY_BACKOFF_FACTOR * nextWaitTime); return [3 /*break*/, 6]; case 6: return [3 /*break*/, 1]; case 7: return [2 /*return*/]; } }); }); } function makeCancelToken() { var cancelled = false; return { cancel: function () { return (cancelled = true); }, isCancelled: function () { return cancelled; } }; } function throwIfCancelled(isCancelled) { if (isCancelled()) { throw CANCELLED; } } var CANCELLED = new Error("Cancelled"); //# sourceMappingURL=promises.js.map /***/ }), /***/ 83811: /*!*************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/version.js ***! \*************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "VERSION": () => (/* binding */ VERSION) /* harmony export */ }); // This file is autogenerated by injectVersion.js. Any changes will be // overwritten on commit! var VERSION = "1.1.10"; //# sourceMappingURL=version.js.map /***/ }), /***/ 173: /*!*********************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/web3-adapter/alchemyContext.js ***! \*********************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "makeAlchemyContext": () => (/* binding */ makeAlchemyContext) /* harmony export */ }); /* harmony import */ var sturdy_websocket__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sturdy-websocket */ 36574); /* harmony import */ var websocket__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! websocket */ 66033); /* harmony import */ var websocket__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(websocket__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _util_jsonRpc__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/jsonRpc */ 49885); /* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../version */ 83811); /* harmony import */ var _alchemySendHttp__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./alchemySendHttp */ 20224); /* harmony import */ var _alchemySendWebSocket__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./alchemySendWebSocket */ 25260); /* harmony import */ var _httpProvider__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./httpProvider */ 13817); /* harmony import */ var _sendJsonRpcPayload__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./sendJsonRpcPayload */ 9022); /* harmony import */ var _sendRestPayload__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./sendRestPayload */ 97635); /* harmony import */ var _webSocketProvider__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./webSocketProvider */ 91863); /* provided dependency */ var process = __webpack_require__(/*! process/browser.js */ 29849); var NODE_MAX_WS_FRAME_SIZE = 100 * 1024 * 1024; // 100 MB function makeAlchemyContext(url, config) { var makeJsonRpcPayload = (0,_util_jsonRpc__WEBPACK_IMPORTED_MODULE_2__.makeJsonRpcPayloadFactory)(); var restSender = (0,_sendRestPayload__WEBPACK_IMPORTED_MODULE_3__.makeRestPayloadSender)({ config: config, url: url, }); if (/^https?:\/\//.test(url)) { var alchemySendJsonrRpc = (0,_alchemySendHttp__WEBPACK_IMPORTED_MODULE_4__.makeJsonRpcHttpSender)(url); var _a = (0,_sendJsonRpcPayload__WEBPACK_IMPORTED_MODULE_5__.makeJsonRpcPayloadSender)(alchemySendJsonrRpc, config), sendJsonRpcPayload = _a.sendJsonRpcPayload, setWriteProvider = _a.setWriteProvider; var jsonRpcSenders = (0,_util_jsonRpc__WEBPACK_IMPORTED_MODULE_2__.makeJsonRpcSenders)(sendJsonRpcPayload, makeJsonRpcPayload); var provider = (0,_httpProvider__WEBPACK_IMPORTED_MODULE_6__.makeAlchemyHttpProvider)(sendJsonRpcPayload); return { provider: provider, jsonRpcSenders: jsonRpcSenders, restSender: restSender, setWriteProvider: setWriteProvider }; } else if (/^wss?:\/\//.test(url)) { var protocol = isAlchemyUrl(url) ? "alchemy-web3-" + _version__WEBPACK_IMPORTED_MODULE_7__.VERSION : undefined; var ws = new sturdy_websocket__WEBPACK_IMPORTED_MODULE_0__.default(url, protocol, { wsConstructor: getWebSocketConstructor(), }); var alchemySend = (0,_alchemySendWebSocket__WEBPACK_IMPORTED_MODULE_8__.makeWebSocketSender)(ws); var _b = (0,_sendJsonRpcPayload__WEBPACK_IMPORTED_MODULE_5__.makeJsonRpcPayloadSender)(alchemySend, config), sendJsonRpcPayload = _b.sendJsonRpcPayload, setWriteProvider = _b.setWriteProvider; var jsonRpcSenders = (0,_util_jsonRpc__WEBPACK_IMPORTED_MODULE_2__.makeJsonRpcSenders)(sendJsonRpcPayload, makeJsonRpcPayload); var provider = new _webSocketProvider__WEBPACK_IMPORTED_MODULE_9__.AlchemyWebSocketProvider(ws, sendJsonRpcPayload, jsonRpcSenders); return { provider: provider, jsonRpcSenders: jsonRpcSenders, restSender: restSender, setWriteProvider: setWriteProvider }; } else { throw new Error("Alchemy URL protocol must be one of http, https, ws, or wss. Recieved: " + url); } } function getWebSocketConstructor() { return isNodeEnvironment() ? function (url, protocols) { return new websocket__WEBPACK_IMPORTED_MODULE_1__.w3cwebsocket(url, protocols, undefined, undefined, undefined, { maxReceivedMessageSize: NODE_MAX_WS_FRAME_SIZE, maxReceivedFrameSize: NODE_MAX_WS_FRAME_SIZE, }); } : WebSocket; } function isNodeEnvironment() { return (typeof process !== "undefined" && process != null && process.versions != null && process.versions.node != null); } function isAlchemyUrl(url) { return url.indexOf("alchemyapi.io") >= 0; } //# sourceMappingURL=alchemyContext.js.map /***/ }), /***/ 20224: /*!**********************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/web3-adapter/alchemySendHttp.js ***! \**********************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "makeJsonRpcHttpSender": () => (/* binding */ makeJsonRpcHttpSender) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tslib */ 64762); /* harmony import */ var fetch_ponyfill__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fetch-ponyfill */ 2094); /* harmony import */ var fetch_ponyfill__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fetch_ponyfill__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../version */ 83811); var _a = fetch_ponyfill__WEBPACK_IMPORTED_MODULE_0___default()(), fetch = _a.fetch, Headers = _a.Headers; var ALCHEMY_HEADERS = new Headers({ Accept: "application/json", "Content-Type": "application/json", "Alchemy-Web3-Version": _version__WEBPACK_IMPORTED_MODULE_1__.VERSION, }); var RATE_LIMIT_STATUS = 429; function makeJsonRpcHttpSender(url) { var _this = this; return function (request) { return (0,tslib__WEBPACK_IMPORTED_MODULE_2__.__awaiter)(_this, void 0, void 0, function () { var response, status, _a; var _b, _c; return (0,tslib__WEBPACK_IMPORTED_MODULE_2__.__generator)(this, function (_d) { switch (_d.label) { case 0: return [4 /*yield*/, fetch(url, { method: "POST", headers: ALCHEMY_HEADERS, body: JSON.stringify(request), })]; case 1: response = _d.sent(); status = response.status; _a = status; switch (_a) { case 200: return [3 /*break*/, 2]; case RATE_LIMIT_STATUS: return [3 /*break*/, 4]; case 0: return [3 /*break*/, 5]; } return [3 /*break*/, 6]; case 2: _b = { type: "jsonrpc" }; return [4 /*yield*/, response.json()]; case 3: return [2 /*return*/, (_b.response = _d.sent(), _b)]; case 4: return [2 /*return*/, { type: "rateLimit" }]; case 5: return [2 /*return*/, { type: "networkError", status: 0, message: "Connection failed.", }]; case 6: _c = { status: status, type: "networkError" }; return [4 /*yield*/, response.json()]; case 7: return [2 /*return*/, (_c.message = (_d.sent()).message, _c)]; } }); }); }; } //# sourceMappingURL=alchemySendHttp.js.map /***/ }), /***/ 25260: /*!***************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/web3-adapter/alchemySendWebSocket.js ***! \***************************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "makeWebSocketSender": () => (/* binding */ makeWebSocketSender) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! tslib */ 64762); /* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types */ 51348); /* provided dependency */ var console = __webpack_require__(/*! console-browserify */ 88883); function makeWebSocketSender(ws) { var contextsById = new Map(); ws.addEventListener("message", function (message) { var response = JSON.parse(message.data); if (!(0,_types__WEBPACK_IMPORTED_MODULE_0__.isResponse)(response)) { return; } var id = getIdFromResponse(response); if (id === undefined) { return; } var context = contextsById.get(id); if (!context) { return; } var resolve = context.resolve; contextsById.delete(id); if (!Array.isArray(response) && response.error && response.error.code === 429) { resolve({ type: "rateLimit" }); } else { resolve({ response: response, type: "jsonrpc" }); } }); ws.addEventListener("down", function () { (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__read)(contextsById)).forEach(function (_a) { var _b = (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__read)(_a, 2), id = _b[0], _c = _b[1], request = _c.request, resolve = _c.resolve; if (isWrite(request)) { // Writes cannot be resent because they will fail for a duplicate nonce. contextsById.delete(id); resolve({ type: "networkError", status: 0, message: "WebSocket closed before receiving a response for write request with id: " + id + ".", }); } }); }); ws.addEventListener("reopen", function () { var e_1, _a; try { for (var _b = (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__values)(contextsById.values()), _c = _b.next(); !_c.done; _c = _b.next()) { var request = _c.value.request; ws.send(JSON.stringify(request)); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } }); return function (request) { return new Promise(function (resolve) { var id = getIdFromRequest(request); if (id !== undefined) { var existingContext = contextsById.get(id); if (existingContext) { var message = "Another WebSocket request was made with the same id (" + id + ") before a response was received."; console.error(message); existingContext.resolve({ message: message, type: "networkError", status: 0, }); } contextsById.set(id, { request: request, resolve: resolve }); } ws.send(JSON.stringify(request)); }); }; } function getIdFromRequest(request) { if (!Array.isArray(request)) { return request.id; } return getCanonicalIdFromList(request.map(function (p) { return p.id; })); } function getIdFromResponse(response) { if (!Array.isArray(response)) { return response.id; } return getCanonicalIdFromList(response.map(function (p) { return p.id; })); } /** * Since the JSON-RPC spec allows responses to be returned in a different order * than sent, we need a mechanism for choosing a canonical id from a list that * doesn't depend on the order. This chooses the "minimum" id by an arbitrary * ordering: the smallest string if possible, otherwise the smallest number, * otherwise null. */ function getCanonicalIdFromList(ids) { var stringIds = ids.filter(function (id) { return typeof id === "string"; }); if (stringIds.length > 0) { return stringIds.reduce(function (bestId, id) { return (bestId < id ? bestId : id); }); } var numberIds = ids.filter(function (id) { return typeof id === "number"; }); if (numberIds.length > 0) { return Math.min.apply(Math, (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__read)(numberIds))); } return ids.indexOf(null) >= 0 ? null : undefined; } function isWrite(request) { return Array.isArray(request) ? request.every(isSingleWrite) : isSingleWrite(request); } var WRITE_METHODS = ["eth_sendTransaction", "eth_sendRawTransaction"]; function isSingleWrite(request) { return WRITE_METHODS.includes(request.method); } //# sourceMappingURL=alchemySendWebSocket.js.map /***/ }), /***/ 55916: /*!****************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/web3-adapter/customRPC.js ***! \****************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "patchEnableCustomRPC": () => (/* binding */ patchEnableCustomRPC) /* harmony export */ }); /* harmony import */ var web3_core_method__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! web3-core-method */ 50202); /* harmony import */ var web3_core_method__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(web3_core_method__WEBPACK_IMPORTED_MODULE_0__); var MethodFn = (web3_core_method__WEBPACK_IMPORTED_MODULE_0___default()); function patchEnableCustomRPC(web3) { web3.eth.customRPC = function (opts) { var newMethod = new MethodFn({ name: opts.name, call: opts.call, params: opts.params || 0, inputFormatter: opts.inputFormatter || null, outputFormatter: opts.outputFormatter || null, }); newMethod.attachToObject(this); newMethod.setRequestManager(this._requestManager, this.accounts); }; } //# sourceMappingURL=customRPC.js.map /***/ }), /***/ 82925: /*!*********************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/web3-adapter/eth_feeHistory.js ***! \*********************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "patchEthFeeHistoryMethod": () => (/* binding */ patchEthFeeHistoryMethod) /* harmony export */ }); /* harmony import */ var web3_core_helpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! web3-core-helpers */ 20176); /* harmony import */ var web3_core_helpers__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(web3_core_helpers__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var web3_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! web3-utils */ 60819); /* harmony import */ var web3_utils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(web3_utils__WEBPACK_IMPORTED_MODULE_1__); function patchEthFeeHistoryMethod(web3) { web3.eth.customRPC({ name: "getFeeHistory", call: "eth_feeHistory", params: 3, inputFormatter: [ web3_utils__WEBPACK_IMPORTED_MODULE_1__.toNumber, web3_core_helpers__WEBPACK_IMPORTED_MODULE_0__.formatters.inputBlockNumberFormatter, function (value) { return value; }, ], }); } //# sourceMappingURL=eth_feeHistory.js.map /***/ }), /***/ 73517: /*!*******************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/web3-adapter/eth_maxPriorityFeePerGas.js ***! \*******************************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "patchEthMaxPriorityFeePerGasMethod": () => (/* binding */ patchEthMaxPriorityFeePerGasMethod) /* harmony export */ }); function patchEthMaxPriorityFeePerGasMethod(web3) { web3.eth.customRPC({ name: "getMaxPriorityFeePerGas", call: "eth_maxPriorityFeePerGas", params: 0, }); } //# sourceMappingURL=eth_maxPriorityFeePerGas.js.map /***/ }), /***/ 13817: /*!*******************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/web3-adapter/httpProvider.js ***! \*******************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "makeAlchemyHttpProvider": () => (/* binding */ makeAlchemyHttpProvider) /* harmony export */ }); /* harmony import */ var _util_promises__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/promises */ 21857); /** * Returns a "provider" which can be passed to the Web3 constructor. */ function makeAlchemyHttpProvider(sendJsonRpcPayload) { function send(payload, callback) { (0,_util_promises__WEBPACK_IMPORTED_MODULE_0__.callWhenDone)(sendJsonRpcPayload(payload), callback); } return { send: send }; } //# sourceMappingURL=httpProvider.js.map /***/ }), /***/ 9022: /*!*************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/web3-adapter/sendJsonRpcPayload.js ***! \*************************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "makeJsonRpcPayloadSender": () => (/* binding */ makeJsonRpcPayloadSender) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tslib */ 64762); /* harmony import */ var assert_never__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! assert-never */ 44477); /* harmony import */ var _util_promises__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/promises */ 21857); var ALCHEMY_DISALLOWED_METHODS = [ "eth_accounts", "eth_sendTransaction", "eth_sign", "eth_signTypedData_v3", "eth_signTypedData", "personal_sign", ]; function makeJsonRpcPayloadSender(alchemySendJsonRpc, config) { var currentWriteProvider = config.writeProvider; var sendJsonRpcPayload = function (payload) { var disallowedMethod = getDisallowedMethod(payload); if (!disallowedMethod) { try { return sendJsonRpcWithRetries(payload, alchemySendJsonRpc, config); } catch (alchemyError) { // Fallback to write provider, but if both fail throw the error from // Alchemy. if (!currentWriteProvider) { throw alchemyError; } try { return sendJsonRpcWithProvider(currentWriteProvider, payload); } catch (_a) { throw alchemyError; } } } else { if (!currentWriteProvider) { throw new Error("No provider available for method \"" + disallowedMethod + "\""); } return sendJsonRpcWithProvider(currentWriteProvider, payload); } }; function setWriteProvider(writeProvider) { currentWriteProvider = writeProvider !== null && writeProvider !== void 0 ? writeProvider : null; } return { sendJsonRpcPayload: sendJsonRpcPayload, setWriteProvider: setWriteProvider, }; } function sendJsonRpcWithProvider(provider, payload) { var anyProvider = provider; var sendMethod = (anyProvider.sendAsync ? anyProvider.sendAsync : anyProvider.send).bind(anyProvider); return (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.promisify)(function (callback) { return sendMethod(payload, callback); }); } function getDisallowedMethod(payload) { var payloads = Array.isArray(payload) ? payload : [payload]; var disallowedRequest = payloads.find(function (p) { return ALCHEMY_DISALLOWED_METHODS.indexOf(p.method) >= 0; }) || undefined; return disallowedRequest && disallowedRequest.method; } function sendJsonRpcWithRetries(payload, alchemySendJsonRpc, _a) { var maxRetries = _a.maxRetries, retryInterval = _a.retryInterval, retryJitter = _a.retryJitter; return (0,tslib__WEBPACK_IMPORTED_MODULE_2__.__awaiter)(this, void 0, void 0, function () { var i, result, status_1, message, statusString; return (0,tslib__WEBPACK_IMPORTED_MODULE_2__.__generator)(this, function (_b) { switch (_b.label) { case 0: i = 0; _b.label = 1; case 1: if (!(i < maxRetries + 1)) return [3 /*break*/, 5]; return [4 /*yield*/, alchemySendJsonRpc(payload)]; case 2: result = _b.sent(); switch (result.type) { case "jsonrpc": return [2 /*return*/, result.response]; case "rateLimit": break; case "networkError": { status_1 = result.status, message = result.message; statusString = status_1 !== 0 ? "(" + status_1 + ") " : ""; throw new Error(statusString + " " + message); } default: return [2 /*return*/, (0,assert_never__WEBPACK_IMPORTED_MODULE_0__.default)(result)]; } return [4 /*yield*/, (0,_util_promises__WEBPACK_IMPORTED_MODULE_1__.delay)(retryInterval + ((retryJitter * Math.random()) | 0))]; case 3: _b.sent(); _b.label = 4; case 4: i++; return [3 /*break*/, 1]; case 5: throw new Error("Rate limited for " + (maxRetries + 1) + " consecutive attempts."); } }); }); } //# sourceMappingURL=sendJsonRpcPayload.js.map /***/ }), /***/ 97635: /*!**********************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/web3-adapter/sendRestPayload.js ***! \**********************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "makeRestPayloadSender": () => (/* binding */ makeRestPayloadSender) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! tslib */ 64762); /* harmony import */ var fetch_ponyfill__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fetch-ponyfill */ 2094); /* harmony import */ var fetch_ponyfill__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fetch_ponyfill__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _util_promises__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/promises */ 21857); function makeRestPayloadSender(_a) { var _this = this; var url = _a.url, config = _a.config; // The rest payload sender only works for alchemy.com http endpoints. var error; if (/^wss?:\/\//.test(url)) { error = "Alchemy rest endpoints are not available via websockets"; } if (!url.includes("alchemy")) { error = "Alchemy specific rest endpoints are not available with a non Alchemy provider."; } if (url.includes("alchemyapi.io")) { error = "Alchemy specific rest endpoints are not available with our legacy endpoints on alchemyapi.io, please switch over to alchemy.com"; } var urlObject = new URL(url); var origin = urlObject.origin; var apiKey = urlObject.pathname.substring(urlObject.pathname.lastIndexOf("/") + 1); var fetch = fetch_ponyfill__WEBPACK_IMPORTED_MODULE_0___default()().fetch; var sendRestPayload = function (path, payload) { return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__awaiter)(_this, void 0, void 0, function () { var maxRetries, retryInterval, retryJitter, endpoint, i, response, status_1; return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__generator)(this, function (_a) { switch (_a.label) { case 0: if (error) { throw new Error(error); } maxRetries = config.maxRetries, retryInterval = config.retryInterval, retryJitter = config.retryJitter; if (!(origin && apiKey)) return [3 /*break*/, 6]; endpoint = new URL(origin); endpoint.search = new URLSearchParams(payload).toString(); endpoint.pathname = apiKey + path; i = 0; _a.label = 1; case 1: if (!(i < maxRetries + 1)) return [3 /*break*/, 5]; return [4 /*yield*/, fetch(endpoint.href)]; case 2: response = _a.sent(); status_1 = response.status; switch (status_1) { case 200: return [2 /*return*/, response.json()]; case 429: break; default: throw new Error(response.status + ":" + response.statusText); } return [4 /*yield*/, (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.delay)(retryInterval + ((retryJitter * Math.random()) | 0))]; case 3: _a.sent(); _a.label = 4; case 4: i++; return [3 /*break*/, 1]; case 5: throw new Error("Rate limited for " + (maxRetries + 1) + " consecutive attempts."); case 6: return [2 /*return*/, Promise.resolve()]; } }); }); }; return { sendRestPayload: sendRestPayload, }; } //# sourceMappingURL=sendRestPayload.js.map /***/ }), /***/ 91863: /*!************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/dist/esm/web3-adapter/webSocketProvider.js ***! \************************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "AlchemyWebSocketProvider": () => (/* binding */ AlchemyWebSocketProvider) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! tslib */ 64762); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! eventemitter3 */ 4157); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _subscriptions_subscriptionBackfill__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../subscriptions/subscriptionBackfill */ 19397); /* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types */ 51348); /* harmony import */ var _util_hex__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/hex */ 23164); /* harmony import */ var _util_jsonRpc__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/jsonRpc */ 49885); /* harmony import */ var _util_promises__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/promises */ 21857); /* provided dependency */ var console = __webpack_require__(/*! console-browserify */ 88883); var HEARTBEAT_INTERVAL = 30000; var HEARTBEAT_WAIT_TIME = 10000; var BACKFILL_TIMEOUT = 60000; var BACKFILL_RETRIES = 5; /** * Subscriptions have a memory of recent events they have sent so that in the * event that they disconnect and need to backfill, they can detect re-orgs. * Keep a buffer that goes back at least these many blocks, the maximum amount * at which we might conceivably see a re-org. * * Note that while our buffer goes back this many blocks, it may contain more * than this many elements, since in the case of logs subscriptions more than * one event may be emitted for a block. */ var RETAINED_EVENT_BLOCK_COUNT = 10; var AlchemyWebSocketProvider = /** @class */ (function (_super) { (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__extends)(AlchemyWebSocketProvider, _super); function AlchemyWebSocketProvider(ws, sendJsonRpcPayload, jsonRpcSenders) { var _this = _super.call(this) || this; _this.ws = ws; _this.sendJsonRpcPayload = sendJsonRpcPayload; _this.jsonRpcSenders = jsonRpcSenders; // In the case of a WebSocket reconnection, all subscriptions are lost and we // create new ones to replace them, but we want to create the illusion that // the original subscriptions persist. Thus, maintain a mapping from the // "virtual" subscription ids which are visible to the consumer to the // "physical" subscription ids of the actual connections. This terminology is // borrowed from virtual and physical memory, which has a similar mapping. _this.virtualSubscriptionsById = new Map(); _this.virtualIdsByPhysicalId = new Map(); _this.cancelBackfill = noop; _this.startHeartbeat = function () { if (_this.heartbeatIntervalId != null) { return; } _this.heartbeatIntervalId = setInterval(function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__awaiter)(_this, void 0, void 0, function () { var _a; return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__generator)(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 2, , 3]); return [4 /*yield*/, (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.withTimeout)(this.jsonRpcSenders.send("net_version"), HEARTBEAT_WAIT_TIME)]; case 1: _b.sent(); return [3 /*break*/, 3]; case 2: _a = _b.sent(); this.ws.reconnect(); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }, HEARTBEAT_INTERVAL); }; _this.stopHeartbeatAndBackfill = function () { if (_this.heartbeatIntervalId != null) { clearInterval(_this.heartbeatIntervalId); _this.heartbeatIntervalId = undefined; } _this.cancelBackfill(); }; _this.handleMessage = function (event) { var message = JSON.parse(event.data); if (!(0,_types__WEBPACK_IMPORTED_MODULE_3__.isSubscriptionEvent)(message)) { return; } var physicalId = message.params.subscription; var virtualId = _this.virtualIdsByPhysicalId.get(physicalId); if (!virtualId) { return; } var subscription = _this.virtualSubscriptionsById.get(virtualId); if (subscription.method !== "eth_subscribe") { _this.emitGenericEvent(virtualId, message.params.result); return; } switch (subscription.params[0]) { case "newHeads": { var newHeadsSubscription = subscription; var newHeadsMessage = message; var isBackfilling = newHeadsSubscription.isBackfilling, backfillBuffer = newHeadsSubscription.backfillBuffer; var result = newHeadsMessage.params.result; if (isBackfilling) { addToNewHeadsEventsBuffer(backfillBuffer, result); } else { _this.emitNewHeadsEvent(virtualId, result); } break; } case "logs": { var logsSubscription = subscription; var logsMessage = message; var isBackfilling = logsSubscription.isBackfilling, backfillBuffer = logsSubscription.backfillBuffer; var result = logsMessage.params.result; if (isBackfilling) { addToLogsEventsBuffer(backfillBuffer, result); } else { _this.emitLogsEvent(virtualId, result); } break; } default: _this.emitGenericEvent(virtualId, message.params.result); } }; _this.handleReopen = function () { var e_1, _a; _this.virtualIdsByPhysicalId.clear(); var _b = (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.makeCancelToken)(), cancel = _b.cancel, isCancelled = _b.isCancelled; _this.cancelBackfill = cancel; var _loop_1 = function (subscription) { (function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__awaiter)(_this, void 0, void 0, function () { var error_1; return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.resubscribeAndBackfill(isCancelled, subscription)]; case 1: _a.sent(); return [3 /*break*/, 3]; case 2: error_1 = _a.sent(); if (!isCancelled()) { console.error("Error while backfilling \"" + subscription.params[0] + "\" subscription. Some events may be missing.", error_1); } return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); })(); }; try { for (var _c = (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__values)(_this.virtualSubscriptionsById.values()), _d = _c.next(); !_d.done; _d = _c.next()) { var subscription = _d.value; _loop_1(subscription); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_d && !_d.done && (_a = _c.return)) _a.call(_c); } finally { if (e_1) throw e_1.error; } } _this.startHeartbeat(); }; _this.backfiller = (0,_subscriptions_subscriptionBackfill__WEBPACK_IMPORTED_MODULE_4__.makeBackfiller)(jsonRpcSenders); _this.addSocketListeners(); _this.startHeartbeat(); return _this; } AlchemyWebSocketProvider.prototype.send = function (request, callback) { if (isSubscribeRequest(request)) { var id = request.id; if (id === undefined) { // The JSON-RPC spec says to return nothing if there is no request id. return; } (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.callWhenDone)(this.subscribe(request), callback); return; } if (isUnsubscribeRequest(request)) { (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.callWhenDone)(this.unsubscribe(request), callback); return; } (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.callWhenDone)(this.sendJsonRpcPayload(request), callback); }; AlchemyWebSocketProvider.prototype.supportsSubscriptions = function () { return true; }; AlchemyWebSocketProvider.prototype.disconnect = function (code, reason) { this.removeSocketListeners(); this.removeAllListeners(); this.stopHeartbeatAndBackfill(); this.ws.close(code, reason); }; AlchemyWebSocketProvider.prototype.connect = function () { // No-op. We're already connected when passed a websocket in the // constructor. }; AlchemyWebSocketProvider.prototype.reset = function () { // No-op. }; AlchemyWebSocketProvider.prototype.reconnect = function () { // No-op. This isn't called anywhere. }; AlchemyWebSocketProvider.prototype.subscribe = function (request) { return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__awaiter)(this, void 0, void 0, function () { var method, _a, params, startingBlockNumber, response, id; return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__generator)(this, function (_b) { switch (_b.label) { case 0: method = request.method, _a = request.params, params = _a === void 0 ? [] : _a; return [4 /*yield*/, this.getBlockNumber()]; case 1: startingBlockNumber = _b.sent(); return [4 /*yield*/, this.sendJsonRpcPayload(request)]; case 2: response = _b.sent(); id = response.result; this.virtualSubscriptionsById.set(id, { method: method, params: params, startingBlockNumber: startingBlockNumber, virtualId: id, physicalId: id, sentEvents: [], isBackfilling: false, backfillBuffer: [], }); this.virtualIdsByPhysicalId.set(id, id); return [2 /*return*/, (0,_util_jsonRpc__WEBPACK_IMPORTED_MODULE_5__.makeResponse)(request.id, id)]; } }); }); }; AlchemyWebSocketProvider.prototype.unsubscribe = function (request) { var _a; return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__awaiter)(this, void 0, void 0, function () { var subscriptionId, virtualSubscription, physicalId, physicalRequest; return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__generator)(this, function (_b) { switch (_b.label) { case 0: subscriptionId = (_a = request.params) === null || _a === void 0 ? void 0 : _a[0]; virtualSubscription = this.virtualSubscriptionsById.get(subscriptionId); if (!virtualSubscription) { return [2 /*return*/, (0,_util_jsonRpc__WEBPACK_IMPORTED_MODULE_5__.makeResponse)(request.id, false)]; } physicalId = virtualSubscription.physicalId; physicalRequest = (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_1__.__assign)({}, request), { params: [physicalId] }); return [4 /*yield*/, this.sendJsonRpcPayload(physicalRequest)]; case 1: _b.sent(); this.virtualSubscriptionsById.delete(subscriptionId); this.virtualIdsByPhysicalId.delete(physicalId); return [2 /*return*/, (0,_util_jsonRpc__WEBPACK_IMPORTED_MODULE_5__.makeResponse)(request.id, true)]; } }); }); }; AlchemyWebSocketProvider.prototype.addSocketListeners = function () { this.ws.addEventListener("message", this.handleMessage); this.ws.addEventListener("reopen", this.handleReopen); this.ws.addEventListener("down", this.stopHeartbeatAndBackfill); }; AlchemyWebSocketProvider.prototype.removeSocketListeners = function () { this.ws.removeEventListener("message", this.handleMessage); this.ws.removeEventListener("reopen", this.handleReopen); this.ws.removeEventListener("down", this.stopHeartbeatAndBackfill); }; AlchemyWebSocketProvider.prototype.resubscribeAndBackfill = function (isCancelled, subscription) { return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__awaiter)(this, void 0, void 0, function () { var virtualId, method, params, sentEvents, backfillBuffer, startingBlockNumber, physicalId, _a, backfillEvents, events, filter_1, backfillEvents, events; var _this = this; return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__generator)(this, function (_b) { switch (_b.label) { case 0: virtualId = subscription.virtualId, method = subscription.method, params = subscription.params, sentEvents = subscription.sentEvents, backfillBuffer = subscription.backfillBuffer, startingBlockNumber = subscription.startingBlockNumber; subscription.isBackfilling = true; backfillBuffer.length = 0; _b.label = 1; case 1: _b.trys.push([1, , 9, 10]); return [4 /*yield*/, this.jsonRpcSenders.send(method, params)]; case 2: physicalId = _b.sent(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.throwIfCancelled)(isCancelled); subscription.physicalId = physicalId; this.virtualIdsByPhysicalId.set(physicalId, virtualId); _a = params[0]; switch (_a) { case "newHeads": return [3 /*break*/, 3]; case "logs": return [3 /*break*/, 5]; } return [3 /*break*/, 7]; case 3: return [4 /*yield*/, (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.withBackoffRetries)(function () { return (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.withTimeout)(_this.backfiller.getNewHeadsBackfill(isCancelled, sentEvents, startingBlockNumber), BACKFILL_TIMEOUT); }, BACKFILL_RETRIES, function () { return !isCancelled(); })]; case 4: backfillEvents = _b.sent(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.throwIfCancelled)(isCancelled); events = (0,_subscriptions_subscriptionBackfill__WEBPACK_IMPORTED_MODULE_4__.dedupeNewHeads)((0,tslib__WEBPACK_IMPORTED_MODULE_1__.__spreadArray)((0,tslib__WEBPACK_IMPORTED_MODULE_1__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__read)(backfillEvents)), (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__read)(backfillBuffer))); events.forEach(function (event) { return _this.emitNewHeadsEvent(virtualId, event); }); return [3 /*break*/, 8]; case 5: filter_1 = params[1] || {}; return [4 /*yield*/, (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.withBackoffRetries)(function () { return (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.withTimeout)(_this.backfiller.getLogsBackfill(isCancelled, filter_1, sentEvents, startingBlockNumber), BACKFILL_TIMEOUT); }, BACKFILL_RETRIES, function () { return !isCancelled(); })]; case 6: backfillEvents = _b.sent(); (0,_util_promises__WEBPACK_IMPORTED_MODULE_2__.throwIfCancelled)(isCancelled); events = (0,_subscriptions_subscriptionBackfill__WEBPACK_IMPORTED_MODULE_4__.dedupeLogs)((0,tslib__WEBPACK_IMPORTED_MODULE_1__.__spreadArray)((0,tslib__WEBPACK_IMPORTED_MODULE_1__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__read)(backfillEvents)), (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__read)(backfillBuffer))); events.forEach(function (event) { return _this.emitLogsEvent(virtualId, event); }); return [3 /*break*/, 8]; case 7: return [3 /*break*/, 8]; case 8: return [3 /*break*/, 10]; case 9: subscription.isBackfilling = false; backfillBuffer.length = 0; return [7 /*endfinally*/]; case 10: return [2 /*return*/]; } }); }); }; AlchemyWebSocketProvider.prototype.getBlockNumber = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__awaiter)(this, void 0, void 0, function () { var blockNumberHex; return (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__generator)(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.jsonRpcSenders.send("eth_blockNumber")]; case 1: blockNumberHex = _a.sent(); return [2 /*return*/, (0,_util_hex__WEBPACK_IMPORTED_MODULE_6__.fromHex)(blockNumberHex)]; } }); }); }; AlchemyWebSocketProvider.prototype.emitNewHeadsEvent = function (virtualId, result) { this.emitAndRememberEvent(virtualId, result, getNewHeadsBlockNumber); }; AlchemyWebSocketProvider.prototype.emitLogsEvent = function (virtualId, result) { this.emitAndRememberEvent(virtualId, result, getLogsBlockNumber); }; /** * Emits an event to consumers, but also remembers it in its subscriptions's * `sentEvents` buffer so that we can detect re-orgs if the connection drops * and needs to be reconnected. */ AlchemyWebSocketProvider.prototype.emitAndRememberEvent = function (virtualId, result, getBlockNumber) { var subscription = this.virtualSubscriptionsById.get(virtualId); if (!subscription) { return; } // Web3 modifies these event objects once we pass them on (changing hex // numbers to numbers). We want the original event, so make a defensive // copy. addToPastEventsBuffer(subscription.sentEvents, (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__assign)({}, result), getBlockNumber); this.emitGenericEvent(virtualId, result); }; AlchemyWebSocketProvider.prototype.emitGenericEvent = function (virtualId, result) { var event = { jsonrpc: "2.0", method: "eth_subscription", params: { subscription: virtualId, result: result, }, }; this.emit("data", event); }; return AlchemyWebSocketProvider; }((eventemitter3__WEBPACK_IMPORTED_MODULE_0___default()))); function addToNewHeadsEventsBuffer(pastEvents, event) { addToPastEventsBuffer(pastEvents, event, getNewHeadsBlockNumber); } function addToLogsEventsBuffer(pastEvents, event) { addToPastEventsBuffer(pastEvents, event, getLogsBlockNumber); } /** * Adds a new event to an array of events, evicting any events which * are so old that they will no longer feasibly be part of a reorg. */ function addToPastEventsBuffer(pastEvents, event, getBlockNumber) { var currentBlockNumber = getBlockNumber(event); // Find first index of an event recent enough to retain, then drop everything // at a lower index. var firstGoodIndex = pastEvents.findIndex(function (e) { return getBlockNumber(e) > currentBlockNumber - RETAINED_EVENT_BLOCK_COUNT; }); if (firstGoodIndex === -1) { pastEvents.length = 0; } else { pastEvents.splice(0, firstGoodIndex); } pastEvents.push(event); } function isSubscribeRequest(request) { return !Array.isArray(request) && request.method === "eth_subscribe"; } function isUnsubscribeRequest(request) { return !Array.isArray(request) && request.method === "eth_unsubscribe"; } function getNewHeadsBlockNumber(event) { return (0,_util_hex__WEBPACK_IMPORTED_MODULE_6__.fromHex)(event.number); } function getLogsBlockNumber(event) { return (0,_util_hex__WEBPACK_IMPORTED_MODULE_6__.fromHex)(event.blockNumber); } function noop() { // Nothing. } //# sourceMappingURL=webSocketProvider.js.map /***/ }), /***/ 74450: /*!*****************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/eth-lib/lib/account.js ***! \*****************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; const Bytes = __webpack_require__(/*! ./bytes */ 33605); const Nat = __webpack_require__(/*! ./nat */ 89207); const elliptic = __webpack_require__(/*! elliptic */ 5247); const rlp = __webpack_require__(/*! ./rlp */ 78044); const secp256k1 = new elliptic.ec("secp256k1"); // eslint-disable-line const { keccak256, keccak256s } = __webpack_require__(/*! ./hash */ 10663); const create = entropy => { const innerHex = keccak256(Bytes.concat(Bytes.random(32), entropy || Bytes.random(32))); const middleHex = Bytes.concat(Bytes.concat(Bytes.random(32), innerHex), Bytes.random(32)); const outerHex = keccak256(middleHex); return fromPrivate(outerHex); }; const toChecksum = address => { const addressHash = keccak256s(address.slice(2)); let checksumAddress = "0x"; for (let i = 0; i < 40; i++) checksumAddress += parseInt(addressHash[i + 2], 16) > 7 ? address[i + 2].toUpperCase() : address[i + 2]; return checksumAddress; }; const fromPrivate = privateKey => { const buffer = new Buffer(privateKey.slice(2), "hex"); const ecKey = secp256k1.keyFromPrivate(buffer); const publicKey = "0x" + ecKey.getPublic(false, 'hex').slice(2); const publicHash = keccak256(publicKey); const address = toChecksum("0x" + publicHash.slice(-40)); return { address: address, privateKey: privateKey }; }; const encodeSignature = ([v, r, s]) => Bytes.flatten([r, s, v]); const decodeSignature = hex => [Bytes.slice(64, Bytes.length(hex), hex), Bytes.slice(0, 32, hex), Bytes.slice(32, 64, hex)]; const makeSigner = addToV => (hash, privateKey) => { const signature = secp256k1.keyFromPrivate(new Buffer(privateKey.slice(2), "hex")).sign(new Buffer(hash.slice(2), "hex"), { canonical: true }); return encodeSignature([Nat.fromString(Bytes.fromNumber(addToV + signature.recoveryParam)), Bytes.pad(32, Bytes.fromNat("0x" + signature.r.toString(16))), Bytes.pad(32, Bytes.fromNat("0x" + signature.s.toString(16)))]); }; const sign = makeSigner(27); // v=27|28 instead of 0|1... const recover = (hash, signature) => { const vals = decodeSignature(signature); const vrs = { v: Bytes.toNumber(vals[0]), r: vals[1].slice(2), s: vals[2].slice(2) }; const ecPublicKey = secp256k1.recoverPubKey(new Buffer(hash.slice(2), "hex"), vrs, vrs.v < 2 ? vrs.v : 1 - vrs.v % 2); // because odd vals mean v=0... sadly that means v=0 means v=1... I hate that const publicKey = "0x" + ecPublicKey.encode("hex", false).slice(2); const publicHash = keccak256(publicKey); const address = toChecksum("0x" + publicHash.slice(-40)); return address; }; module.exports = { create, toChecksum, fromPrivate, sign, makeSigner, recover, encodeSignature, decodeSignature }; /***/ }), /***/ 19538: /*!***************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/eth-lib/lib/array.js ***! \***************************************************************************/ /***/ ((module) => { const generate = (num, fn) => { let a = []; for (var i = 0; i < num; ++i) a.push(fn(i)); return a; }; const replicate = (num, val) => generate(num, () => val); const concat = (a, b) => a.concat(b); const flatten = a => { let r = []; for (let j = 0, J = a.length; j < J; ++j) for (let i = 0, I = a[j].length; i < I; ++i) r.push(a[j][i]); return r; }; const chunksOf = (n, a) => { let b = []; for (let i = 0, l = a.length; i < l; i += n) b.push(a.slice(i, i + n)); return b; }; module.exports = { generate, replicate, concat, flatten, chunksOf }; /***/ }), /***/ 33605: /*!***************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/eth-lib/lib/bytes.js ***! \***************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const A = __webpack_require__(/*! ./array.js */ 19538); const at = (bytes, index) => parseInt(bytes.slice(index * 2 + 2, index * 2 + 4), 16); const random = bytes => { let rnd; if (typeof window !== "undefined" && window.crypto && window.crypto.getRandomValues) rnd = window.crypto.getRandomValues(new Uint8Array(bytes));else if (true) rnd = __webpack_require__(/*! crypto */ 19726).randomBytes(bytes);else {} let hex = "0x"; for (let i = 0; i < bytes; ++i) hex += ("00" + rnd[i].toString(16)).slice(-2); return hex; }; const length = a => (a.length - 2) / 2; const flatten = a => "0x" + a.reduce((r, s) => r + s.slice(2), ""); const slice = (i, j, bs) => "0x" + bs.slice(i * 2 + 2, j * 2 + 2); const reverse = hex => { let rev = "0x"; for (let i = 0, l = length(hex); i < l; ++i) { rev += hex.slice((l - i) * 2, (l - i + 1) * 2); } return rev; }; const pad = (l, hex) => hex.length === l * 2 + 2 ? hex : pad(l, "0x" + "0" + hex.slice(2)); const padRight = (l, hex) => hex.length === l * 2 + 2 ? hex : padRight(l, hex + "0"); const toArray = hex => { let arr = []; for (let i = 2, l = hex.length; i < l; i += 2) arr.push(parseInt(hex.slice(i, i + 2), 16)); return arr; }; const fromArray = arr => { let hex = "0x"; for (let i = 0, l = arr.length; i < l; ++i) { let b = arr[i]; hex += (b < 16 ? "0" : "") + b.toString(16); } return hex; }; const toUint8Array = hex => new Uint8Array(toArray(hex)); const fromUint8Array = arr => fromArray([].slice.call(arr, 0)); const fromNumber = num => { let hex = num.toString(16); return hex.length % 2 === 0 ? "0x" + hex : "0x0" + hex; }; const toNumber = hex => parseInt(hex.slice(2), 16); const concat = (a, b) => a.concat(b.slice(2)); const fromNat = bn => bn === "0x0" ? "0x" : bn.length % 2 === 0 ? bn : "0x0" + bn.slice(2); const toNat = bn => bn[2] === "0" ? "0x" + bn.slice(3) : bn; const fromAscii = ascii => { let hex = "0x"; for (let i = 0; i < ascii.length; ++i) hex += ("00" + ascii.charCodeAt(i).toString(16)).slice(-2); return hex; }; const toAscii = hex => { let ascii = ""; for (let i = 2; i < hex.length; i += 2) ascii += String.fromCharCode(parseInt(hex.slice(i, i + 2), 16)); return ascii; }; // From https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330 const fromString = s => { const makeByte = uint8 => { const b = uint8.toString(16); return b.length < 2 ? "0" + b : b; }; let bytes = "0x"; for (let ci = 0; ci != s.length; ci++) { let c = s.charCodeAt(ci); if (c < 128) { bytes += makeByte(c); continue; } if (c < 2048) { bytes += makeByte(c >> 6 | 192); } else { if (c > 0xd7ff && c < 0xdc00) { if (++ci == s.length) return null; let c2 = s.charCodeAt(ci); if (c2 < 0xdc00 || c2 > 0xdfff) return null; c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); bytes += makeByte(c >> 18 | 240); bytes += makeByte(c >> 12 & 63 | 128); } else { // c <= 0xffff bytes += makeByte(c >> 12 | 224); } bytes += makeByte(c >> 6 & 63 | 128); } bytes += makeByte(c & 63 | 128); } return bytes; }; const toString = bytes => { let s = ''; let i = 0; let l = length(bytes); while (i < l) { let c = at(bytes, i++); if (c > 127) { if (c > 191 && c < 224) { if (i >= l) return null; c = (c & 31) << 6 | at(bytes, i) & 63; } else if (c > 223 && c < 240) { if (i + 1 >= l) return null; c = (c & 15) << 12 | (at(bytes, i) & 63) << 6 | at(bytes, ++i) & 63; } else if (c > 239 && c < 248) { if (i + 2 >= l) return null; c = (c & 7) << 18 | (at(bytes, i) & 63) << 12 | (at(bytes, ++i) & 63) << 6 | at(bytes, ++i) & 63; } else return null; ++i; } if (c <= 0xffff) s += String.fromCharCode(c);else if (c <= 0x10ffff) { c -= 0x10000; s += String.fromCharCode(c >> 10 | 0xd800); s += String.fromCharCode(c & 0x3FF | 0xdc00); } else return null; } return s; }; module.exports = { random, length, concat, flatten, slice, reverse, pad, padRight, fromAscii, toAscii, fromString, toString, fromNumber, toNumber, fromNat, toNat, fromArray, toArray, fromUint8Array, toUint8Array }; /***/ }), /***/ 10663: /*!**************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/eth-lib/lib/hash.js ***! \**************************************************************************/ /***/ ((module) => { // This was ported from https://github.com/emn178/js-sha3, with some minor // modifications and pruning. It is licensed under MIT: // // Copyright 2015-2016 Chen, Yi-Cyuan // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. const HEX_CHARS = '0123456789abcdef'.split(''); const KECCAK_PADDING = [1, 256, 65536, 16777216]; const SHIFT = [0, 8, 16, 24]; const RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; const Keccak = bits => ({ blocks: [], reset: true, block: 0, start: 0, blockCount: 1600 - (bits << 1) >> 5, outputBlocks: bits >> 5, s: (s => [].concat(s, s, s, s, s))([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }); const update = (state, message) => { var length = message.length, blocks = state.blocks, byteCount = state.blockCount << 2, blockCount = state.blockCount, outputBlocks = state.outputBlocks, s = state.s, index = 0, i, code; // update while (index < length) { if (state.reset) { state.reset = false; blocks[0] = state.block; for (i = 1; i < blockCount + 1; ++i) { blocks[i] = 0; } } if (typeof message !== "string") { for (i = state.start; index < length && i < byteCount; ++index) { blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; } } else { for (i = state.start; index < length && i < byteCount; ++index) { code = message.charCodeAt(index); if (code < 0x80) { blocks[i >> 2] |= code << SHIFT[i++ & 3]; } else if (code < 0x800) { blocks[i >> 2] |= (0xc0 | code >> 6) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; } else if (code < 0xd800 || code >= 0xe000) { blocks[i >> 2] |= (0xe0 | code >> 12) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; } else { code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff); blocks[i >> 2] |= (0xf0 | code >> 18) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | code >> 12 & 0x3f) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; } } } state.lastByteIndex = i; if (i >= byteCount) { state.start = i - byteCount; state.block = blocks[blockCount]; for (i = 0; i < blockCount; ++i) { s[i] ^= blocks[i]; } f(s); state.reset = true; } else { state.start = i; } } // finalize i = state.lastByteIndex; blocks[i >> 2] |= KECCAK_PADDING[i & 3]; if (state.lastByteIndex === byteCount) { blocks[0] = blocks[blockCount]; for (i = 1; i < blockCount + 1; ++i) { blocks[i] = 0; } } blocks[blockCount - 1] |= 0x80000000; for (i = 0; i < blockCount; ++i) { s[i] ^= blocks[i]; } f(s); // toString var hex = '', i = 0, j = 0, block; while (j < outputBlocks) { for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { block = s[i]; hex += HEX_CHARS[block >> 4 & 0x0F] + HEX_CHARS[block & 0x0F] + HEX_CHARS[block >> 12 & 0x0F] + HEX_CHARS[block >> 8 & 0x0F] + HEX_CHARS[block >> 20 & 0x0F] + HEX_CHARS[block >> 16 & 0x0F] + HEX_CHARS[block >> 28 & 0x0F] + HEX_CHARS[block >> 24 & 0x0F]; } if (j % blockCount === 0) { f(s); i = 0; } } return "0x" + hex; }; const f = s => { var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; for (n = 0; n < 48; n += 2) { c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; h = c8 ^ (c2 << 1 | c3 >>> 31); l = c9 ^ (c3 << 1 | c2 >>> 31); s[0] ^= h; s[1] ^= l; s[10] ^= h; s[11] ^= l; s[20] ^= h; s[21] ^= l; s[30] ^= h; s[31] ^= l; s[40] ^= h; s[41] ^= l; h = c0 ^ (c4 << 1 | c5 >>> 31); l = c1 ^ (c5 << 1 | c4 >>> 31); s[2] ^= h; s[3] ^= l; s[12] ^= h; s[13] ^= l; s[22] ^= h; s[23] ^= l; s[32] ^= h; s[33] ^= l; s[42] ^= h; s[43] ^= l; h = c2 ^ (c6 << 1 | c7 >>> 31); l = c3 ^ (c7 << 1 | c6 >>> 31); s[4] ^= h; s[5] ^= l; s[14] ^= h; s[15] ^= l; s[24] ^= h; s[25] ^= l; s[34] ^= h; s[35] ^= l; s[44] ^= h; s[45] ^= l; h = c4 ^ (c8 << 1 | c9 >>> 31); l = c5 ^ (c9 << 1 | c8 >>> 31); s[6] ^= h; s[7] ^= l; s[16] ^= h; s[17] ^= l; s[26] ^= h; s[27] ^= l; s[36] ^= h; s[37] ^= l; s[46] ^= h; s[47] ^= l; h = c6 ^ (c0 << 1 | c1 >>> 31); l = c7 ^ (c1 << 1 | c0 >>> 31); s[8] ^= h; s[9] ^= l; s[18] ^= h; s[19] ^= l; s[28] ^= h; s[29] ^= l; s[38] ^= h; s[39] ^= l; s[48] ^= h; s[49] ^= l; b0 = s[0]; b1 = s[1]; b32 = s[11] << 4 | s[10] >>> 28; b33 = s[10] << 4 | s[11] >>> 28; b14 = s[20] << 3 | s[21] >>> 29; b15 = s[21] << 3 | s[20] >>> 29; b46 = s[31] << 9 | s[30] >>> 23; b47 = s[30] << 9 | s[31] >>> 23; b28 = s[40] << 18 | s[41] >>> 14; b29 = s[41] << 18 | s[40] >>> 14; b20 = s[2] << 1 | s[3] >>> 31; b21 = s[3] << 1 | s[2] >>> 31; b2 = s[13] << 12 | s[12] >>> 20; b3 = s[12] << 12 | s[13] >>> 20; b34 = s[22] << 10 | s[23] >>> 22; b35 = s[23] << 10 | s[22] >>> 22; b16 = s[33] << 13 | s[32] >>> 19; b17 = s[32] << 13 | s[33] >>> 19; b48 = s[42] << 2 | s[43] >>> 30; b49 = s[43] << 2 | s[42] >>> 30; b40 = s[5] << 30 | s[4] >>> 2; b41 = s[4] << 30 | s[5] >>> 2; b22 = s[14] << 6 | s[15] >>> 26; b23 = s[15] << 6 | s[14] >>> 26; b4 = s[25] << 11 | s[24] >>> 21; b5 = s[24] << 11 | s[25] >>> 21; b36 = s[34] << 15 | s[35] >>> 17; b37 = s[35] << 15 | s[34] >>> 17; b18 = s[45] << 29 | s[44] >>> 3; b19 = s[44] << 29 | s[45] >>> 3; b10 = s[6] << 28 | s[7] >>> 4; b11 = s[7] << 28 | s[6] >>> 4; b42 = s[17] << 23 | s[16] >>> 9; b43 = s[16] << 23 | s[17] >>> 9; b24 = s[26] << 25 | s[27] >>> 7; b25 = s[27] << 25 | s[26] >>> 7; b6 = s[36] << 21 | s[37] >>> 11; b7 = s[37] << 21 | s[36] >>> 11; b38 = s[47] << 24 | s[46] >>> 8; b39 = s[46] << 24 | s[47] >>> 8; b30 = s[8] << 27 | s[9] >>> 5; b31 = s[9] << 27 | s[8] >>> 5; b12 = s[18] << 20 | s[19] >>> 12; b13 = s[19] << 20 | s[18] >>> 12; b44 = s[29] << 7 | s[28] >>> 25; b45 = s[28] << 7 | s[29] >>> 25; b26 = s[38] << 8 | s[39] >>> 24; b27 = s[39] << 8 | s[38] >>> 24; b8 = s[48] << 14 | s[49] >>> 18; b9 = s[49] << 14 | s[48] >>> 18; s[0] = b0 ^ ~b2 & b4; s[1] = b1 ^ ~b3 & b5; s[10] = b10 ^ ~b12 & b14; s[11] = b11 ^ ~b13 & b15; s[20] = b20 ^ ~b22 & b24; s[21] = b21 ^ ~b23 & b25; s[30] = b30 ^ ~b32 & b34; s[31] = b31 ^ ~b33 & b35; s[40] = b40 ^ ~b42 & b44; s[41] = b41 ^ ~b43 & b45; s[2] = b2 ^ ~b4 & b6; s[3] = b3 ^ ~b5 & b7; s[12] = b12 ^ ~b14 & b16; s[13] = b13 ^ ~b15 & b17; s[22] = b22 ^ ~b24 & b26; s[23] = b23 ^ ~b25 & b27; s[32] = b32 ^ ~b34 & b36; s[33] = b33 ^ ~b35 & b37; s[42] = b42 ^ ~b44 & b46; s[43] = b43 ^ ~b45 & b47; s[4] = b4 ^ ~b6 & b8; s[5] = b5 ^ ~b7 & b9; s[14] = b14 ^ ~b16 & b18; s[15] = b15 ^ ~b17 & b19; s[24] = b24 ^ ~b26 & b28; s[25] = b25 ^ ~b27 & b29; s[34] = b34 ^ ~b36 & b38; s[35] = b35 ^ ~b37 & b39; s[44] = b44 ^ ~b46 & b48; s[45] = b45 ^ ~b47 & b49; s[6] = b6 ^ ~b8 & b0; s[7] = b7 ^ ~b9 & b1; s[16] = b16 ^ ~b18 & b10; s[17] = b17 ^ ~b19 & b11; s[26] = b26 ^ ~b28 & b20; s[27] = b27 ^ ~b29 & b21; s[36] = b36 ^ ~b38 & b30; s[37] = b37 ^ ~b39 & b31; s[46] = b46 ^ ~b48 & b40; s[47] = b47 ^ ~b49 & b41; s[8] = b8 ^ ~b0 & b2; s[9] = b9 ^ ~b1 & b3; s[18] = b18 ^ ~b10 & b12; s[19] = b19 ^ ~b11 & b13; s[28] = b28 ^ ~b20 & b22; s[29] = b29 ^ ~b21 & b23; s[38] = b38 ^ ~b30 & b32; s[39] = b39 ^ ~b31 & b33; s[48] = b48 ^ ~b40 & b42; s[49] = b49 ^ ~b41 & b43; s[0] ^= RC[n]; s[1] ^= RC[n + 1]; } }; const keccak = bits => str => { var msg; if (str.slice(0, 2) === "0x") { msg = []; for (var i = 2, l = str.length; i < l; i += 2) msg.push(parseInt(str.slice(i, i + 2), 16)); } else { msg = str; } return update(Keccak(bits, bits), msg); }; module.exports = { keccak256: keccak(256), keccak512: keccak(512), keccak256s: keccak(256), keccak512s: keccak(512) }; /***/ }), /***/ 89207: /*!*************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/eth-lib/lib/nat.js ***! \*************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const BN = __webpack_require__(/*! bn.js */ 62630); const Bytes = __webpack_require__(/*! ./bytes */ 33605); const fromBN = bn => "0x" + bn.toString("hex"); const toBN = str => new BN(str.slice(2), 16); const fromString = str => { const bn = "0x" + (str.slice(0, 2) === "0x" ? new BN(str.slice(2), 16) : new BN(str, 10)).toString("hex"); return bn === "0x0" ? "0x" : bn; }; const toEther = wei => toNumber(div(wei, fromString("10000000000"))) / 100000000; const fromEther = eth => mul(fromNumber(Math.floor(eth * 100000000)), fromString("10000000000")); const toString = a => toBN(a).toString(10); const fromNumber = a => typeof a === "string" ? /^0x/.test(a) ? a : "0x" + a : "0x" + new BN(a).toString("hex"); const toNumber = a => toBN(a).toNumber(); const toUint256 = a => Bytes.pad(32, a); const bin = method => (a, b) => fromBN(toBN(a)[method](toBN(b))); const add = bin("add"); const mul = bin("mul"); const div = bin("div"); const sub = bin("sub"); module.exports = { toString, fromString, toNumber, fromNumber, toEther, fromEther, toUint256, add, mul, div, sub }; /***/ }), /***/ 78044: /*!*************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/eth-lib/lib/rlp.js ***! \*************************************************************************/ /***/ ((module) => { // The RLP format // Serialization and deserialization for the BytesTree type, under the following grammar: // | First byte | Meaning | // | ---------- | -------------------------------------------------------------------------- | // | 0 to 127 | HEX(leaf) | // | 128 to 183 | HEX(length_of_leaf + 128) + HEX(leaf) | // | 184 to 191 | HEX(length_of_length_of_leaf + 128 + 55) + HEX(length_of_leaf) + HEX(leaf) | // | 192 to 247 | HEX(length_of_node + 192) + HEX(node) | // | 248 to 255 | HEX(length_of_length_of_node + 128 + 55) + HEX(length_of_node) + HEX(node) | const encode = tree => { const padEven = str => str.length % 2 === 0 ? str : "0" + str; const uint = num => padEven(num.toString(16)); const length = (len, add) => len < 56 ? uint(add + len) : uint(add + uint(len).length / 2 + 55) + uint(len); const dataTree = tree => { if (typeof tree === "string") { const hex = tree.slice(2); const pre = hex.length != 2 || hex >= "80" ? length(hex.length / 2, 128) : ""; return pre + hex; } else { const hex = tree.map(dataTree).join(""); const pre = length(hex.length / 2, 192); return pre + hex; } }; return "0x" + dataTree(tree); }; const decode = hex => { let i = 2; const parseTree = () => { if (i >= hex.length) throw ""; const head = hex.slice(i, i + 2); return head < "80" ? (i += 2, "0x" + head) : head < "c0" ? parseHex() : parseList(); }; const parseLength = () => { const len = parseInt(hex.slice(i, i += 2), 16) % 64; return len < 56 ? len : parseInt(hex.slice(i, i += (len - 55) * 2), 16); }; const parseHex = () => { const len = parseLength(); return "0x" + hex.slice(i, i += len * 2); }; const parseList = () => { const lim = parseLength() * 2 + i; let list = []; while (i < lim) list.push(parseTree()); return list; }; try { return parseTree(); } catch (e) { return []; } }; module.exports = { encode, decode }; /***/ }), /***/ 43149: /*!**********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/account.js ***! \**********************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isZeroAddress = exports.zeroAddress = exports.importPublic = exports.privateToAddress = exports.privateToPublic = exports.publicToAddress = exports.pubToAddress = exports.isValidPublic = exports.isValidPrivate = exports.generateAddress2 = exports.generateAddress = exports.isValidChecksumAddress = exports.toChecksumAddress = exports.isValidAddress = exports.Account = void 0; var assert_1 = __importDefault(__webpack_require__(/*! assert */ 80469)); var bn_js_1 = __importDefault(__webpack_require__(/*! bn.js */ 66503)); var rlp = __importStar(__webpack_require__(/*! rlp */ 78084)); var secp256k1_1 = __webpack_require__(/*! ethereum-cryptography/secp256k1 */ 10019); var internal_1 = __webpack_require__(/*! ./internal */ 99671); var constants_1 = __webpack_require__(/*! ./constants */ 31982); var bytes_1 = __webpack_require__(/*! ./bytes */ 83643); var hash_1 = __webpack_require__(/*! ./hash */ 83989); var helpers_1 = __webpack_require__(/*! ./helpers */ 34087); var types_1 = __webpack_require__(/*! ./types */ 83554); var Account = /** @class */ (function () { /** * This constructor assigns and validates the values. * Use the static factory methods to assist in creating an Account from varying data types. */ function Account(nonce, balance, stateRoot, codeHash) { if (nonce === void 0) { nonce = new bn_js_1.default(0); } if (balance === void 0) { balance = new bn_js_1.default(0); } if (stateRoot === void 0) { stateRoot = constants_1.KECCAK256_RLP; } if (codeHash === void 0) { codeHash = constants_1.KECCAK256_NULL; } this.nonce = nonce; this.balance = balance; this.stateRoot = stateRoot; this.codeHash = codeHash; this._validate(); } Account.fromAccountData = function (accountData) { var nonce = accountData.nonce, balance = accountData.balance, stateRoot = accountData.stateRoot, codeHash = accountData.codeHash; return new Account(nonce ? new bn_js_1.default((0, bytes_1.toBuffer)(nonce)) : undefined, balance ? new bn_js_1.default((0, bytes_1.toBuffer)(balance)) : undefined, stateRoot ? (0, bytes_1.toBuffer)(stateRoot) : undefined, codeHash ? (0, bytes_1.toBuffer)(codeHash) : undefined); }; Account.fromRlpSerializedAccount = function (serialized) { var values = rlp.decode(serialized); if (!Array.isArray(values)) { throw new Error('Invalid serialized account input. Must be array'); } return this.fromValuesArray(values); }; Account.fromValuesArray = function (values) { var _a = __read(values, 4), nonce = _a[0], balance = _a[1], stateRoot = _a[2], codeHash = _a[3]; return new Account(new bn_js_1.default(nonce), new bn_js_1.default(balance), stateRoot, codeHash); }; Account.prototype._validate = function () { if (this.nonce.lt(new bn_js_1.default(0))) { throw new Error('nonce must be greater than zero'); } if (this.balance.lt(new bn_js_1.default(0))) { throw new Error('balance must be greater than zero'); } if (this.stateRoot.length !== 32) { throw new Error('stateRoot must have a length of 32'); } if (this.codeHash.length !== 32) { throw new Error('codeHash must have a length of 32'); } }; /** * Returns a Buffer Array of the raw Buffers for the account, in order. */ Account.prototype.raw = function () { return [ (0, types_1.bnToUnpaddedBuffer)(this.nonce), (0, types_1.bnToUnpaddedBuffer)(this.balance), this.stateRoot, this.codeHash, ]; }; /** * Returns the RLP serialization of the account as a `Buffer`. */ Account.prototype.serialize = function () { return rlp.encode(this.raw()); }; /** * Returns a `Boolean` determining if the account is a contract. */ Account.prototype.isContract = function () { return !this.codeHash.equals(constants_1.KECCAK256_NULL); }; /** * Returns a `Boolean` determining if the account is empty complying to the definition of * account emptiness in [EIP-161](https://eips.ethereum.org/EIPS/eip-161): * "An account is considered empty when it has no code and zero nonce and zero balance." */ Account.prototype.isEmpty = function () { return this.balance.isZero() && this.nonce.isZero() && this.codeHash.equals(constants_1.KECCAK256_NULL); }; return Account; }()); exports.Account = Account; /** * Checks if the address is a valid. Accepts checksummed addresses too. */ var isValidAddress = function (hexAddress) { try { (0, helpers_1.assertIsString)(hexAddress); } catch (e) { return false; } return /^0x[0-9a-fA-F]{40}$/.test(hexAddress); }; exports.isValidAddress = isValidAddress; /** * Returns a checksummed address. * * If an eip1191ChainId is provided, the chainId will be included in the checksum calculation. This * has the effect of checksummed addresses for one chain having invalid checksums for others. * For more details see [EIP-1191](https://eips.ethereum.org/EIPS/eip-1191). * * WARNING: Checksums with and without the chainId will differ and the EIP-1191 checksum is not * backwards compatible to the original widely adopted checksum format standard introduced in * [EIP-55](https://eips.ethereum.org/EIPS/eip-55), so this will break in existing applications. * Usage of this EIP is therefore discouraged unless you have a very targeted use case. */ var toChecksumAddress = function (hexAddress, eip1191ChainId) { (0, helpers_1.assertIsHexString)(hexAddress); var address = (0, internal_1.stripHexPrefix)(hexAddress).toLowerCase(); var prefix = ''; if (eip1191ChainId) { var chainId = (0, types_1.toType)(eip1191ChainId, types_1.TypeOutput.BN); prefix = chainId.toString() + '0x'; } var hash = (0, hash_1.keccakFromString)(prefix + address).toString('hex'); var ret = '0x'; for (var i = 0; i < address.length; i++) { if (parseInt(hash[i], 16) >= 8) { ret += address[i].toUpperCase(); } else { ret += address[i]; } } return ret; }; exports.toChecksumAddress = toChecksumAddress; /** * Checks if the address is a valid checksummed address. * * See toChecksumAddress' documentation for details about the eip1191ChainId parameter. */ var isValidChecksumAddress = function (hexAddress, eip1191ChainId) { return (0, exports.isValidAddress)(hexAddress) && (0, exports.toChecksumAddress)(hexAddress, eip1191ChainId) === hexAddress; }; exports.isValidChecksumAddress = isValidChecksumAddress; /** * Generates an address of a newly created contract. * @param from The address which is creating this new address * @param nonce The nonce of the from account */ var generateAddress = function (from, nonce) { (0, helpers_1.assertIsBuffer)(from); (0, helpers_1.assertIsBuffer)(nonce); var nonceBN = new bn_js_1.default(nonce); if (nonceBN.isZero()) { // in RLP we want to encode null in the case of zero nonce // read the RLP documentation for an answer if you dare return (0, hash_1.rlphash)([from, null]).slice(-20); } // Only take the lower 160bits of the hash return (0, hash_1.rlphash)([from, Buffer.from(nonceBN.toArray())]).slice(-20); }; exports.generateAddress = generateAddress; /** * Generates an address for a contract created using CREATE2. * @param from The address which is creating this new address * @param salt A salt * @param initCode The init code of the contract being created */ var generateAddress2 = function (from, salt, initCode) { (0, helpers_1.assertIsBuffer)(from); (0, helpers_1.assertIsBuffer)(salt); (0, helpers_1.assertIsBuffer)(initCode); (0, assert_1.default)(from.length === 20); (0, assert_1.default)(salt.length === 32); var address = (0, hash_1.keccak256)(Buffer.concat([Buffer.from('ff', 'hex'), from, salt, (0, hash_1.keccak256)(initCode)])); return address.slice(-20); }; exports.generateAddress2 = generateAddress2; /** * Checks if the private key satisfies the rules of the curve secp256k1. */ var isValidPrivate = function (privateKey) { return (0, secp256k1_1.privateKeyVerify)(privateKey); }; exports.isValidPrivate = isValidPrivate; /** * Checks if the public key satisfies the rules of the curve secp256k1 * and the requirements of Ethereum. * @param publicKey The two points of an uncompressed key, unless sanitize is enabled * @param sanitize Accept public keys in other formats */ var isValidPublic = function (publicKey, sanitize) { if (sanitize === void 0) { sanitize = false; } (0, helpers_1.assertIsBuffer)(publicKey); if (publicKey.length === 64) { // Convert to SEC1 for secp256k1 return (0, secp256k1_1.publicKeyVerify)(Buffer.concat([Buffer.from([4]), publicKey])); } if (!sanitize) { return false; } return (0, secp256k1_1.publicKeyVerify)(publicKey); }; exports.isValidPublic = isValidPublic; /** * Returns the ethereum address of a given public key. * Accepts "Ethereum public keys" and SEC1 encoded keys. * @param pubKey The two points of an uncompressed key, unless sanitize is enabled * @param sanitize Accept public keys in other formats */ var pubToAddress = function (pubKey, sanitize) { if (sanitize === void 0) { sanitize = false; } (0, helpers_1.assertIsBuffer)(pubKey); if (sanitize && pubKey.length !== 64) { pubKey = Buffer.from((0, secp256k1_1.publicKeyConvert)(pubKey, false).slice(1)); } (0, assert_1.default)(pubKey.length === 64); // Only take the lower 160bits of the hash return (0, hash_1.keccak)(pubKey).slice(-20); }; exports.pubToAddress = pubToAddress; exports.publicToAddress = exports.pubToAddress; /** * Returns the ethereum public key of a given private key. * @param privateKey A private key must be 256 bits wide */ var privateToPublic = function (privateKey) { (0, helpers_1.assertIsBuffer)(privateKey); // skip the type flag and use the X, Y points return Buffer.from((0, secp256k1_1.publicKeyCreate)(privateKey, false)).slice(1); }; exports.privateToPublic = privateToPublic; /** * Returns the ethereum address of a given private key. * @param privateKey A private key must be 256 bits wide */ var privateToAddress = function (privateKey) { return (0, exports.publicToAddress)((0, exports.privateToPublic)(privateKey)); }; exports.privateToAddress = privateToAddress; /** * Converts a public key to the Ethereum format. */ var importPublic = function (publicKey) { (0, helpers_1.assertIsBuffer)(publicKey); if (publicKey.length !== 64) { publicKey = Buffer.from((0, secp256k1_1.publicKeyConvert)(publicKey, false).slice(1)); } return publicKey; }; exports.importPublic = importPublic; /** * Returns the zero address. */ var zeroAddress = function () { var addressLength = 20; var addr = (0, bytes_1.zeros)(addressLength); return (0, bytes_1.bufferToHex)(addr); }; exports.zeroAddress = zeroAddress; /** * Checks if a given address is the zero address. */ var isZeroAddress = function (hexAddress) { try { (0, helpers_1.assertIsString)(hexAddress); } catch (e) { return false; } var zeroAddr = (0, exports.zeroAddress)(); return zeroAddr === hexAddress; }; exports.isZeroAddress = isZeroAddress; //# sourceMappingURL=account.js.map /***/ }), /***/ 75221: /*!**********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/address.js ***! \**********************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Address = void 0; var assert_1 = __importDefault(__webpack_require__(/*! assert */ 80469)); var bn_js_1 = __importDefault(__webpack_require__(/*! bn.js */ 66503)); var bytes_1 = __webpack_require__(/*! ./bytes */ 83643); var account_1 = __webpack_require__(/*! ./account */ 43149); var Address = /** @class */ (function () { function Address(buf) { (0, assert_1.default)(buf.length === 20, 'Invalid address length'); this.buf = buf; } /** * Returns the zero address. */ Address.zero = function () { return new Address((0, bytes_1.zeros)(20)); }; /** * Returns an Address object from a hex-encoded string. * @param str - Hex-encoded address */ Address.fromString = function (str) { (0, assert_1.default)((0, account_1.isValidAddress)(str), 'Invalid address'); return new Address((0, bytes_1.toBuffer)(str)); }; /** * Returns an address for a given public key. * @param pubKey The two points of an uncompressed key */ Address.fromPublicKey = function (pubKey) { (0, assert_1.default)(Buffer.isBuffer(pubKey), 'Public key should be Buffer'); var buf = (0, account_1.pubToAddress)(pubKey); return new Address(buf); }; /** * Returns an address for a given private key. * @param privateKey A private key must be 256 bits wide */ Address.fromPrivateKey = function (privateKey) { (0, assert_1.default)(Buffer.isBuffer(privateKey), 'Private key should be Buffer'); var buf = (0, account_1.privateToAddress)(privateKey); return new Address(buf); }; /** * Generates an address for a newly created contract. * @param from The address which is creating this new address * @param nonce The nonce of the from account */ Address.generate = function (from, nonce) { (0, assert_1.default)(bn_js_1.default.isBN(nonce)); return new Address((0, account_1.generateAddress)(from.buf, nonce.toArrayLike(Buffer))); }; /** * Generates an address for a contract created using CREATE2. * @param from The address which is creating this new address * @param salt A salt * @param initCode The init code of the contract being created */ Address.generate2 = function (from, salt, initCode) { (0, assert_1.default)(Buffer.isBuffer(salt)); (0, assert_1.default)(Buffer.isBuffer(initCode)); return new Address((0, account_1.generateAddress2)(from.buf, salt, initCode)); }; /** * Is address equal to another. */ Address.prototype.equals = function (address) { return this.buf.equals(address.buf); }; /** * Is address zero. */ Address.prototype.isZero = function () { return this.equals(Address.zero()); }; /** * True if address is in the address range defined * by EIP-1352 */ Address.prototype.isPrecompileOrSystemAddress = function () { var addressBN = new bn_js_1.default(this.buf); var rangeMin = new bn_js_1.default(0); var rangeMax = new bn_js_1.default('ffff', 'hex'); return addressBN.gte(rangeMin) && addressBN.lte(rangeMax); }; /** * Returns hex encoding of address. */ Address.prototype.toString = function () { return '0x' + this.buf.toString('hex'); }; /** * Returns Buffer representation of address. */ Address.prototype.toBuffer = function () { return Buffer.from(this.buf); }; return Address; }()); exports.Address = Address; //# sourceMappingURL=address.js.map /***/ }), /***/ 83643: /*!********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/bytes.js ***! \********************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baToJSON = exports.toUtf8 = exports.addHexPrefix = exports.toUnsigned = exports.fromSigned = exports.bufferToHex = exports.bufferToInt = exports.toBuffer = exports.unpadHexString = exports.unpadArray = exports.unpadBuffer = exports.setLengthRight = exports.setLengthLeft = exports.zeros = exports.intToBuffer = exports.intToHex = void 0; var bn_js_1 = __importDefault(__webpack_require__(/*! bn.js */ 66503)); var internal_1 = __webpack_require__(/*! ./internal */ 99671); var helpers_1 = __webpack_require__(/*! ./helpers */ 34087); /** * Converts a `Number` into a hex `String` * @param {Number} i * @return {String} */ var intToHex = function (i) { if (!Number.isSafeInteger(i) || i < 0) { throw new Error("Received an invalid integer type: " + i); } return "0x" + i.toString(16); }; exports.intToHex = intToHex; /** * Converts an `Number` to a `Buffer` * @param {Number} i * @return {Buffer} */ var intToBuffer = function (i) { var hex = (0, exports.intToHex)(i); return Buffer.from((0, internal_1.padToEven)(hex.slice(2)), 'hex'); }; exports.intToBuffer = intToBuffer; /** * Returns a buffer filled with 0s. * @param bytes the number of bytes the buffer should be */ var zeros = function (bytes) { return Buffer.allocUnsafe(bytes).fill(0); }; exports.zeros = zeros; /** * Pads a `Buffer` with zeros till it has `length` bytes. * Truncates the beginning or end of input if its length exceeds `length`. * @param msg the value to pad (Buffer) * @param length the number of bytes the output should be * @param right whether to start padding form the left or right * @return (Buffer) */ var setLength = function (msg, length, right) { var buf = (0, exports.zeros)(length); if (right) { if (msg.length < length) { msg.copy(buf); return buf; } return msg.slice(0, length); } else { if (msg.length < length) { msg.copy(buf, length - msg.length); return buf; } return msg.slice(-length); } }; /** * Left Pads a `Buffer` with leading zeros till it has `length` bytes. * Or it truncates the beginning if it exceeds. * @param msg the value to pad (Buffer) * @param length the number of bytes the output should be * @return (Buffer) */ var setLengthLeft = function (msg, length) { (0, helpers_1.assertIsBuffer)(msg); return setLength(msg, length, false); }; exports.setLengthLeft = setLengthLeft; /** * Right Pads a `Buffer` with trailing zeros till it has `length` bytes. * it truncates the end if it exceeds. * @param msg the value to pad (Buffer) * @param length the number of bytes the output should be * @return (Buffer) */ var setLengthRight = function (msg, length) { (0, helpers_1.assertIsBuffer)(msg); return setLength(msg, length, true); }; exports.setLengthRight = setLengthRight; /** * Trims leading zeros from a `Buffer`, `String` or `Number[]`. * @param a (Buffer|Array|String) * @return (Buffer|Array|String) */ var stripZeros = function (a) { var first = a[0]; while (a.length > 0 && first.toString() === '0') { a = a.slice(1); first = a[0]; } return a; }; /** * Trims leading zeros from a `Buffer`. * @param a (Buffer) * @return (Buffer) */ var unpadBuffer = function (a) { (0, helpers_1.assertIsBuffer)(a); return stripZeros(a); }; exports.unpadBuffer = unpadBuffer; /** * Trims leading zeros from an `Array` (of numbers). * @param a (number[]) * @return (number[]) */ var unpadArray = function (a) { (0, helpers_1.assertIsArray)(a); return stripZeros(a); }; exports.unpadArray = unpadArray; /** * Trims leading zeros from a hex-prefixed `String`. * @param a (String) * @return (String) */ var unpadHexString = function (a) { (0, helpers_1.assertIsHexString)(a); a = (0, internal_1.stripHexPrefix)(a); return stripZeros(a); }; exports.unpadHexString = unpadHexString; /** * Attempts to turn a value into a `Buffer`. * Inputs supported: `Buffer`, `String` (hex-prefixed), `Number`, null/undefined, `BN` and other objects * with a `toArray()` or `toBuffer()` method. * @param v the value */ var toBuffer = function (v) { if (v === null || v === undefined) { return Buffer.allocUnsafe(0); } if (Buffer.isBuffer(v)) { return Buffer.from(v); } if (Array.isArray(v) || v instanceof Uint8Array) { return Buffer.from(v); } if (typeof v === 'string') { if (!(0, internal_1.isHexString)(v)) { throw new Error("Cannot convert string to buffer. toBuffer only supports 0x-prefixed hex strings and this string was given: " + v); } return Buffer.from((0, internal_1.padToEven)((0, internal_1.stripHexPrefix)(v)), 'hex'); } if (typeof v === 'number') { return (0, exports.intToBuffer)(v); } if (bn_js_1.default.isBN(v)) { return v.toArrayLike(Buffer); } if (v.toArray) { // converts a BN to a Buffer return Buffer.from(v.toArray()); } if (v.toBuffer) { return Buffer.from(v.toBuffer()); } throw new Error('invalid type'); }; exports.toBuffer = toBuffer; /** * Converts a `Buffer` to a `Number`. * @param buf `Buffer` object to convert * @throws If the input number exceeds 53 bits. */ var bufferToInt = function (buf) { return new bn_js_1.default((0, exports.toBuffer)(buf)).toNumber(); }; exports.bufferToInt = bufferToInt; /** * Converts a `Buffer` into a `0x`-prefixed hex `String`. * @param buf `Buffer` object to convert */ var bufferToHex = function (buf) { buf = (0, exports.toBuffer)(buf); return '0x' + buf.toString('hex'); }; exports.bufferToHex = bufferToHex; /** * Interprets a `Buffer` as a signed integer and returns a `BN`. Assumes 256-bit numbers. * @param num Signed integer value */ var fromSigned = function (num) { return new bn_js_1.default(num).fromTwos(256); }; exports.fromSigned = fromSigned; /** * Converts a `BN` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers. * @param num */ var toUnsigned = function (num) { return Buffer.from(num.toTwos(256).toArray()); }; exports.toUnsigned = toUnsigned; /** * Adds "0x" to a given `String` if it does not already start with "0x". */ var addHexPrefix = function (str) { if (typeof str !== 'string') { return str; } return (0, internal_1.isHexPrefixed)(str) ? str : '0x' + str; }; exports.addHexPrefix = addHexPrefix; /** * Returns the utf8 string representation from a hex string. * * Examples: * * Input 1: '657468657265756d000000000000000000000000000000000000000000000000' * Input 2: '657468657265756d' * Input 3: '000000000000000000000000000000000000000000000000657468657265756d' * * Output (all 3 input variants): 'ethereum' * * Note that this method is not intended to be used with hex strings * representing quantities in both big endian or little endian notation. * * @param string Hex string, should be `0x` prefixed * @return Utf8 string */ var toUtf8 = function (hex) { var zerosRegexp = /^(00)+|(00)+$/g; hex = (0, internal_1.stripHexPrefix)(hex); if (hex.length % 2 !== 0) { throw new Error('Invalid non-even hex string input for toUtf8() provided'); } var bufferVal = Buffer.from(hex.replace(zerosRegexp, ''), 'hex'); return bufferVal.toString('utf8'); }; exports.toUtf8 = toUtf8; /** * Converts a `Buffer` or `Array` to JSON. * @param ba (Buffer|Array) * @return (Array|String|null) */ var baToJSON = function (ba) { if (Buffer.isBuffer(ba)) { return "0x" + ba.toString('hex'); } else if (ba instanceof Array) { var array = []; for (var i = 0; i < ba.length; i++) { array.push((0, exports.baToJSON)(ba[i])); } return array; } }; exports.baToJSON = baToJSON; //# sourceMappingURL=bytes.js.map /***/ }), /***/ 31982: /*!************************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/constants.js ***! \************************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.KECCAK256_RLP = exports.KECCAK256_RLP_S = exports.KECCAK256_RLP_ARRAY = exports.KECCAK256_RLP_ARRAY_S = exports.KECCAK256_NULL = exports.KECCAK256_NULL_S = exports.TWO_POW256 = exports.MAX_INTEGER = void 0; var Buffer = __webpack_require__(/*! buffer */ 3875).Buffer; var bn_js_1 = __importDefault(__webpack_require__(/*! bn.js */ 66503)); /** * The max integer that this VM can handle */ exports.MAX_INTEGER = new bn_js_1.default('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16); /** * 2^256 */ exports.TWO_POW256 = new bn_js_1.default('10000000000000000000000000000000000000000000000000000000000000000', 16); /** * Keccak-256 hash of null */ exports.KECCAK256_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; /** * Keccak-256 hash of null */ exports.KECCAK256_NULL = Buffer.from(exports.KECCAK256_NULL_S, 'hex'); /** * Keccak-256 of an RLP of an empty array */ exports.KECCAK256_RLP_ARRAY_S = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'; /** * Keccak-256 of an RLP of an empty array */ exports.KECCAK256_RLP_ARRAY = Buffer.from(exports.KECCAK256_RLP_ARRAY_S, 'hex'); /** * Keccak-256 hash of the RLP of null */ exports.KECCAK256_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'; /** * Keccak-256 hash of the RLP of null */ exports.KECCAK256_RLP = Buffer.from(exports.KECCAK256_RLP_S, 'hex'); //# sourceMappingURL=constants.js.map /***/ }), /***/ 94010: /*!************************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/externals.js ***! \************************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /** * Re-exports commonly used modules: * * Exports [`BN`](https://github.com/indutny/bn.js), [`rlp`](https://github.com/ethereumjs/rlp). * @packageDocumentation */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.rlp = exports.BN = void 0; var bn_js_1 = __importDefault(__webpack_require__(/*! bn.js */ 66503)); exports.BN = bn_js_1.default; var rlp = __importStar(__webpack_require__(/*! rlp */ 78084)); exports.rlp = rlp; //# sourceMappingURL=externals.js.map /***/ }), /***/ 83989: /*!*******************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/hash.js ***! \*******************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.rlphash = exports.ripemd160FromArray = exports.ripemd160FromString = exports.ripemd160 = exports.sha256FromArray = exports.sha256FromString = exports.sha256 = exports.keccakFromArray = exports.keccakFromHexString = exports.keccakFromString = exports.keccak256 = exports.keccak = void 0; var keccak_1 = __webpack_require__(/*! ethereum-cryptography/keccak */ 55075); var createHash = __webpack_require__(/*! create-hash */ 12506); var rlp = __importStar(__webpack_require__(/*! rlp */ 78084)); var bytes_1 = __webpack_require__(/*! ./bytes */ 83643); var helpers_1 = __webpack_require__(/*! ./helpers */ 34087); /** * Creates Keccak hash of a Buffer input * @param a The input data (Buffer) * @param bits (number = 256) The Keccak width */ var keccak = function (a, bits) { if (bits === void 0) { bits = 256; } (0, helpers_1.assertIsBuffer)(a); switch (bits) { case 224: { return (0, keccak_1.keccak224)(a); } case 256: { return (0, keccak_1.keccak256)(a); } case 384: { return (0, keccak_1.keccak384)(a); } case 512: { return (0, keccak_1.keccak512)(a); } default: { throw new Error("Invald algorithm: keccak" + bits); } } }; exports.keccak = keccak; /** * Creates Keccak-256 hash of the input, alias for keccak(a, 256). * @param a The input data (Buffer) */ var keccak256 = function (a) { return (0, exports.keccak)(a); }; exports.keccak256 = keccak256; /** * Creates Keccak hash of a utf-8 string input * @param a The input data (String) * @param bits (number = 256) The Keccak width */ var keccakFromString = function (a, bits) { if (bits === void 0) { bits = 256; } (0, helpers_1.assertIsString)(a); var buf = Buffer.from(a, 'utf8'); return (0, exports.keccak)(buf, bits); }; exports.keccakFromString = keccakFromString; /** * Creates Keccak hash of an 0x-prefixed string input * @param a The input data (String) * @param bits (number = 256) The Keccak width */ var keccakFromHexString = function (a, bits) { if (bits === void 0) { bits = 256; } (0, helpers_1.assertIsHexString)(a); return (0, exports.keccak)((0, bytes_1.toBuffer)(a), bits); }; exports.keccakFromHexString = keccakFromHexString; /** * Creates Keccak hash of a number array input * @param a The input data (number[]) * @param bits (number = 256) The Keccak width */ var keccakFromArray = function (a, bits) { if (bits === void 0) { bits = 256; } (0, helpers_1.assertIsArray)(a); return (0, exports.keccak)((0, bytes_1.toBuffer)(a), bits); }; exports.keccakFromArray = keccakFromArray; /** * Creates SHA256 hash of an input. * @param a The input data (Buffer|Array|String) */ var _sha256 = function (a) { a = (0, bytes_1.toBuffer)(a); return createHash('sha256').update(a).digest(); }; /** * Creates SHA256 hash of a Buffer input. * @param a The input data (Buffer) */ var sha256 = function (a) { (0, helpers_1.assertIsBuffer)(a); return _sha256(a); }; exports.sha256 = sha256; /** * Creates SHA256 hash of a string input. * @param a The input data (string) */ var sha256FromString = function (a) { (0, helpers_1.assertIsString)(a); return _sha256(a); }; exports.sha256FromString = sha256FromString; /** * Creates SHA256 hash of a number[] input. * @param a The input data (number[]) */ var sha256FromArray = function (a) { (0, helpers_1.assertIsArray)(a); return _sha256(a); }; exports.sha256FromArray = sha256FromArray; /** * Creates RIPEMD160 hash of the input. * @param a The input data (Buffer|Array|String|Number) * @param padded Whether it should be padded to 256 bits or not */ var _ripemd160 = function (a, padded) { a = (0, bytes_1.toBuffer)(a); var hash = createHash('rmd160').update(a).digest(); if (padded === true) { return (0, bytes_1.setLengthLeft)(hash, 32); } else { return hash; } }; /** * Creates RIPEMD160 hash of a Buffer input. * @param a The input data (Buffer) * @param padded Whether it should be padded to 256 bits or not */ var ripemd160 = function (a, padded) { (0, helpers_1.assertIsBuffer)(a); return _ripemd160(a, padded); }; exports.ripemd160 = ripemd160; /** * Creates RIPEMD160 hash of a string input. * @param a The input data (String) * @param padded Whether it should be padded to 256 bits or not */ var ripemd160FromString = function (a, padded) { (0, helpers_1.assertIsString)(a); return _ripemd160(a, padded); }; exports.ripemd160FromString = ripemd160FromString; /** * Creates RIPEMD160 hash of a number[] input. * @param a The input data (number[]) * @param padded Whether it should be padded to 256 bits or not */ var ripemd160FromArray = function (a, padded) { (0, helpers_1.assertIsArray)(a); return _ripemd160(a, padded); }; exports.ripemd160FromArray = ripemd160FromArray; /** * Creates SHA-3 hash of the RLP encoded version of the input. * @param a The input data */ var rlphash = function (a) { return (0, exports.keccak)(rlp.encode(a)); }; exports.rlphash = rlphash; //# sourceMappingURL=hash.js.map /***/ }), /***/ 34087: /*!**********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/helpers.js ***! \**********************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.assertIsString = exports.assertIsArray = exports.assertIsBuffer = exports.assertIsHexString = void 0; var internal_1 = __webpack_require__(/*! ./internal */ 99671); /** * Throws if a string is not hex prefixed * @param {string} input string to check hex prefix of */ var assertIsHexString = function (input) { if (!(0, internal_1.isHexString)(input)) { var msg = "This method only supports 0x-prefixed hex strings but input was: " + input; throw new Error(msg); } }; exports.assertIsHexString = assertIsHexString; /** * Throws if input is not a buffer * @param {Buffer} input value to check */ var assertIsBuffer = function (input) { if (!Buffer.isBuffer(input)) { var msg = "This method only supports Buffer but input was: " + input; throw new Error(msg); } }; exports.assertIsBuffer = assertIsBuffer; /** * Throws if input is not an array * @param {number[]} input value to check */ var assertIsArray = function (input) { if (!Array.isArray(input)) { var msg = "This method only supports number arrays but input was: " + input; throw new Error(msg); } }; exports.assertIsArray = assertIsArray; /** * Throws if input is not a string * @param {string} input value to check */ var assertIsString = function (input) { if (typeof input !== 'string') { var msg = "This method only supports strings but input was: " + input; throw new Error(msg); } }; exports.assertIsString = assertIsString; //# sourceMappingURL=helpers.js.map /***/ }), /***/ 34692: /*!********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/index.js ***! \********************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isHexString = exports.getKeys = exports.fromAscii = exports.fromUtf8 = exports.toAscii = exports.arrayContainsArray = exports.getBinarySize = exports.padToEven = exports.stripHexPrefix = exports.isHexPrefixed = void 0; /** * Constants */ __exportStar(__webpack_require__(/*! ./constants */ 31982), exports); /** * Account class and helper functions */ __exportStar(__webpack_require__(/*! ./account */ 43149), exports); /** * Address type */ __exportStar(__webpack_require__(/*! ./address */ 75221), exports); /** * Hash functions */ __exportStar(__webpack_require__(/*! ./hash */ 83989), exports); /** * ECDSA signature */ __exportStar(__webpack_require__(/*! ./signature */ 6889), exports); /** * Utilities for manipulating Buffers, byte arrays, etc. */ __exportStar(__webpack_require__(/*! ./bytes */ 83643), exports); /** * Function for definining properties on an object */ __exportStar(__webpack_require__(/*! ./object */ 64982), exports); /** * External exports (BN, rlp, secp256k1) */ __exportStar(__webpack_require__(/*! ./externals */ 94010), exports); /** * Helpful TypeScript types */ __exportStar(__webpack_require__(/*! ./types */ 83554), exports); /** * Export ethjs-util methods */ var internal_1 = __webpack_require__(/*! ./internal */ 99671); Object.defineProperty(exports, "isHexPrefixed", ({ enumerable: true, get: function () { return internal_1.isHexPrefixed; } })); Object.defineProperty(exports, "stripHexPrefix", ({ enumerable: true, get: function () { return internal_1.stripHexPrefix; } })); Object.defineProperty(exports, "padToEven", ({ enumerable: true, get: function () { return internal_1.padToEven; } })); Object.defineProperty(exports, "getBinarySize", ({ enumerable: true, get: function () { return internal_1.getBinarySize; } })); Object.defineProperty(exports, "arrayContainsArray", ({ enumerable: true, get: function () { return internal_1.arrayContainsArray; } })); Object.defineProperty(exports, "toAscii", ({ enumerable: true, get: function () { return internal_1.toAscii; } })); Object.defineProperty(exports, "fromUtf8", ({ enumerable: true, get: function () { return internal_1.fromUtf8; } })); Object.defineProperty(exports, "fromAscii", ({ enumerable: true, get: function () { return internal_1.fromAscii; } })); Object.defineProperty(exports, "getKeys", ({ enumerable: true, get: function () { return internal_1.getKeys; } })); Object.defineProperty(exports, "isHexString", ({ enumerable: true, get: function () { return internal_1.isHexString; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 99671: /*!***********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/internal.js ***! \***********************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; /* The MIT License Copyright (c) 2016 Nick Dodson. nickdodson.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isHexString = exports.getKeys = exports.fromAscii = exports.fromUtf8 = exports.toAscii = exports.arrayContainsArray = exports.getBinarySize = exports.padToEven = exports.stripHexPrefix = exports.isHexPrefixed = void 0; /** * Returns a `Boolean` on whether or not the a `String` starts with '0x' * @param str the string input value * @return a boolean if it is or is not hex prefixed * @throws if the str input is not a string */ function isHexPrefixed(str) { if (typeof str !== 'string') { throw new Error("[isHexPrefixed] input must be type 'string', received type " + typeof str); } return str[0] === '0' && str[1] === 'x'; } exports.isHexPrefixed = isHexPrefixed; /** * Removes '0x' from a given `String` if present * @param str the string value * @returns the string without 0x prefix */ var stripHexPrefix = function (str) { if (typeof str !== 'string') throw new Error("[stripHexPrefix] input must be type 'string', received " + typeof str); return isHexPrefixed(str) ? str.slice(2) : str; }; exports.stripHexPrefix = stripHexPrefix; /** * Pads a `String` to have an even length * @param value * @return output */ function padToEven(value) { var a = value; if (typeof a !== 'string') { throw new Error("[padToEven] value must be type 'string', received " + typeof a); } if (a.length % 2) a = "0" + a; return a; } exports.padToEven = padToEven; /** * Get the binary size of a string * @param str * @returns the number of bytes contained within the string */ function getBinarySize(str) { if (typeof str !== 'string') { throw new Error("[getBinarySize] method requires input type 'string', recieved " + typeof str); } return Buffer.byteLength(str, 'utf8'); } exports.getBinarySize = getBinarySize; /** * Returns TRUE if the first specified array contains all elements * from the second one. FALSE otherwise. * * @param superset * @param subset * */ function arrayContainsArray(superset, subset, some) { if (Array.isArray(superset) !== true) { throw new Error("[arrayContainsArray] method requires input 'superset' to be an array, got type '" + typeof superset + "'"); } if (Array.isArray(subset) !== true) { throw new Error("[arrayContainsArray] method requires input 'subset' to be an array, got type '" + typeof subset + "'"); } return subset[some ? 'some' : 'every'](function (value) { return superset.indexOf(value) >= 0; }); } exports.arrayContainsArray = arrayContainsArray; /** * Should be called to get ascii from its hex representation * * @param string in hex * @returns ascii string representation of hex value */ function toAscii(hex) { var str = ''; var i = 0; var l = hex.length; if (hex.substring(0, 2) === '0x') i = 2; for (; i < l; i += 2) { var code = parseInt(hex.substr(i, 2), 16); str += String.fromCharCode(code); } return str; } exports.toAscii = toAscii; /** * Should be called to get hex representation (prefixed by 0x) of utf8 string * * @param string * @param optional padding * @returns hex representation of input string */ function fromUtf8(stringValue) { var str = Buffer.from(stringValue, 'utf8'); return "0x" + padToEven(str.toString('hex')).replace(/^0+|0+$/g, ''); } exports.fromUtf8 = fromUtf8; /** * Should be called to get hex representation (prefixed by 0x) of ascii string * * @param string * @param optional padding * @returns hex representation of input string */ function fromAscii(stringValue) { var hex = ''; for (var i = 0; i < stringValue.length; i++) { var code = stringValue.charCodeAt(i); var n = code.toString(16); hex += n.length < 2 ? "0" + n : n; } return "0x" + hex; } exports.fromAscii = fromAscii; /** * Returns the keys from an array of objects. * @example * ```js * getKeys([{a: '1', b: '2'}, {a: '3', b: '4'}], 'a') => ['1', '3'] *```` * @param params * @param key * @param allowEmpty * @returns output just a simple array of output keys */ function getKeys(params, key, allowEmpty) { if (!Array.isArray(params)) { throw new Error("[getKeys] method expects input 'params' to be an array, got " + typeof params); } if (typeof key !== 'string') { throw new Error("[getKeys] method expects input 'key' to be type 'string', got " + typeof params); } var result = []; for (var i = 0; i < params.length; i++) { var value = params[i][key]; if (allowEmpty && !value) { value = ''; } else if (typeof value !== 'string') { throw new Error("invalid abi - expected type 'string', received " + typeof value); } result.push(value); } return result; } exports.getKeys = getKeys; /** * Is the string a hex string. * * @param value * @param length * @returns output the string is a hex string */ function isHexString(value, length) { if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) return false; if (length && value.length !== 2 + 2 * length) return false; return true; } exports.isHexString = isHexString; //# sourceMappingURL=internal.js.map /***/ }), /***/ 64982: /*!*********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/object.js ***! \*********************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defineProperties = void 0; var assert_1 = __importDefault(__webpack_require__(/*! assert */ 80469)); var internal_1 = __webpack_require__(/*! ./internal */ 99671); var rlp = __importStar(__webpack_require__(/*! rlp */ 78084)); var bytes_1 = __webpack_require__(/*! ./bytes */ 83643); /** * Defines properties on a `Object`. It make the assumption that underlying data is binary. * @param self the `Object` to define properties on * @param fields an array fields to define. Fields can contain: * * `name` - the name of the properties * * `length` - the number of bytes the field can have * * `allowLess` - if the field can be less than the length * * `allowEmpty` * @param data data to be validated against the definitions * @deprecated */ var defineProperties = function (self, fields, data) { self.raw = []; self._fields = []; // attach the `toJSON` self.toJSON = function (label) { if (label === void 0) { label = false; } if (label) { var obj_1 = {}; self._fields.forEach(function (field) { obj_1[field] = "0x" + self[field].toString('hex'); }); return obj_1; } return (0, bytes_1.baToJSON)(self.raw); }; self.serialize = function serialize() { return rlp.encode(self.raw); }; fields.forEach(function (field, i) { self._fields.push(field.name); function getter() { return self.raw[i]; } function setter(v) { v = (0, bytes_1.toBuffer)(v); if (v.toString('hex') === '00' && !field.allowZero) { v = Buffer.allocUnsafe(0); } if (field.allowLess && field.length) { v = (0, bytes_1.unpadBuffer)(v); (0, assert_1.default)(field.length >= v.length, "The field " + field.name + " must not have more " + field.length + " bytes"); } else if (!(field.allowZero && v.length === 0) && field.length) { (0, assert_1.default)(field.length === v.length, "The field " + field.name + " must have byte length of " + field.length); } self.raw[i] = v; } Object.defineProperty(self, field.name, { enumerable: true, configurable: true, get: getter, set: setter, }); if (field.default) { self[field.name] = field.default; } // attach alias if (field.alias) { Object.defineProperty(self, field.alias, { enumerable: false, configurable: true, set: setter, get: getter, }); } }); // if the constuctor is passed data if (data) { if (typeof data === 'string') { data = Buffer.from((0, internal_1.stripHexPrefix)(data), 'hex'); } if (Buffer.isBuffer(data)) { data = rlp.decode(data); } if (Array.isArray(data)) { if (data.length > self._fields.length) { throw new Error('wrong number of fields in data'); } // make sure all the items are buffers data.forEach(function (d, i) { self[self._fields[i]] = (0, bytes_1.toBuffer)(d); }); } else if (typeof data === 'object') { var keys_1 = Object.keys(data); fields.forEach(function (field) { if (keys_1.indexOf(field.name) !== -1) self[field.name] = data[field.name]; if (keys_1.indexOf(field.alias) !== -1) self[field.alias] = data[field.alias]; }); } else { throw new Error('invalid data'); } } }; exports.defineProperties = defineProperties; //# sourceMappingURL=object.js.map /***/ }), /***/ 6889: /*!************************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/signature.js ***! \************************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.hashPersonalMessage = exports.isValidSignature = exports.fromRpcSig = exports.toCompactSig = exports.toRpcSig = exports.ecrecover = exports.ecsign = void 0; var secp256k1_1 = __webpack_require__(/*! ethereum-cryptography/secp256k1 */ 10019); var bn_js_1 = __importDefault(__webpack_require__(/*! bn.js */ 66503)); var bytes_1 = __webpack_require__(/*! ./bytes */ 83643); var hash_1 = __webpack_require__(/*! ./hash */ 83989); var helpers_1 = __webpack_require__(/*! ./helpers */ 34087); var types_1 = __webpack_require__(/*! ./types */ 83554); function ecsign(msgHash, privateKey, chainId) { var _a = (0, secp256k1_1.ecdsaSign)(msgHash, privateKey), signature = _a.signature, recovery = _a.recid; var r = Buffer.from(signature.slice(0, 32)); var s = Buffer.from(signature.slice(32, 64)); if (!chainId || typeof chainId === 'number') { // return legacy type ECDSASignature (deprecated in favor of ECDSASignatureBuffer to handle large chainIds) if (chainId && !Number.isSafeInteger(chainId)) { throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative input type)'); } var v_1 = chainId ? recovery + (chainId * 2 + 35) : recovery + 27; return { r: r, s: s, v: v_1 }; } var chainIdBN = (0, types_1.toType)(chainId, types_1.TypeOutput.BN); var v = chainIdBN.muln(2).addn(35).addn(recovery).toArrayLike(Buffer); return { r: r, s: s, v: v }; } exports.ecsign = ecsign; function calculateSigRecovery(v, chainId) { var vBN = (0, types_1.toType)(v, types_1.TypeOutput.BN); if (!chainId) { return vBN.subn(27); } var chainIdBN = (0, types_1.toType)(chainId, types_1.TypeOutput.BN); return vBN.sub(chainIdBN.muln(2).addn(35)); } function isValidSigRecovery(recovery) { var rec = new bn_js_1.default(recovery); return rec.eqn(0) || rec.eqn(1); } /** * ECDSA public key recovery from signature. * @returns Recovered public key */ var ecrecover = function (msgHash, v, r, s, chainId) { var signature = Buffer.concat([(0, bytes_1.setLengthLeft)(r, 32), (0, bytes_1.setLengthLeft)(s, 32)], 64); var recovery = calculateSigRecovery(v, chainId); if (!isValidSigRecovery(recovery)) { throw new Error('Invalid signature v value'); } var senderPubKey = (0, secp256k1_1.ecdsaRecover)(signature, recovery.toNumber(), msgHash); return Buffer.from((0, secp256k1_1.publicKeyConvert)(senderPubKey, false).slice(1)); }; exports.ecrecover = ecrecover; /** * Convert signature parameters into the format of `eth_sign` RPC method. * @returns Signature */ var toRpcSig = function (v, r, s, chainId) { var recovery = calculateSigRecovery(v, chainId); if (!isValidSigRecovery(recovery)) { throw new Error('Invalid signature v value'); } // geth (and the RPC eth_sign method) uses the 65 byte format used by Bitcoin return (0, bytes_1.bufferToHex)(Buffer.concat([(0, bytes_1.setLengthLeft)(r, 32), (0, bytes_1.setLengthLeft)(s, 32), (0, bytes_1.toBuffer)(v)])); }; exports.toRpcSig = toRpcSig; /** * Convert signature parameters into the format of Compact Signature Representation (EIP-2098). * @returns Signature */ var toCompactSig = function (v, r, s, chainId) { var recovery = calculateSigRecovery(v, chainId); if (!isValidSigRecovery(recovery)) { throw new Error('Invalid signature v value'); } var vn = (0, types_1.toType)(v, types_1.TypeOutput.Number); var ss = s; if ((vn > 28 && vn % 2 === 1) || vn === 1 || vn === 28) { ss = Buffer.from(s); ss[0] |= 0x80; } return (0, bytes_1.bufferToHex)(Buffer.concat([(0, bytes_1.setLengthLeft)(r, 32), (0, bytes_1.setLengthLeft)(ss, 32)])); }; exports.toCompactSig = toCompactSig; /** * Convert signature format of the `eth_sign` RPC method to signature parameters * NOTE: all because of a bug in geth: https://github.com/ethereum/go-ethereum/issues/2053 */ var fromRpcSig = function (sig) { var buf = (0, bytes_1.toBuffer)(sig); var r; var s; var v; if (buf.length >= 65) { r = buf.slice(0, 32); s = buf.slice(32, 64); v = (0, bytes_1.bufferToInt)(buf.slice(64)); } else if (buf.length === 64) { // Compact Signature Representation (https://eips.ethereum.org/EIPS/eip-2098) r = buf.slice(0, 32); s = buf.slice(32, 64); v = (0, bytes_1.bufferToInt)(buf.slice(32, 33)) >> 7; s[0] &= 0x7f; } else { throw new Error('Invalid signature length'); } // support both versions of `eth_sign` responses if (v < 27) { v += 27; } return { v: v, r: r, s: s, }; }; exports.fromRpcSig = fromRpcSig; /** * Validate a ECDSA signature. * @param homesteadOrLater Indicates whether this is being used on either the homestead hardfork or a later one */ var isValidSignature = function (v, r, s, homesteadOrLater, chainId) { if (homesteadOrLater === void 0) { homesteadOrLater = true; } var SECP256K1_N_DIV_2 = new bn_js_1.default('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16); var SECP256K1_N = new bn_js_1.default('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 16); if (r.length !== 32 || s.length !== 32) { return false; } if (!isValidSigRecovery(calculateSigRecovery(v, chainId))) { return false; } var rBN = new bn_js_1.default(r); var sBN = new bn_js_1.default(s); if (rBN.isZero() || rBN.gt(SECP256K1_N) || sBN.isZero() || sBN.gt(SECP256K1_N)) { return false; } if (homesteadOrLater && sBN.cmp(SECP256K1_N_DIV_2) === 1) { return false; } return true; }; exports.isValidSignature = isValidSignature; /** * Returns the keccak-256 hash of `message`, prefixed with the header used by the `eth_sign` RPC call. * The output of this function can be fed into `ecsign` to produce the same signature as the `eth_sign` * call for a given `message`, or fed to `ecrecover` along with a signature to recover the public key * used to produce the signature. */ var hashPersonalMessage = function (message) { (0, helpers_1.assertIsBuffer)(message); var prefix = Buffer.from("\u0019Ethereum Signed Message:\n" + message.length, 'utf-8'); return (0, hash_1.keccak)(Buffer.concat([prefix, message])); }; exports.hashPersonalMessage = hashPersonalMessage; //# sourceMappingURL=signature.js.map /***/ }), /***/ 83554: /*!********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/dist.browser/types.js ***! \********************************************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toType = exports.TypeOutput = exports.bnToRlp = exports.bnToUnpaddedBuffer = exports.bnToHex = void 0; var bn_js_1 = __importDefault(__webpack_require__(/*! bn.js */ 66503)); var internal_1 = __webpack_require__(/*! ./internal */ 99671); var bytes_1 = __webpack_require__(/*! ./bytes */ 83643); /** * Convert BN to 0x-prefixed hex string. */ function bnToHex(value) { return "0x" + value.toString(16); } exports.bnToHex = bnToHex; /** * Convert value from BN to an unpadded Buffer * (useful for RLP transport) * @param value value to convert */ function bnToUnpaddedBuffer(value) { // Using `bn.toArrayLike(Buffer)` instead of `bn.toBuffer()` // for compatibility with browserify and similar tools return (0, bytes_1.unpadBuffer)(value.toArrayLike(Buffer)); } exports.bnToUnpaddedBuffer = bnToUnpaddedBuffer; /** * Deprecated alias for {@link bnToUnpaddedBuffer} * @deprecated */ function bnToRlp(value) { return bnToUnpaddedBuffer(value); } exports.bnToRlp = bnToRlp; /** * Type output options */ var TypeOutput; (function (TypeOutput) { TypeOutput[TypeOutput["Number"] = 0] = "Number"; TypeOutput[TypeOutput["BN"] = 1] = "BN"; TypeOutput[TypeOutput["Buffer"] = 2] = "Buffer"; TypeOutput[TypeOutput["PrefixedHexString"] = 3] = "PrefixedHexString"; })(TypeOutput = exports.TypeOutput || (exports.TypeOutput = {})); function toType(input, outputType) { if (input === null) { return null; } if (input === undefined) { return undefined; } if (typeof input === 'string' && !(0, internal_1.isHexString)(input)) { throw new Error("A string must be provided with a 0x-prefix, given: " + input); } else if (typeof input === 'number' && !Number.isSafeInteger(input)) { throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative input type)'); } var output = (0, bytes_1.toBuffer)(input); if (outputType === TypeOutput.Buffer) { return output; } else if (outputType === TypeOutput.BN) { return new bn_js_1.default(output); } else if (outputType === TypeOutput.Number) { var bn = new bn_js_1.default(output); var max = new bn_js_1.default(Number.MAX_SAFE_INTEGER.toString()); if (bn.gt(max)) { throw new Error('The provided number is greater than MAX_SAFE_INTEGER (please use an alternative output type)'); } return bn.toNumber(); } else { // outputType === TypeOutput.PrefixedHexString return "0x" + output.toString('hex'); } } exports.toType = toType; //# sourceMappingURL=types.js.map /***/ }), /***/ 66503: /*!***************************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/ethereumjs-util/node_modules/bn.js/lib/bn.js ***! \***************************************************************************************************/ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); (function (module, exports) { 'use strict'; // Utils function assert (val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits (ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } // BN function BN (number, base, endian) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (typeof module === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { Buffer = window.Buffer; } else { Buffer = __webpack_require__(/*! buffer */ 91585).Buffer; } } catch (e) { } BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } if (typeof number === 'object') { return this._initArray(number, base, endian); } if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; this.negative = 1; } if (start < number.length) { if (base === 16) { this._parseHex(number, start, endian); } else { this._parseBase(number, base, start); if (endian === 'le') { this._initArray(this.toArray(), base, endian); } } } }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [number & 0x3ffffff]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [0]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this._strip(); }; function parseHex4Bits (string, index) { var c = string.charCodeAt(index); // '0' - '9' if (c >= 48 && c <= 57) { return c - 48; // 'A' - 'F' } else if (c >= 65 && c <= 70) { return c - 55; // 'a' - 'f' } else if (c >= 97 && c <= 102) { return c - 87; } else { assert(false, 'Invalid character in ' + string); } } function parseHexByte (string, lowerBound, index) { var r = parseHex4Bits(string, index); if (index - 1 >= lowerBound) { r |= parseHex4Bits(string, index - 1) << 4; } return r; } BN.prototype._parseHex = function _parseHex (number, start, endian) { // Create possibly bigger array to ensure that it fits the number this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } // 24-bits chunks var off = 0; var j = 0; var w; if (endian === 'be') { for (i = number.length - 1; i >= start; i -= 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } else { var parseLength = number.length - start; for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } this._strip(); }; function parseBase (str, start, end, mul) { var r = 0; var b = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { b = c - 49 + 0xa; // 'A' } else if (c >= 17) { b = c - 17 + 0xa; // '0' - '9' } else { b = c; } assert(c >= 0 && b < mul, 'Invalid character'); r += b; } return r; } BN.prototype._parseBase = function _parseBase (number, base, start) { // Initialize as zero this.words = [0]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = (limbPow / base) | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } this._strip(); }; BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; function move (dest, src) { dest.words = src.words; dest.length = src.length; dest.negative = src.negative; dest.red = src.red; } BN.prototype._move = function _move (dest) { move(dest, this); }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype._strip = function strip () { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; // Check Symbol.for because not everywhere where Symbol defined // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') { try { BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect; } catch (e) { BN.prototype.inspect = inspect; } } else { BN.prototype.inspect = inspect; } function inspect () { return (this.red ? ''; } /* var zeros = []; var groupSizes = []; var groupBases = []; var s = ''; var i = -1; while (++i < BN.wordSize) { zeros[i] = s; s += '0'; } groupSizes[0] = 0; groupSizes[1] = 0; groupBases[0] = 0; groupBases[1] = 0; var base = 2 - 1; while (++base < 36 + 1) { var groupSize = 0; var groupBase = 1; while (groupBase < (1 << BN.wordSize) / base) { groupBase *= base; groupSize += 1; } groupSizes[base] = groupSize; groupBases[base] = groupBase; } */ var zeros = [ '', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000' ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN.prototype.toString = function toString (base, padding) { base = base || 10; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; var carry = 0; for (var i = 0; i < this.length; i++) { var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (24 - off)) & 0xffffff; if (carry !== 0 || i !== this.length - 1) { out = zeros[6 - word.length] + word + out; } else { out = word + out; } off += 2; if (off >= 26) { off -= 26; i--; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } if (base === (base | 0) && base >= 2 && base <= 36) { // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); var groupBase = groupBases[base]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modrn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber () { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + (this.words[1] * 0x4000000); } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return (this.negative !== 0) ? -ret : ret; }; BN.prototype.toJSON = function toJSON () { return this.toString(16, 2); }; if (Buffer) { BN.prototype.toBuffer = function toBuffer (endian, length) { return this.toArrayLike(Buffer, endian, length); }; } BN.prototype.toArray = function toArray (endian, length) { return this.toArrayLike(Array, endian, length); }; var allocate = function allocate (ArrayType, size) { if (ArrayType.allocUnsafe) { return ArrayType.allocUnsafe(size); } return new ArrayType(size); }; BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { this._strip(); var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); var res = allocate(ArrayType, reqLength); var postfix = endian === 'le' ? 'LE' : 'BE'; this['_toArrayLike' + postfix](res, byteLength); return res; }; BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) { var position = 0; var carry = 0; for (var i = 0, shift = 0; i < this.length; i++) { var word = (this.words[i] << shift) | carry; res[position++] = word & 0xff; if (position < res.length) { res[position++] = (word >> 8) & 0xff; } if (position < res.length) { res[position++] = (word >> 16) & 0xff; } if (shift === 6) { if (position < res.length) { res[position++] = (word >> 24) & 0xff; } carry = 0; shift = 0; } else { carry = word >>> 24; shift += 2; } } if (position < res.length) { res[position++] = carry; while (position < res.length) { res[position++] = 0; } } }; BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) { var position = res.length - 1; var carry = 0; for (var i = 0, shift = 0; i < this.length; i++) { var word = (this.words[i] << shift) | carry; res[position--] = word & 0xff; if (position >= 0) { res[position--] = (word >> 8) & 0xff; } if (position >= 0) { res[position--] = (word >> 16) & 0xff; } if (shift === 6) { if (position >= 0) { res[position--] = (word >> 24) & 0xff; } carry = 0; shift = 0; } else { carry = word >>> 24; shift += 2; } } if (position >= 0) { res[position--] = carry; while (position >= 0) { res[position--] = 0; } } }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits (w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength () { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray (num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] >>> wbit) & 0x01; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits () { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this._strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor (num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand (num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this._strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand (num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor (num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this._strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor (num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn (width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } // And remove leading zeroes return this._strip(); }; BN.prototype.notn = function notn (width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn (bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = (bit / 26) | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | (1 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this._strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; // Copy the rest of the words } else if (a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add (num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub (num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this._strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = carry >>> 26; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = (k - j) | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += (r / 0x4000000) | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out._strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo (self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = (mid + Math.imul(ah0, bl0)) | 0; hi = Math.imul(ah0, bh0); var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = (mid + Math.imul(ah1, bl0)) | 0; hi = Math.imul(ah1, bh0); lo = (lo + Math.imul(al0, bl1)) | 0; mid = (mid + Math.imul(al0, bh1)) | 0; mid = (mid + Math.imul(ah0, bl1)) | 0; hi = (hi + Math.imul(ah0, bh1)) | 0; var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = (mid + Math.imul(ah2, bl0)) | 0; hi = Math.imul(ah2, bh0); lo = (lo + Math.imul(al1, bl1)) | 0; mid = (mid + Math.imul(al1, bh1)) | 0; mid = (mid + Math.imul(ah1, bl1)) | 0; hi = (hi + Math.imul(ah1, bh1)) | 0; lo = (lo + Math.imul(al0, bl2)) | 0; mid = (mid + Math.imul(al0, bh2)) | 0; mid = (mid + Math.imul(ah0, bl2)) | 0; hi = (hi + Math.imul(ah0, bh2)) | 0; var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = (mid + Math.imul(ah3, bl0)) | 0; hi = Math.imul(ah3, bh0); lo = (lo + Math.imul(al2, bl1)) | 0; mid = (mid + Math.imul(al2, bh1)) | 0; mid = (mid + Math.imul(ah2, bl1)) | 0; hi = (hi + Math.imul(ah2, bh1)) | 0; lo = (lo + Math.imul(al1, bl2)) | 0; mid = (mid + Math.imul(al1, bh2)) | 0; mid = (mid + Math.imul(ah1, bl2)) | 0; hi = (hi + Math.imul(ah1, bh2)) | 0; lo = (lo + Math.imul(al0, bl3)) | 0; mid = (mid + Math.imul(al0, bh3)) | 0; mid = (mid + Math.imul(ah0, bl3)) | 0; hi = (hi + Math.imul(ah0, bh3)) | 0; var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = (mid + Math.imul(ah4, bl0)) | 0; hi = Math.imul(ah4, bh0); lo = (lo + Math.imul(al3, bl1)) | 0; mid = (mid + Math.imul(al3, bh1)) | 0; mid = (mid + Math.imul(ah3, bl1)) | 0; hi = (hi + Math.imul(ah3, bh1)) | 0; lo = (lo + Math.imul(al2, bl2)) | 0; mid = (mid + Math.imul(al2, bh2)) | 0; mid = (mid + Math.imul(ah2, bl2)) | 0; hi = (hi + Math.imul(ah2, bh2)) | 0; lo = (lo + Math.imul(al1, bl3)) | 0; mid = (mid + Math.imul(al1, bh3)) | 0; mid = (mid + Math.imul(ah1, bl3)) | 0; hi = (hi + Math.imul(ah1, bh3)) | 0; lo = (lo + Math.imul(al0, bl4)) | 0; mid = (mid + Math.imul(al0, bh4)) | 0; mid = (mid + Math.imul(ah0, bl4)) | 0; hi = (hi + Math.imul(ah0, bh4)) | 0; var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = (mid + Math.imul(ah5, bl0)) | 0; hi = Math.imul(ah5, bh0); lo = (lo + Math.imul(al4, bl1)) | 0; mid = (mid + Math.imul(al4, bh1)) | 0; mid = (mid + Math.imul(ah4, bl1)) | 0; hi = (hi + Math.imul(ah4, bh1)) | 0; lo = (lo + Math.imul(al3, bl2)) | 0; mid = (mid + Math.imul(al3, bh2)) | 0; mid = (mid + Math.imul(ah3, bl2)) | 0; hi = (hi + Math.imul(ah3, bh2)) | 0; lo = (lo + Math.imul(al2, bl3)) | 0; mid = (mid + Math.imul(al2, bh3)) | 0; mid = (mid + Math.imul(ah2, bl3)) | 0; hi = (hi + Math.imul(ah2, bh3)) | 0; lo = (lo + Math.imul(al1, bl4)) | 0; mid = (mid + Math.imul(al1, bh4)) | 0; mid = (mid + Math.imul(ah1, bl4)) | 0; hi = (hi + Math.imul(ah1, bh4)) | 0; lo = (lo + Math.imul(al0, bl5)) | 0; mid = (mid + Math.imul(al0, bh5)) | 0; mid = (mid + Math.imul(ah0, bl5)) | 0; hi = (hi + Math.imul(ah0, bh5)) | 0; var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = (mid + Math.imul(ah6, bl0)) | 0; hi = Math.imul(ah6, bh0); lo = (lo + Math.imul(al5, bl1)) | 0; mid = (mid + Math.imul(al5, bh1)) | 0; mid = (mid + Math.imul(ah5, bl1)) | 0; hi = (hi + Math.imul(ah5, bh1)) | 0; lo = (lo + Math.imul(al4, bl2)) | 0; mid = (mid + Math.imul(al4, bh2)) | 0; mid = (mid + Math.imul(ah4, bl2)) | 0; hi = (hi + Math.imul(ah4, bh2)) | 0; lo = (lo + Math.imul(al3, bl3)) | 0; mid = (mid + Math.imul(al3, bh3)) | 0; mid = (mid + Math.imul(ah3, bl3)) | 0; hi = (hi + Math.imul(ah3, bh3)) | 0; lo = (lo + Math.imul(al2, bl4)) | 0; mid = (mid + Math.imul(al2, bh4)) | 0; mid = (mid + Math.imul(ah2, bl4)) | 0; hi = (hi + Math.imul(ah2, bh4)) | 0; lo = (lo + Math.imul(al1, bl5)) | 0; mid = (mid + Math.imul(al1, bh5)) | 0; mid = (mid + Math.imul(ah1, bl5)) | 0; hi = (hi + Math.imul(ah1, bh5)) | 0; lo = (lo + Math.imul(al0, bl6)) | 0; mid = (mid + Math.imul(al0, bh6)) | 0; mid = (mid + Math.imul(ah0, bl6)) | 0; hi = (hi + Math.imul(ah0, bh6)) | 0; var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = (mid + Math.imul(ah7, bl0)) | 0; hi = Math.imul(ah7, bh0); lo = (lo + Math.imul(al6, bl1)) | 0; mid = (mid + Math.imul(al6, bh1)) | 0; mid = (mid + Math.imul(ah6, bl1)) | 0; hi = (hi + Math.imul(ah6, bh1)) | 0; lo = (lo + Math.imul(al5, bl2)) | 0; mid = (mid + Math.imul(al5, bh2)) | 0; mid = (mid + Math.imul(ah5, bl2)) | 0; hi = (hi + Math.imul(ah5, bh2)) | 0; lo = (lo + Math.imul(al4, bl3)) | 0; mid = (mid + Math.imul(al4, bh3)) | 0; mid = (mid + Math.imul(ah4, bl3)) | 0; hi = (hi + Math.imul(ah4, bh3)) | 0; lo = (lo + Math.imul(al3, bl4)) | 0; mid = (mid + Math.imul(al3, bh4)) | 0; mid = (mid + Math.imul(ah3, bl4)) | 0; hi = (hi + Math.imul(ah3, bh4)) | 0; lo = (lo + Math.imul(al2, bl5)) | 0; mid = (mid + Math.imul(al2, bh5)) | 0; mid = (mid + Math.imul(ah2, bl5)) | 0; hi = (hi + Math.imul(ah2, bh5)) | 0; lo = (lo + Math.imul(al1, bl6)) | 0; mid = (mid + Math.imul(al1, bh6)) | 0; mid = (mid + Math.imul(ah1, bl6)) | 0; hi = (hi + Math.imul(ah1, bh6)) | 0; lo = (lo + Math.imul(al0, bl7)) | 0; mid = (mid + Math.imul(al0, bh7)) | 0; mid = (mid + Math.imul(ah0, bl7)) | 0; hi = (hi + Math.imul(ah0, bh7)) | 0; var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = (mid + Math.imul(ah8, bl0)) | 0; hi = Math.imul(ah8, bh0); lo = (lo + Math.imul(al7, bl1)) | 0; mid = (mid + Math.imul(al7, bh1)) | 0; mid = (mid + Math.imul(ah7, bl1)) | 0; hi = (hi + Math.imul(ah7, bh1)) | 0; lo = (lo + Math.imul(al6, bl2)) | 0; mid = (mid + Math.imul(al6, bh2)) | 0; mid = (mid + Math.imul(ah6, bl2)) | 0; hi = (hi + Math.imul(ah6, bh2)) | 0; lo = (lo + Math.imul(al5, bl3)) | 0; mid = (mid + Math.imul(al5, bh3)) | 0; mid = (mid + Math.imul(ah5, bl3)) | 0; hi = (hi + Math.imul(ah5, bh3)) | 0; lo = (lo + Math.imul(al4, bl4)) | 0; mid = (mid + Math.imul(al4, bh4)) | 0; mid = (mid + Math.imul(ah4, bl4)) | 0; hi = (hi + Math.imul(ah4, bh4)) | 0; lo = (lo + Math.imul(al3, bl5)) | 0; mid = (mid + Math.imul(al3, bh5)) | 0; mid = (mid + Math.imul(ah3, bl5)) | 0; hi = (hi + Math.imul(ah3, bh5)) | 0; lo = (lo + Math.imul(al2, bl6)) | 0; mid = (mid + Math.imul(al2, bh6)) | 0; mid = (mid + Math.imul(ah2, bl6)) | 0; hi = (hi + Math.imul(ah2, bh6)) | 0; lo = (lo + Math.imul(al1, bl7)) | 0; mid = (mid + Math.imul(al1, bh7)) | 0; mid = (mid + Math.imul(ah1, bl7)) | 0; hi = (hi + Math.imul(ah1, bh7)) | 0; lo = (lo + Math.imul(al0, bl8)) | 0; mid = (mid + Math.imul(al0, bh8)) | 0; mid = (mid + Math.imul(ah0, bl8)) | 0; hi = (hi + Math.imul(ah0, bh8)) | 0; var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = (mid + Math.imul(ah9, bl0)) | 0; hi = Math.imul(ah9, bh0); lo = (lo + Math.imul(al8, bl1)) | 0; mid = (mid + Math.imul(al8, bh1)) | 0; mid = (mid + Math.imul(ah8, bl1)) | 0; hi = (hi + Math.imul(ah8, bh1)) | 0; lo = (lo + Math.imul(al7, bl2)) | 0; mid = (mid + Math.imul(al7, bh2)) | 0; mid = (mid + Math.imul(ah7, bl2)) | 0; hi = (hi + Math.imul(ah7, bh2)) | 0; lo = (lo + Math.imul(al6, bl3)) | 0; mid = (mid + Math.imul(al6, bh3)) | 0; mid = (mid + Math.imul(ah6, bl3)) | 0; hi = (hi + Math.imul(ah6, bh3)) | 0; lo = (lo + Math.imul(al5, bl4)) | 0; mid = (mid + Math.imul(al5, bh4)) | 0; mid = (mid + Math.imul(ah5, bl4)) | 0; hi = (hi + Math.imul(ah5, bh4)) | 0; lo = (lo + Math.imul(al4, bl5)) | 0; mid = (mid + Math.imul(al4, bh5)) | 0; mid = (mid + Math.imul(ah4, bl5)) | 0; hi = (hi + Math.imul(ah4, bh5)) | 0; lo = (lo + Math.imul(al3, bl6)) | 0; mid = (mid + Math.imul(al3, bh6)) | 0; mid = (mid + Math.imul(ah3, bl6)) | 0; hi = (hi + Math.imul(ah3, bh6)) | 0; lo = (lo + Math.imul(al2, bl7)) | 0; mid = (mid + Math.imul(al2, bh7)) | 0; mid = (mid + Math.imul(ah2, bl7)) | 0; hi = (hi + Math.imul(ah2, bh7)) | 0; lo = (lo + Math.imul(al1, bl8)) | 0; mid = (mid + Math.imul(al1, bh8)) | 0; mid = (mid + Math.imul(ah1, bl8)) | 0; hi = (hi + Math.imul(ah1, bh8)) | 0; lo = (lo + Math.imul(al0, bl9)) | 0; mid = (mid + Math.imul(al0, bh9)) | 0; mid = (mid + Math.imul(ah0, bl9)) | 0; hi = (hi + Math.imul(ah0, bh9)) | 0; var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = (mid + Math.imul(ah9, bl1)) | 0; hi = Math.imul(ah9, bh1); lo = (lo + Math.imul(al8, bl2)) | 0; mid = (mid + Math.imul(al8, bh2)) | 0; mid = (mid + Math.imul(ah8, bl2)) | 0; hi = (hi + Math.imul(ah8, bh2)) | 0; lo = (lo + Math.imul(al7, bl3)) | 0; mid = (mid + Math.imul(al7, bh3)) | 0; mid = (mid + Math.imul(ah7, bl3)) | 0; hi = (hi + Math.imul(ah7, bh3)) | 0; lo = (lo + Math.imul(al6, bl4)) | 0; mid = (mid + Math.imul(al6, bh4)) | 0; mid = (mid + Math.imul(ah6, bl4)) | 0; hi = (hi + Math.imul(ah6, bh4)) | 0; lo = (lo + Math.imul(al5, bl5)) | 0; mid = (mid + Math.imul(al5, bh5)) | 0; mid = (mid + Math.imul(ah5, bl5)) | 0; hi = (hi + Math.imul(ah5, bh5)) | 0; lo = (lo + Math.imul(al4, bl6)) | 0; mid = (mid + Math.imul(al4, bh6)) | 0; mid = (mid + Math.imul(ah4, bl6)) | 0; hi = (hi + Math.imul(ah4, bh6)) | 0; lo = (lo + Math.imul(al3, bl7)) | 0; mid = (mid + Math.imul(al3, bh7)) | 0; mid = (mid + Math.imul(ah3, bl7)) | 0; hi = (hi + Math.imul(ah3, bh7)) | 0; lo = (lo + Math.imul(al2, bl8)) | 0; mid = (mid + Math.imul(al2, bh8)) | 0; mid = (mid + Math.imul(ah2, bl8)) | 0; hi = (hi + Math.imul(ah2, bh8)) | 0; lo = (lo + Math.imul(al1, bl9)) | 0; mid = (mid + Math.imul(al1, bh9)) | 0; mid = (mid + Math.imul(ah1, bl9)) | 0; hi = (hi + Math.imul(ah1, bh9)) | 0; var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = (mid + Math.imul(ah9, bl2)) | 0; hi = Math.imul(ah9, bh2); lo = (lo + Math.imul(al8, bl3)) | 0; mid = (mid + Math.imul(al8, bh3)) | 0; mid = (mid + Math.imul(ah8, bl3)) | 0; hi = (hi + Math.imul(ah8, bh3)) | 0; lo = (lo + Math.imul(al7, bl4)) | 0; mid = (mid + Math.imul(al7, bh4)) | 0; mid = (mid + Math.imul(ah7, bl4)) | 0; hi = (hi + Math.imul(ah7, bh4)) | 0; lo = (lo + Math.imul(al6, bl5)) | 0; mid = (mid + Math.imul(al6, bh5)) | 0; mid = (mid + Math.imul(ah6, bl5)) | 0; hi = (hi + Math.imul(ah6, bh5)) | 0; lo = (lo + Math.imul(al5, bl6)) | 0; mid = (mid + Math.imul(al5, bh6)) | 0; mid = (mid + Math.imul(ah5, bl6)) | 0; hi = (hi + Math.imul(ah5, bh6)) | 0; lo = (lo + Math.imul(al4, bl7)) | 0; mid = (mid + Math.imul(al4, bh7)) | 0; mid = (mid + Math.imul(ah4, bl7)) | 0; hi = (hi + Math.imul(ah4, bh7)) | 0; lo = (lo + Math.imul(al3, bl8)) | 0; mid = (mid + Math.imul(al3, bh8)) | 0; mid = (mid + Math.imul(ah3, bl8)) | 0; hi = (hi + Math.imul(ah3, bh8)) | 0; lo = (lo + Math.imul(al2, bl9)) | 0; mid = (mid + Math.imul(al2, bh9)) | 0; mid = (mid + Math.imul(ah2, bl9)) | 0; hi = (hi + Math.imul(ah2, bh9)) | 0; var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = (mid + Math.imul(ah9, bl3)) | 0; hi = Math.imul(ah9, bh3); lo = (lo + Math.imul(al8, bl4)) | 0; mid = (mid + Math.imul(al8, bh4)) | 0; mid = (mid + Math.imul(ah8, bl4)) | 0; hi = (hi + Math.imul(ah8, bh4)) | 0; lo = (lo + Math.imul(al7, bl5)) | 0; mid = (mid + Math.imul(al7, bh5)) | 0; mid = (mid + Math.imul(ah7, bl5)) | 0; hi = (hi + Math.imul(ah7, bh5)) | 0; lo = (lo + Math.imul(al6, bl6)) | 0; mid = (mid + Math.imul(al6, bh6)) | 0; mid = (mid + Math.imul(ah6, bl6)) | 0; hi = (hi + Math.imul(ah6, bh6)) | 0; lo = (lo + Math.imul(al5, bl7)) | 0; mid = (mid + Math.imul(al5, bh7)) | 0; mid = (mid + Math.imul(ah5, bl7)) | 0; hi = (hi + Math.imul(ah5, bh7)) | 0; lo = (lo + Math.imul(al4, bl8)) | 0; mid = (mid + Math.imul(al4, bh8)) | 0; mid = (mid + Math.imul(ah4, bl8)) | 0; hi = (hi + Math.imul(ah4, bh8)) | 0; lo = (lo + Math.imul(al3, bl9)) | 0; mid = (mid + Math.imul(al3, bh9)) | 0; mid = (mid + Math.imul(ah3, bl9)) | 0; hi = (hi + Math.imul(ah3, bh9)) | 0; var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = (mid + Math.imul(ah9, bl4)) | 0; hi = Math.imul(ah9, bh4); lo = (lo + Math.imul(al8, bl5)) | 0; mid = (mid + Math.imul(al8, bh5)) | 0; mid = (mid + Math.imul(ah8, bl5)) | 0; hi = (hi + Math.imul(ah8, bh5)) | 0; lo = (lo + Math.imul(al7, bl6)) | 0; mid = (mid + Math.imul(al7, bh6)) | 0; mid = (mid + Math.imul(ah7, bl6)) | 0; hi = (hi + Math.imul(ah7, bh6)) | 0; lo = (lo + Math.imul(al6, bl7)) | 0; mid = (mid + Math.imul(al6, bh7)) | 0; mid = (mid + Math.imul(ah6, bl7)) | 0; hi = (hi + Math.imul(ah6, bh7)) | 0; lo = (lo + Math.imul(al5, bl8)) | 0; mid = (mid + Math.imul(al5, bh8)) | 0; mid = (mid + Math.imul(ah5, bl8)) | 0; hi = (hi + Math.imul(ah5, bh8)) | 0; lo = (lo + Math.imul(al4, bl9)) | 0; mid = (mid + Math.imul(al4, bh9)) | 0; mid = (mid + Math.imul(ah4, bl9)) | 0; hi = (hi + Math.imul(ah4, bh9)) | 0; var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = (mid + Math.imul(ah9, bl5)) | 0; hi = Math.imul(ah9, bh5); lo = (lo + Math.imul(al8, bl6)) | 0; mid = (mid + Math.imul(al8, bh6)) | 0; mid = (mid + Math.imul(ah8, bl6)) | 0; hi = (hi + Math.imul(ah8, bh6)) | 0; lo = (lo + Math.imul(al7, bl7)) | 0; mid = (mid + Math.imul(al7, bh7)) | 0; mid = (mid + Math.imul(ah7, bl7)) | 0; hi = (hi + Math.imul(ah7, bh7)) | 0; lo = (lo + Math.imul(al6, bl8)) | 0; mid = (mid + Math.imul(al6, bh8)) | 0; mid = (mid + Math.imul(ah6, bl8)) | 0; hi = (hi + Math.imul(ah6, bh8)) | 0; lo = (lo + Math.imul(al5, bl9)) | 0; mid = (mid + Math.imul(al5, bh9)) | 0; mid = (mid + Math.imul(ah5, bl9)) | 0; hi = (hi + Math.imul(ah5, bh9)) | 0; var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = (mid + Math.imul(ah9, bl6)) | 0; hi = Math.imul(ah9, bh6); lo = (lo + Math.imul(al8, bl7)) | 0; mid = (mid + Math.imul(al8, bh7)) | 0; mid = (mid + Math.imul(ah8, bl7)) | 0; hi = (hi + Math.imul(ah8, bh7)) | 0; lo = (lo + Math.imul(al7, bl8)) | 0; mid = (mid + Math.imul(al7, bh8)) | 0; mid = (mid + Math.imul(ah7, bl8)) | 0; hi = (hi + Math.imul(ah7, bh8)) | 0; lo = (lo + Math.imul(al6, bl9)) | 0; mid = (mid + Math.imul(al6, bh9)) | 0; mid = (mid + Math.imul(ah6, bl9)) | 0; hi = (hi + Math.imul(ah6, bh9)) | 0; var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = (mid + Math.imul(ah9, bl7)) | 0; hi = Math.imul(ah9, bh7); lo = (lo + Math.imul(al8, bl8)) | 0; mid = (mid + Math.imul(al8, bh8)) | 0; mid = (mid + Math.imul(ah8, bl8)) | 0; hi = (hi + Math.imul(ah8, bh8)) | 0; lo = (lo + Math.imul(al7, bl9)) | 0; mid = (mid + Math.imul(al7, bh9)) | 0; mid = (mid + Math.imul(ah7, bl9)) | 0; hi = (hi + Math.imul(ah7, bh9)) | 0; var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = (mid + Math.imul(ah9, bl8)) | 0; hi = Math.imul(ah9, bh8); lo = (lo + Math.imul(al8, bl9)) | 0; mid = (mid + Math.imul(al8, bh9)) | 0; mid = (mid + Math.imul(ah8, bl9)) | 0; hi = (hi + Math.imul(ah8, bh9)) | 0; var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = (mid + Math.imul(ah9, bl9)) | 0; hi = Math.imul(ah9, bh9); var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo (self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.length + num.length; var carry = 0; var hncarry = 0; for (var k = 0; k < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = hncarry; hncarry = 0; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.words[i] | 0; var b = num.words[j] | 0; var r = a * b; var lo = r & 0x3ffffff; ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; lo = (lo + rword) | 0; rword = lo & 0x3ffffff; ncarry = (ncarry + (lo >>> 26)) | 0; hncarry += ncarry >>> 26; ncarry &= 0x3ffffff; } out.words[k] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k] = carry; } else { out.length--; } return out._strip(); } function jumboMulTo (self, num, out) { // Temporary disable, see https://github.com/indutny/bn.js/issues/211 // var fftm = new FFTM(); // return fftm.mulp(self, num, out); return bigMulTo(self, num, out); } BN.prototype.mulTo = function mulTo (num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM (x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT (N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out._strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += (w / 0x4000000) | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return isNegNum ? this.ineg() : this; }; BN.prototype.muln = function muln (num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr () { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr () { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow (num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (26 - r); } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this._strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - (hint % 26)) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; this.words[i] = (carry << (26 - r)) | (word >>> r); carry = word & mask; } // Push carried bits as a mask if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this._strip(); }; BN.prototype.ishrn = function ishrn (bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln (bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln (bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn (bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn (bits) { return this.clone().iushrn(bits); }; // Test if n bit is set BN.prototype.testn = function testn (bit) { assert(typeof bit === 'number' && bit >= 0); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; assert(this.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } if (r !== 0) { s++; } this.length = Math.min(s, this.length); if (r !== 0) { var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); this.words[this.length - 1] &= mask; } return this._strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn (bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) <= num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { this.words[i] -= 0x4000000; if (i === this.length - 1) { this.words[i + 1] = 1; } else { this.words[i + 1]++; } } this.length = Math.max(this.length, i + 1); return this; }; // Subtract plain number `num` from `this` BN.prototype.isubn = function isubn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // Carry for (var i = 0; i < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this._strip(); }; BN.prototype.addn = function addn (num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn (num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs () { this.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this._strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this._strip(); }; BN.prototype._wordDiv = function _wordDiv (num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min((qj / bhi) | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q._strip(); } a._strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod (num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // Both numbers are positive at this point // Strip both numbers to approximate shift value if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN(0), mod: this }; } // Very short reduction if (num.length === 1) { if (mode === 'div') { return { div: this.divn(num.words[0]), mod: null }; } if (mode === 'mod') { return { div: null, mod: new BN(this.modrn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN(this.modrn(num.words[0])) }; } return this._wordDiv(num, mode); }; // Find `this` / `num` BN.prototype.div = function div (num) { return this.divmod(num, 'div', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod (num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod (num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound (num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r2 = num.andln(1); var cmp = mod.cmp(half); // Round down if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div; // Round up return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN.prototype.modrn = function modrn (num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(num <= 0x3ffffff); var p = (1 << 26) % num; var acc = 0; for (var i = this.length - 1; i >= 0; i--) { acc = (p * acc + (this.words[i] | 0)) % num; } return isNegNum ? -acc : acc; }; // WARNING: DEPRECATED BN.prototype.modn = function modn (num) { return this.modrn(num); }; // In-place division by number BN.prototype.idivn = function idivn (num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(num <= 0x3ffffff); var carry = 0; for (var i = this.length - 1; i >= 0; i--) { var w = (this.words[i] | 0) + carry * 0x4000000; this.words[i] = (w / num) | 0; carry = w % num; } this._strip(); return isNegNum ? this.ineg() : this; }; BN.prototype.divn = function divn (num) { return this.clone().idivn(num); }; BN.prototype.egcd = function egcd (p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp (p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd (num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm (num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven () { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd () { return (this.words[0] & 1) === 1; }; // And first word and num BN.prototype.andln = function andln (num) { return this.words[0] & num; }; // Increment at the bit position in-line BN.prototype.bincn = function bincn (bit) { assert(typeof bit === 'number'); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero () { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn (num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this._strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` BN.prototype.cmp = function cmp (num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; // Unsigned comparison BN.prototype.ucmp = function ucmp (num) { // At this point both numbers have the same sign if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn (num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt (num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten (num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte (num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn (num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt (num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten (num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte (num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn (num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq (num) { return this.cmp(num) === 0; }; // // A reduce context, could be using montgomery or something better, depending // on the `m` itself. // BN.red = function red (num) { return new Red(num); }; BN.prototype.toRed = function toRed (ctx) { assert(!this.red, 'Already a number in reduction context'); assert(this.negative === 0, 'red works only with positives'); return ctx.convertTo(this)._forceRed(ctx); }; BN.prototype.fromRed = function fromRed () { assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }; BN.prototype._forceRed = function _forceRed (ctx) { this.red = ctx; return this; }; BN.prototype.forceRed = function forceRed (ctx) { assert(!this.red, 'Already a number in reduction context'); return this._forceRed(ctx); }; BN.prototype.redAdd = function redAdd (num) { assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }; BN.prototype.redIAdd = function redIAdd (num) { assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }; BN.prototype.redSub = function redSub (num) { assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }; BN.prototype.redISub = function redISub (num) { assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }; BN.prototype.redShl = function redShl (num) { assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }; BN.prototype.redMul = function redMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.mul(this, num); }; BN.prototype.redIMul = function redIMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.imul(this, num); }; BN.prototype.redSqr = function redSqr () { assert(this.red, 'redSqr works only with red numbers'); this.red._verify1(this); return this.red.sqr(this); }; BN.prototype.redISqr = function redISqr () { assert(this.red, 'redISqr works only with red numbers'); this.red._verify1(this); return this.red.isqr(this); }; // Square root over p BN.prototype.redSqrt = function redSqrt () { assert(this.red, 'redSqrt works only with red numbers'); this.red._verify1(this); return this.red.sqrt(this); }; BN.prototype.redInvm = function redInvm () { assert(this.red, 'redInvm works only with red numbers'); this.red._verify1(this); return this.red.invm(this); }; // Return negative clone of `this` % `red modulo` BN.prototype.redNeg = function redNeg () { assert(this.red, 'redNeg works only with red numbers'); this.red._verify1(this); return this.red.neg(this); }; BN.prototype.redPow = function redPow (num) { assert(this.red && !num.red, 'redPow(normalNum)'); this.red._verify1(this); return this.red.pow(this, num); }; // Prime numbers with efficient reduction var primes = { k256: null, p224: null, p192: null, p25519: null }; // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K this.name = name; this.p = new BN(p, 16); this.n = this.p.bitLength(); this.k = new BN(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp () { var tmp = new BN(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce (num) { // Assumes that `num` is less than `P^2` // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) var r = num; var rlen; do { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { if (r.strip !== undefined) { // r is a BN v4 instance r.strip(); } else { // r is a BN v5 instance r._strip(); } } return r; }; MPrime.prototype.split = function split (input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK (num) { return num.imul(this.k); }; function K256 () { MPrime.call( this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } inherits(K256, MPrime); K256.prototype.split = function split (input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK (num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224 () { MPrime.call( this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192 () { MPrime.call( this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519 () { // 2 ^ 255 - 19 MPrime.call( this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; num.words[i] = lo; carry = hi; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; // Exported mostly for testing purposes, use plain name instead BN._prime = function prime (name) { // Cached version of prime if (primes[name]) return primes[name]; var prime; if (name === 'k256') { prime = new K256(); } else if (name === 'p224') { prime = new P224(); } else if (name === 'p192') { prime = new P192(); } else if (name === 'p25519') { prime = new P25519(); } else { throw new Error('Unknown prime ' + name); } primes[name] = prime; return prime; }; // // Base reduction engine // function Red (m) { if (typeof m === 'string') { var prime = BN._prime(m); this.m = prime.p; this.prime = prime; } else { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1 (a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2 (a, b) { assert((a.negative | b.negative) === 0, 'red works only with positives'); assert(a.red && a.red === b.red, 'red works only with red numbers'); }; Red.prototype.imod = function imod (a) { if (this.prime) return this.prime.ireduce(a)._forceRed(this); move(a, a.umod(this.m)._forceRed(this)); return a; }; Red.prototype.neg = function neg (a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._forceRed(this); }; Red.prototype.add = function add (a, b) { this._verify2(a, b); var res = a.add(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd (a, b) { this._verify2(a, b); var res = a.iadd(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub (a, b) { this._verify2(a, b); var res = a.sub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub (a, b) { this._verify2(a, b); var res = a.isub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl (a, num) { this._verify1(a); return this.imod(a.ushln(num)); }; Red.prototype.imul = function imul (a, b) { this._verify2(a, b); return this.imod(a.imul(b)); }; Red.prototype.mul = function mul (a, b) { this._verify2(a, b); return this.imod(a.mul(b)); }; Red.prototype.isqr = function isqr (a) { return this.imul(a, a.clone()); }; Red.prototype.sqr = function sqr (a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt (a) { if (a.isZero()) return a.clone(); var mod3 = this.m.andln(3); assert(mod3 % 2 === 1); // Fast case if (mod3 === 3) { var pow = this.m.add(new BN(1)).iushrn(2); return this.pow(a, pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) var q = this.m.subn(1); var s = 0; while (!q.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); var one = new BN(1).toRed(this); var nOne = one.redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. var lpow = this.m.subn(1).iushrn(1); var z = this.m.bitLength(); z = new BN(2 * z * z).toRed(this); while (this.pow(z, lpow).cmp(nOne) !== 0) { z.redIAdd(nOne); } var c = this.pow(z, q); var r = this.pow(a, q.addn(1).iushrn(1)); var t = this.pow(a, q); var m = s; while (t.cmp(one) !== 0) { var tmp = t; for (var i = 0; tmp.cmp(one) !== 0; i++) { tmp = tmp.redSqr(); } assert(i < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm (a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1).toRed(this); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = (word >> j) & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo (num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; Red.prototype.convertFrom = function convertFrom (num) { var res = num.clone(); res.red = null; return res; }; // // Montgomery method engine // BN.mont = function mont (num) { return new Mont(num); }; function Mont (m) { Red.call(this, m); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - (this.shift % 26); } this.r = new BN(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo (num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom (num) { var r = this.imod(num.mul(this.rinv)); r.red = null; return r; }; Mont.prototype.imul = function imul (a, b) { if (a.isZero() || b.isZero()) { a.words[0] = 0; a.length = 1; return a; } var t = a.imul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul (a, b) { if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); var t = a.mul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm (a) { // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R var res = this.imod(a._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })( false || module, this); /***/ }), /***/ 4157: /*!*****************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/eventemitter3/index.js ***! \*****************************************************************************/ /***/ ((module) => { "use strict"; var has = Object.prototype.hasOwnProperty , prefix = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @private */ function Events() {} // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Add a listener for a given event. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} once Specify if the listener is a one-time listener. * @returns {EventEmitter} * @private */ function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } /** * Clear event by name. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} evt The Event name. * @private */ function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @public */ function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @public */ EventEmitter.prototype.eventNames = function eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Array} The registered listeners. * @public */ EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event , handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; /** * Return the number of listeners listening to a given event. * * @param {(String|Symbol)} event The event name. * @returns {Number} The number of listeners. * @public */ EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event , listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; /** * Calls each of the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; /** * Add a one-time listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; /** * Remove the listeners of a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {*} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {(String|Symbol)} [event] The event name. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // Expose the prefix. // EventEmitter.prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // EventEmitter.EventEmitter = EventEmitter; // // Expose the module. // if (true) { module.exports = EventEmitter; } /***/ }), /***/ 55599: /*!********************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/uuid/index.js ***! \********************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var v1 = __webpack_require__(/*! ./v1 */ 81925); var v4 = __webpack_require__(/*! ./v4 */ 19454); var uuid = v4; uuid.v1 = v1; uuid.v4 = v4; module.exports = uuid; /***/ }), /***/ 1044: /*!******************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/uuid/lib/bytesToUuid.js ***! \******************************************************************************/ /***/ ((module) => { /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 return ([bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]]]).join(''); } module.exports = bytesToUuid; /***/ }), /***/ 63796: /*!******************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/uuid/lib/rng-browser.js ***! \******************************************************************************/ /***/ ((module) => { // Unique ID creation requires a high quality random # generator. In the // browser this is a little complicated due to unknown quality of Math.random() // and inconsistent support for the `crypto` API. We do the best we can via // feature-detection // getRandomValues needs to be invoked in a context where "this" is a Crypto // implementation. Also, find the complete implementation of crypto on IE11. var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) || (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto)); if (getRandomValues) { // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef module.exports = function whatwgRNG() { getRandomValues(rnds8); return rnds8; }; } else { // Math.random()-based (RNG) // // If all else fails, use Math.random(). It's fast, but is of unspecified // quality. var rnds = new Array(16); module.exports = function mathRNG() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) r = Math.random() * 0x100000000; rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } return rnds; }; } /***/ }), /***/ 81925: /*!*****************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/uuid/v1.js ***! \*****************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var rng = __webpack_require__(/*! ./lib/rng */ 63796); var bytesToUuid = __webpack_require__(/*! ./lib/bytesToUuid */ 1044); // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html var _nodeId; var _clockseq; // Previous uuid creation time var _lastMSecs = 0; var _lastNSecs = 0; // See https://github.com/broofa/node-uuid for API details function v1(options, buf, offset) { var i = buf && offset || 0; var b = buf || []; options = options || {}; var node = options.node || _nodeId; var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { var seedBytes = rng(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [ seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] ]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (var n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf ? buf : bytesToUuid(b); } module.exports = v1; /***/ }), /***/ 19454: /*!*****************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/uuid/v4.js ***! \*****************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var rng = __webpack_require__(/*! ./lib/rng */ 63796); var bytesToUuid = __webpack_require__(/*! ./lib/bytesToUuid */ 1044); function v4(options, buf, offset) { var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } module.exports = v4; /***/ }), /***/ 22165: /*!****************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-bzz/lib/index.js ***! \****************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Fabian Vogelsteller * @date 2017 */ var swarm = __webpack_require__(/*! swarm-js */ 21567); var Bzz = function Bzz(provider) { this.givenProvider = Bzz.givenProvider; if (provider && provider._requestManager) { provider = provider.currentProvider; } // only allow file picker when in browser if (typeof document !== 'undefined') { this.pick = swarm.pick; } this.setProvider(provider); }; // set default ethereum provider /* jshint ignore:start */ Bzz.givenProvider = null; if (typeof ethereum !== 'undefined' && ethereum.bzz) { Bzz.givenProvider = ethereum.bzz; } /* jshint ignore:end */ Bzz.prototype.setProvider = function (provider) { // is ethereum provider if (!!provider && typeof provider === 'object' && typeof provider.bzz === 'string') { provider = provider.bzz; // is no string, set default } // else if(!_.isString(provider)) { // provider = 'http://swarm-gateways.net'; // default to gateway // } if (typeof provider === 'string') { this.currentProvider = provider; } else { this.currentProvider = null; var noProviderError = new Error('No provider set, please set one using bzz.setProvider().'); this.download = this.upload = this.isAvailable = function () { throw noProviderError; }; return false; } // add functions this.download = swarm.at(provider).download; this.upload = swarm.at(provider).upload; this.isAvailable = swarm.at(provider).isAvailable; return true; }; module.exports = Bzz; /***/ }), /***/ 52193: /*!**************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-helpers/lib/errors.js ***! \**************************************************************************************/ /***/ ((module) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file errors.js * @author Fabian Vogelsteller * @author Marek Kotewicz * @date 2017 */ module.exports = { ErrorResponse: function (result) { var message = !!result && !!result.error && !!result.error.message ? result.error.message : JSON.stringify(result); var data = (!!result.error && !!result.error.data) ? result.error.data : null; var err = new Error('Returned error: ' + message); err.data = data; return err; }, InvalidNumberOfParams: function (got, expected, method) { return new Error('Invalid number of parameters for "' + method + '". Got ' + got + ' expected ' + expected + '!'); }, InvalidConnection: function (host, event) { return this.ConnectionError('CONNECTION ERROR: Couldn\'t connect to node ' + host + '.', event); }, InvalidProvider: function () { return new Error('Provider not set or invalid'); }, InvalidResponse: function (result) { var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result); return new Error(message); }, ConnectionTimeout: function (ms) { return new Error('CONNECTION TIMEOUT: timeout of ' + ms + ' ms achived'); }, ConnectionNotOpenError: function (event) { return this.ConnectionError('connection not open on send()', event); }, ConnectionCloseError: function (event) { if (typeof event === 'object' && event.code && event.reason) { return this.ConnectionError('CONNECTION ERROR: The connection got closed with ' + 'the close code `' + event.code + '` and the following ' + 'reason string `' + event.reason + '`', event); } return new Error('CONNECTION ERROR: The connection closed unexpectedly'); }, MaxAttemptsReachedOnReconnectingError: function () { return new Error('Maximum number of reconnect attempts reached!'); }, PendingRequestsOnReconnectingError: function () { return new Error('CONNECTION ERROR: Provider started to reconnect before the response got received!'); }, ConnectionError: function (msg, event) { const error = new Error(msg); if (event) { error.code = event.code; error.reason = event.reason; } return error; }, RevertInstructionError: function (reason, signature) { var error = new Error('Your request got reverted with the following reason string: ' + reason); error.reason = reason; error.signature = signature; return error; }, TransactionRevertInstructionError: function (reason, signature, receipt) { var error = new Error('Transaction has been reverted by the EVM:\n' + JSON.stringify(receipt, null, 2)); error.reason = reason; error.signature = signature; error.receipt = receipt; return error; }, TransactionError: function (message, receipt) { var error = new Error(message); error.receipt = receipt; return error; }, NoContractAddressFoundError: function (receipt) { return this.TransactionError('The transaction receipt didn\'t contain a contract address.', receipt); }, ContractCodeNotStoredError: function (receipt) { return this.TransactionError('The contract code couldn\'t be stored, please check your gas limit.', receipt); }, TransactionRevertedWithoutReasonError: function (receipt) { return this.TransactionError('Transaction has been reverted by the EVM:\n' + JSON.stringify(receipt, null, 2), receipt); }, TransactionOutOfGasError: function (receipt) { return this.TransactionError('Transaction ran out of gas. Please provide more gas:\n' + JSON.stringify(receipt, null, 2), receipt); }, ResolverMethodMissingError: function (address, name) { return new Error('The resolver at ' + address + 'does not implement requested method: "' + name + '".'); }, ContractMissingABIError: function () { return new Error('You must provide the json interface of the contract when instantiating a contract object.'); }, ContractOnceRequiresCallbackError: function () { return new Error('Once requires a callback as the second parameter.'); }, ContractEventDoesNotExistError: function (eventName) { return new Error('Event "' + eventName + '" doesn\'t exist in this contract.'); }, ContractReservedEventError: function (type) { return new Error('The event "' + type + '" is a reserved event name, you can\'t use it.'); }, ContractMissingDeployDataError: function () { return new Error('No "data" specified in neither the given options, nor the default options.'); }, ContractNoAddressDefinedError: function () { return new Error('This contract object doesn\'t have address set yet, please set an address first.'); }, ContractNoFromAddressDefinedError: function () { return new Error('No "from" address specified in neither the given options, nor the default options.'); } }; /***/ }), /***/ 67127: /*!******************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-helpers/lib/formatters.js ***! \******************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file formatters.js * @author Fabian Vogelsteller * @author Marek Kotewicz * @date 2017 */ var utils = __webpack_require__(/*! web3-utils */ 60819); var Iban = __webpack_require__(/*! web3-eth-iban */ 19890); /** * Will format the given storage key array values to hex strings. * * @method inputStorageKeysFormatter * * @param {Array} keys * * @returns {Array} */ var inputStorageKeysFormatter = function (keys) { return keys.map(utils.numberToHex); }; /** * Will format the given proof response from the node. * * @method outputProofFormatter * * @param {object} proof * * @returns {object} */ var outputProofFormatter = function (proof) { proof.address = utils.toChecksumAddress(proof.address); proof.nonce = utils.hexToNumberString(proof.nonce); proof.balance = utils.hexToNumberString(proof.balance); return proof; }; /** * Should the format output to a big number * * @method outputBigNumberFormatter * * @param {String|Number|BigNumber|BN} number * * @returns {BN} object */ var outputBigNumberFormatter = function (number) { return utils.toBN(number).toString(10); }; /** * Returns true if the given blockNumber is 'latest', 'pending', or 'earliest. * * @method isPredefinedBlockNumber * * @param {String} blockNumber * * @returns {Boolean} */ var isPredefinedBlockNumber = function (blockNumber) { return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest'; }; /** * Returns the given block number as hex string or does return the defaultBlock property of the current module * * @method inputDefaultBlockNumberFormatter * * @param {String|Number|BN|BigNumber} blockNumber * * @returns {String} */ var inputDefaultBlockNumberFormatter = function (blockNumber) { if (this && (blockNumber === undefined || blockNumber === null)) { return inputBlockNumberFormatter(this.defaultBlock); } return inputBlockNumberFormatter(blockNumber); }; /** * Returns the given block number as hex string or the predefined block number 'latest', 'pending', 'earliest', 'genesis' * * @param {String|Number|BN|BigNumber} blockNumber * * @returns {String} */ var inputBlockNumberFormatter = function (blockNumber) { if (blockNumber === undefined) { return undefined; } if (isPredefinedBlockNumber(blockNumber)) { return blockNumber; } if (blockNumber === 'genesis') { return '0x0'; } return (utils.isHexStrict(blockNumber)) ? ((typeof blockNumber === 'string') ? blockNumber.toLowerCase() : blockNumber) : utils.numberToHex(blockNumber); }; /** * Formats the input of a transaction and converts all values to HEX * * @method _txInputFormatter * @param {Object} transaction options * @returns object */ var _txInputFormatter = function (options) { if (options.to) { // it might be contract creation options.to = inputAddressFormatter(options.to); } if (options.data && options.input) { throw new Error('You can\'t have "data" and "input" as properties of transactions at the same time, please use either "data" or "input" instead.'); } if (!options.data && options.input) { options.data = options.input; delete options.input; } if (options.data && !options.data.startsWith('0x')) { options.data = '0x' + options.data; } if (options.data && !utils.isHex(options.data)) { throw new Error('The data field must be HEX encoded data.'); } // allow both if (options.gas || options.gasLimit) { options.gas = options.gas || options.gasLimit; } if (options.maxPriorityFeePerGas || options.maxFeePerGas) { delete options.gasPrice; } ['gasPrice', 'gas', 'value', 'maxPriorityFeePerGas', 'maxFeePerGas', 'nonce'].filter(function (key) { return options[key] !== undefined; }).forEach(function (key) { options[key] = utils.numberToHex(options[key]); }); return options; }; /** * Formats the input of a transaction and converts all values to HEX * * @method inputCallFormatter * @param {Object} transaction options * @returns object */ var inputCallFormatter = function (options) { options = _txInputFormatter(options); var from = options.from || (this ? this.defaultAccount : null); if (from) { options.from = inputAddressFormatter(from); } return options; }; /** * Formats the input of a transaction and converts all values to HEX * * @method inputTransactionFormatter * @param {Object} options * @returns object */ var inputTransactionFormatter = function (options) { options = _txInputFormatter(options); // check from, only if not number, or object if (!(typeof options.from === 'number') && !(!!options.from && typeof options.from === 'object')) { options.from = options.from || (this ? this.defaultAccount : null); if (!options.from && !(typeof options.from === 'number')) { throw new Error('The send transactions "from" field must be defined!'); } options.from = inputAddressFormatter(options.from); } return options; }; /** * Hex encodes the data passed to eth_sign and personal_sign * * @method inputSignFormatter * @param {String} data * @returns {String} */ var inputSignFormatter = function (data) { return (utils.isHexStrict(data)) ? data : utils.utf8ToHex(data); }; /** * Formats the output of a transaction to its proper values * * @method outputTransactionFormatter * @param {Object} tx * @returns {Object} */ var outputTransactionFormatter = function (tx) { if (tx.blockNumber !== null) tx.blockNumber = utils.hexToNumber(tx.blockNumber); if (tx.transactionIndex !== null) tx.transactionIndex = utils.hexToNumber(tx.transactionIndex); tx.nonce = utils.hexToNumber(tx.nonce); tx.gas = utils.hexToNumber(tx.gas); if (tx.gasPrice) tx.gasPrice = outputBigNumberFormatter(tx.gasPrice); if (tx.maxFeePerGas) tx.maxFeePerGas = outputBigNumberFormatter(tx.maxFeePerGas); if (tx.maxPriorityFeePerGas) tx.maxPriorityFeePerGas = outputBigNumberFormatter(tx.maxPriorityFeePerGas); if (tx.type) tx.type = utils.hexToNumber(tx.type); tx.value = outputBigNumberFormatter(tx.value); if (tx.to && utils.isAddress(tx.to)) { // tx.to could be `0x0` or `null` while contract creation tx.to = utils.toChecksumAddress(tx.to); } else { tx.to = null; // set to `null` if invalid address } if (tx.from) { tx.from = utils.toChecksumAddress(tx.from); } return tx; }; /** * Formats the output of a transaction receipt to its proper values * * @method outputTransactionReceiptFormatter * @param {Object} receipt * @returns {Object} */ var outputTransactionReceiptFormatter = function (receipt) { if (typeof receipt !== 'object') { throw new Error('Received receipt is invalid: ' + receipt); } if (receipt.blockNumber !== null) receipt.blockNumber = utils.hexToNumber(receipt.blockNumber); if (receipt.transactionIndex !== null) receipt.transactionIndex = utils.hexToNumber(receipt.transactionIndex); receipt.cumulativeGasUsed = utils.hexToNumber(receipt.cumulativeGasUsed); receipt.gasUsed = utils.hexToNumber(receipt.gasUsed); if (Array.isArray(receipt.logs)) { receipt.logs = receipt.logs.map(outputLogFormatter); } if (receipt.contractAddress) { receipt.contractAddress = utils.toChecksumAddress(receipt.contractAddress); } if (typeof receipt.status !== 'undefined' && receipt.status !== null) { receipt.status = Boolean(parseInt(receipt.status)); } return receipt; }; /** * Formats the output of a block to its proper values * * @method outputBlockFormatter * @param {Object} block * @returns {Object} */ var outputBlockFormatter = function (block) { // transform to number block.gasLimit = utils.hexToNumber(block.gasLimit); block.gasUsed = utils.hexToNumber(block.gasUsed); block.size = utils.hexToNumber(block.size); block.timestamp = utils.hexToNumber(block.timestamp); if (block.number !== null) block.number = utils.hexToNumber(block.number); if (block.difficulty) block.difficulty = outputBigNumberFormatter(block.difficulty); if (block.totalDifficulty) block.totalDifficulty = outputBigNumberFormatter(block.totalDifficulty); if (Array.isArray(block.transactions)) { block.transactions.forEach(function (item) { if (!(typeof item === 'string')) return outputTransactionFormatter(item); }); } if (block.miner) block.miner = utils.toChecksumAddress(block.miner); return block; }; /** * Formats the input of a log * * @method inputLogFormatter * @param {Object} log object * @returns {Object} log */ var inputLogFormatter = function (options) { var toTopic = function (value) { if (value === null || typeof value === 'undefined') return null; value = String(value); if (value.indexOf('0x') === 0) return value; else return utils.fromUtf8(value); }; if (options === undefined) options = {}; // If options !== undefined, don't blow out existing data if (options.fromBlock === undefined) options = { ...options, fromBlock: 'latest' }; if (options.fromBlock || options.fromBlock === 0) options.fromBlock = inputBlockNumberFormatter(options.fromBlock); if (options.toBlock || options.toBlock === 0) options.toBlock = inputBlockNumberFormatter(options.toBlock); // make sure topics, get converted to hex options.topics = options.topics || []; options.topics = options.topics.map(function (topic) { return (Array.isArray(topic)) ? topic.map(toTopic) : toTopic(topic); }); toTopic = null; if (options.address) { options.address = (Array.isArray(options.address)) ? options.address.map(function (addr) { return inputAddressFormatter(addr); }) : inputAddressFormatter(options.address); } return options; }; /** * Formats the output of a log * * @method outputLogFormatter * @param {Object} log object * @returns {Object} log */ var outputLogFormatter = function (log) { // generate a custom log id if (typeof log.blockHash === 'string' && typeof log.transactionHash === 'string' && typeof log.logIndex === 'string') { var shaId = utils.sha3(log.blockHash.replace('0x', '') + log.transactionHash.replace('0x', '') + log.logIndex.replace('0x', '')); log.id = 'log_' + shaId.replace('0x', '').substr(0, 8); } else if (!log.id) { log.id = null; } if (log.blockNumber !== null) log.blockNumber = utils.hexToNumber(log.blockNumber); if (log.transactionIndex !== null) log.transactionIndex = utils.hexToNumber(log.transactionIndex); if (log.logIndex !== null) log.logIndex = utils.hexToNumber(log.logIndex); if (log.address) { log.address = utils.toChecksumAddress(log.address); } return log; }; /** * Formats the input of a whisper post and converts all values to HEX * * @method inputPostFormatter * @param {Object} transaction object * @returns {Object} */ var inputPostFormatter = function (post) { // post.payload = utils.toHex(post.payload); if (post.ttl) post.ttl = utils.numberToHex(post.ttl); if (post.workToProve) post.workToProve = utils.numberToHex(post.workToProve); if (post.priority) post.priority = utils.numberToHex(post.priority); // fallback if (!Array.isArray(post.topics)) { post.topics = post.topics ? [post.topics] : []; } // format the following options post.topics = post.topics.map(function (topic) { // convert only if not hex return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic); }); return post; }; /** * Formats the output of a received post message * * @method outputPostFormatter * @param {Object} * @returns {Object} */ var outputPostFormatter = function (post) { post.expiry = utils.hexToNumber(post.expiry); post.sent = utils.hexToNumber(post.sent); post.ttl = utils.hexToNumber(post.ttl); post.workProved = utils.hexToNumber(post.workProved); // post.payloadRaw = post.payload; // post.payload = utils.hexToAscii(post.payload); // if (utils.isJson(post.payload)) { // post.payload = JSON.parse(post.payload); // } // format the following options if (!post.topics) { post.topics = []; } post.topics = post.topics.map(function (topic) { return utils.toUtf8(topic); }); return post; }; var inputAddressFormatter = function (address) { var iban = new Iban(address); if (iban.isValid() && iban.isDirect()) { return iban.toAddress().toLowerCase(); } else if (utils.isAddress(address)) { return '0x' + address.toLowerCase().replace('0x', ''); } throw new Error(`Provided address ${address} is invalid, the capitalization checksum test failed, or it's an indirect IBAN address which can't be converted.`); }; var outputSyncingFormatter = function (result) { result.startingBlock = utils.hexToNumber(result.startingBlock); result.currentBlock = utils.hexToNumber(result.currentBlock); result.highestBlock = utils.hexToNumber(result.highestBlock); if (result.knownStates) { result.knownStates = utils.hexToNumber(result.knownStates); result.pulledStates = utils.hexToNumber(result.pulledStates); } return result; }; module.exports = { inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter, inputBlockNumberFormatter: inputBlockNumberFormatter, inputCallFormatter: inputCallFormatter, inputTransactionFormatter: inputTransactionFormatter, inputAddressFormatter: inputAddressFormatter, inputPostFormatter: inputPostFormatter, inputLogFormatter: inputLogFormatter, inputSignFormatter: inputSignFormatter, inputStorageKeysFormatter: inputStorageKeysFormatter, outputProofFormatter: outputProofFormatter, outputBigNumberFormatter: outputBigNumberFormatter, outputTransactionFormatter: outputTransactionFormatter, outputTransactionReceiptFormatter: outputTransactionReceiptFormatter, outputBlockFormatter: outputBlockFormatter, outputLogFormatter: outputLogFormatter, outputPostFormatter: outputPostFormatter, outputSyncingFormatter: outputSyncingFormatter }; /***/ }), /***/ 20176: /*!*************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-helpers/lib/index.js ***! \*************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Fabian Vogelsteller * @date 2017 */ var errors = __webpack_require__(/*! ./errors */ 52193); var formatters = __webpack_require__(/*! ./formatters */ 67127); module.exports = { errors: errors, formatters: formatters }; /***/ }), /***/ 50202: /*!************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-method/lib/index.js ***! \************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Fabian Vogelsteller * @author Marek Kotewicz * @date 2017 */ var errors = __webpack_require__(/*! web3-core-helpers */ 20176).errors; var formatters = __webpack_require__(/*! web3-core-helpers */ 20176).formatters; var utils = __webpack_require__(/*! web3-utils */ 60819); var promiEvent = __webpack_require__(/*! web3-core-promievent */ 24817); var Subscriptions = __webpack_require__(/*! web3-core-subscriptions */ 54923).subscriptions; var EthersTransactionUtils = __webpack_require__(/*! @ethersproject/transactions */ 1893); var Method = function Method(options) { if (!options.call || !options.name) { throw new Error('When creating a method you need to provide at least the "name" and "call" property.'); } this.name = options.name; this.call = options.call; this.params = options.params || 0; this.inputFormatter = options.inputFormatter; this.outputFormatter = options.outputFormatter; this.transformPayload = options.transformPayload; this.extraFormatters = options.extraFormatters; this.abiCoder = options.abiCoder; // Will be used to encode the revert reason string this.requestManager = options.requestManager; // reference to eth.accounts this.accounts = options.accounts; this.defaultBlock = options.defaultBlock || 'latest'; this.defaultAccount = options.defaultAccount || null; this.transactionBlockTimeout = options.transactionBlockTimeout || 50; this.transactionConfirmationBlocks = options.transactionConfirmationBlocks || 24; this.transactionPollingTimeout = options.transactionPollingTimeout || 750; this.defaultCommon = options.defaultCommon; this.defaultChain = options.defaultChain; this.defaultHardfork = options.defaultHardfork; this.handleRevert = options.handleRevert; }; Method.prototype.setRequestManager = function (requestManager, accounts) { this.requestManager = requestManager; // reference to eth.accounts if (accounts) { this.accounts = accounts; } }; Method.prototype.createFunction = function (requestManager, accounts) { var func = this.buildCall(); func.call = this.call; this.setRequestManager(requestManager || this.requestManager, accounts || this.accounts); return func; }; Method.prototype.attachToObject = function (obj) { var func = this.buildCall(); func.call = this.call; var name = this.name.split('.'); if (name.length > 1) { obj[name[0]] = obj[name[0]] || {}; obj[name[0]][name[1]] = func; } else { obj[name[0]] = func; } }; /** * Should be used to determine name of the jsonrpc method based on arguments * * @method getCall * @param {Array} arguments * @return {String} name of jsonrpc method */ Method.prototype.getCall = function (args) { return typeof this.call === 'function' ? this.call(args) : this.call; }; /** * Should be used to extract callback from array of arguments. Modifies input param * * @method extractCallback * @param {Array} arguments * @return {Function|Null} callback, if exists */ Method.prototype.extractCallback = function (args) { if (typeof (args[args.length - 1]) === 'function') { return args.pop(); // modify the args array! } }; /** * Should be called to check if the number of arguments is correct * * @method validateArgs * @param {Array} arguments * @throws {Error} if it is not */ Method.prototype.validateArgs = function (args) { if (args.length !== this.params) { throw errors.InvalidNumberOfParams(args.length, this.params, this.name); } }; /** * Should be called to format input args of method * * @method formatInput * @param {Array} * @return {Array} */ Method.prototype.formatInput = function (args) { var _this = this; if (!this.inputFormatter) { return args; } return this.inputFormatter.map(function (formatter, index) { // bind this for defaultBlock, and defaultAccount return formatter ? formatter.call(_this, args[index]) : args[index]; }); }; /** * Should be called to format output(result) of method * * @method formatOutput * @param {Object} * @return {Object} */ Method.prototype.formatOutput = function (result) { var _this = this; if (Array.isArray(result)) { return result.map(function (res) { return _this.outputFormatter && res ? _this.outputFormatter(res) : res; }); } else { return this.outputFormatter && result ? this.outputFormatter(result) : result; } }; /** * Should create payload from given input args * * @method toPayload * @param {Array} args * @return {Object} */ Method.prototype.toPayload = function (args) { var call = this.getCall(args); var callback = this.extractCallback(args); var params = this.formatInput(args); this.validateArgs(params); var payload = { method: call, params: params, callback: callback }; if (this.transformPayload) { payload = this.transformPayload(payload); } return payload; }; Method.prototype._confirmTransaction = function (defer, result, payload) { var method = this, promiseResolved = false, canUnsubscribe = true, timeoutCount = 0, confirmationCount = 0, intervalId = null, lastBlock = null, receiptJSON = '', gasProvided = ((!!payload.params[0] && typeof payload.params[0] === 'object') && payload.params[0].gas) ? payload.params[0].gas : null, isContractDeployment = (!!payload.params[0] && typeof payload.params[0] === 'object') && payload.params[0].data && payload.params[0].from && !payload.params[0].to, hasBytecode = isContractDeployment && payload.params[0].data.length > 2; // add custom send Methods var _ethereumCalls = [ new Method({ name: 'getBlockByNumber', call: 'eth_getBlockByNumber', params: 2, inputFormatter: [formatters.inputBlockNumberFormatter, function (val) { return !!val; }], outputFormatter: formatters.outputBlockFormatter }), new Method({ name: 'getTransactionReceipt', call: 'eth_getTransactionReceipt', params: 1, inputFormatter: [null], outputFormatter: formatters.outputTransactionReceiptFormatter }), new Method({ name: 'getCode', call: 'eth_getCode', params: 2, inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter] }), new Method({ name: 'getTransactionByHash', call: 'eth_getTransactionByHash', params: 1, inputFormatter: [null], outputFormatter: formatters.outputTransactionFormatter }), new Subscriptions({ name: 'subscribe', type: 'eth', subscriptions: { 'newBlockHeaders': { subscriptionName: 'newHeads', params: 0, outputFormatter: formatters.outputBlockFormatter } } }) ]; // attach methods to this._ethereumCall var _ethereumCall = {}; _ethereumCalls.forEach(mthd => { mthd.attachToObject(_ethereumCall); mthd.requestManager = method.requestManager; // assign rather than call setRequestManager() }); // fire "receipt" and confirmation events and resolve after var checkConfirmation = function (existingReceipt, isPolling, err, blockHeader, sub) { if (!err) { // create fake unsubscribe if (!sub) { sub = { unsubscribe: function () { clearInterval(intervalId); } }; } // if we have a valid receipt we don't need to send a request return (existingReceipt ? promiEvent.resolve(existingReceipt) : _ethereumCall.getTransactionReceipt(result)) // catch error from requesting receipt .catch(function (err) { sub.unsubscribe(); promiseResolved = true; utils._fireError({ message: 'Failed to check for transaction receipt:', data: err }, defer.eventEmitter, defer.reject); }) // if CONFIRMATION listener exists check for confirmations, by setting canUnsubscribe = false .then(async function (receipt) { if (!receipt || !receipt.blockHash) { throw new Error('Receipt missing or blockHash null'); } // apply extra formatters if (method.extraFormatters && method.extraFormatters.receiptFormatter) { receipt = method.extraFormatters.receiptFormatter(receipt); } // check if confirmation listener exists if (defer.eventEmitter.listeners('confirmation').length > 0) { var block; // If there was an immediately retrieved receipt, it's already // been confirmed by the direct call to checkConfirmation needed // for parity instant-seal if (existingReceipt === undefined || confirmationCount !== 0) { // Get latest block to emit with confirmation var latestBlock = await _ethereumCall.getBlockByNumber('latest'); var latestBlockHash = latestBlock ? latestBlock.hash : null; if (isPolling) { // Check if actually a new block is existing on polling if (lastBlock) { block = await _ethereumCall.getBlockByNumber(lastBlock.number + 1); if (block) { lastBlock = block; defer.eventEmitter.emit('confirmation', confirmationCount, receipt, latestBlockHash); } } else { block = await _ethereumCall.getBlockByNumber(receipt.blockNumber); lastBlock = block; defer.eventEmitter.emit('confirmation', confirmationCount, receipt, latestBlockHash); } } else { defer.eventEmitter.emit('confirmation', confirmationCount, receipt, latestBlockHash); } } if ((isPolling && block) || !isPolling) { confirmationCount++; } canUnsubscribe = false; if (confirmationCount === method.transactionConfirmationBlocks + 1) { // add 1 so we account for conf 0 sub.unsubscribe(); defer.eventEmitter.removeAllListeners(); } } return receipt; }) // CHECK for CONTRACT DEPLOYMENT .then(async function (receipt) { if (isContractDeployment && !promiseResolved) { if (!receipt.contractAddress) { if (canUnsubscribe) { sub.unsubscribe(); promiseResolved = true; } utils._fireError(errors.NoContractAddressFoundError(receipt), defer.eventEmitter, defer.reject, null, receipt); return; } var code; try { code = await _ethereumCall.getCode(receipt.contractAddress); } catch (err) { // ignore; } if (!code) { return; } // If deployment is status.true and there was a real // bytecode string, assume it was successful. var deploymentSuccess = receipt.status === true && hasBytecode; if (deploymentSuccess || code.length > 2) { defer.eventEmitter.emit('receipt', receipt); // if contract, return instance instead of receipt if (method.extraFormatters && method.extraFormatters.contractDeployFormatter) { defer.resolve(method.extraFormatters.contractDeployFormatter(receipt)); } else { defer.resolve(receipt); } // need to remove listeners, as they aren't removed automatically when succesfull if (canUnsubscribe) { defer.eventEmitter.removeAllListeners(); } } else { utils._fireError(errors.ContractCodeNotStoredError(receipt), defer.eventEmitter, defer.reject, null, receipt); } if (canUnsubscribe) { sub.unsubscribe(); } promiseResolved = true; } return receipt; }) // CHECK for normal tx check for receipt only .then(async function (receipt) { if (!isContractDeployment && !promiseResolved) { if (!receipt.outOfGas && (!gasProvided || gasProvided !== receipt.gasUsed) && (receipt.status === true || receipt.status === '0x1' || typeof receipt.status === 'undefined')) { defer.eventEmitter.emit('receipt', receipt); defer.resolve(receipt); // need to remove listeners, as they aren't removed automatically when succesfull if (canUnsubscribe) { defer.eventEmitter.removeAllListeners(); } } else { receiptJSON = JSON.stringify(receipt, null, 2); if (receipt.status === false || receipt.status === '0x0') { try { var revertMessage = null; if (method.handleRevert && (method.call === 'eth_sendTransaction' || method.call === 'eth_sendRawTransaction')) { var txReplayOptions = payload.params[0]; // If send was raw, fetch the transaction and reconstitute the // original params so they can be replayed with `eth_call` if (method.call === 'eth_sendRawTransaction') { var rawTransactionHex = payload.params[0]; var parsedTx = EthersTransactionUtils.parse(rawTransactionHex); txReplayOptions = formatters.inputTransactionFormatter({ data: parsedTx.data, to: parsedTx.to, from: parsedTx.from, gas: parsedTx.gasLimit.toHexString(), gasPrice: parsedTx.gasPrice.toHexString(), value: parsedTx.value.toHexString() }); } // Get revert reason string with eth_call revertMessage = await method.getRevertReason(txReplayOptions, receipt.blockNumber); if (revertMessage) { // Only throw a revert error if a revert reason is existing utils._fireError(errors.TransactionRevertInstructionError(revertMessage.reason, revertMessage.signature, receipt), defer.eventEmitter, defer.reject, null, receipt); } else { throw false; // Throw false and let the try/catch statement handle the error correctly after } } else { throw false; // Throw false and let the try/catch statement handle the error correctly after } } catch (error) { // Throw an normal revert error if no revert reason is given or the detection of it is disabled utils._fireError(errors.TransactionRevertedWithoutReasonError(receipt), defer.eventEmitter, defer.reject, null, receipt); } } else { // Throw OOG if status is not existing and provided gas and used gas are equal utils._fireError(errors.TransactionOutOfGasError(receipt), defer.eventEmitter, defer.reject, null, receipt); } } if (canUnsubscribe) { sub.unsubscribe(); } promiseResolved = true; } }) // time out the transaction if not mined after 50 blocks .catch(function () { timeoutCount++; // check to see if we are http polling if (!!isPolling) { // polling timeout is different than transactionBlockTimeout blocks since we are triggering every second if (timeoutCount - 1 >= method.transactionPollingTimeout) { sub.unsubscribe(); promiseResolved = true; utils._fireError(errors.TransactionError('Transaction was not mined within ' + method.transactionPollingTimeout + ' seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject); } } else { if (timeoutCount - 1 >= method.transactionBlockTimeout) { sub.unsubscribe(); promiseResolved = true; utils._fireError(errors.TransactionError('Transaction was not mined within ' + method.transactionBlockTimeout + ' blocks, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject); } } }); } else { sub.unsubscribe(); promiseResolved = true; utils._fireError({ message: 'Failed to subscribe to new newBlockHeaders to confirm the transaction receipts.', data: err }, defer.eventEmitter, defer.reject); } }; // start watching for confirmation depending on the support features of the provider var startWatching = function (existingReceipt) { const startInterval = () => { intervalId = setInterval(checkConfirmation.bind(null, existingReceipt, true), 1000); }; if (!this.requestManager.provider.on) { startInterval(); } else { _ethereumCall.subscribe('newBlockHeaders', function (err, blockHeader, sub) { if (err || !blockHeader) { // fall back to polling startInterval(); } else { checkConfirmation(existingReceipt, false, err, blockHeader, sub); } }); } }.bind(this); // first check if we already have a confirmed transaction _ethereumCall.getTransactionReceipt(result) .then(function (receipt) { if (receipt && receipt.blockHash) { if (defer.eventEmitter.listeners('confirmation').length > 0) { // We must keep on watching for new Blocks, if a confirmation listener is present startWatching(receipt); } checkConfirmation(receipt, false); } else if (!promiseResolved) { startWatching(); } }) .catch(function () { if (!promiseResolved) startWatching(); }); }; var getWallet = function (from, accounts) { var wallet = null; // is index given if (typeof from === 'number') { wallet = accounts.wallet[from]; // is account given } else if (!!from && typeof from === 'object' && from.address && from.privateKey) { wallet = from; // search in wallet for address } else { wallet = accounts.wallet[from.toLowerCase()]; } return wallet; }; Method.prototype.buildCall = function () { var method = this, isSendTx = (method.call === 'eth_sendTransaction' || method.call === 'eth_sendRawTransaction'), // || method.call === 'personal_sendTransaction' isCall = (method.call === 'eth_call'); // actual send function var send = function () { var defer = promiEvent(!isSendTx), payload = method.toPayload(Array.prototype.slice.call(arguments)); // CALLBACK function var sendTxCallback = function (err, result) { if (method.handleRevert && isCall && method.abiCoder) { var reasonData; // Ganache / Geth <= 1.9.13 return the reason data as a successful eth_call response // Geth >= 1.9.15 attaches the reason data to an error object. // Geth 1.9.14 is missing revert reason (https://github.com/ethereum/web3.js/issues/3520) if (!err && method.isRevertReasonString(result)) { reasonData = result.substring(10); } else if (err && err.data) { reasonData = err.data.substring(10); } if (reasonData) { var reason = method.abiCoder.decodeParameter('string', '0x' + reasonData); var signature = 'Error(String)'; utils._fireError(errors.RevertInstructionError(reason, signature), defer.eventEmitter, defer.reject, payload.callback, { reason: reason, signature: signature }); return; } } try { result = method.formatOutput(result); } catch (e) { err = e; } if (result instanceof Error) { err = result; } if (!err) { if (payload.callback) { payload.callback(null, result); } } else { if (err.error) { err = err.error; } return utils._fireError(err, defer.eventEmitter, defer.reject, payload.callback); } // return PROMISE if (!isSendTx) { if (!err) { defer.resolve(result); } // return PROMIEVENT } else { defer.eventEmitter.emit('transactionHash', result); method._confirmTransaction(defer, result, payload); } }; // SENDS the SIGNED SIGNATURE var sendSignedTx = function (sign) { var signedPayload = { ...payload, method: 'eth_sendRawTransaction', params: [sign.rawTransaction] }; method.requestManager.send(signedPayload, sendTxCallback); }; var sendRequest = function (payload, method) { if (method && method.accounts && method.accounts.wallet && method.accounts.wallet.length) { var wallet; // ETH_SENDTRANSACTION if (payload.method === 'eth_sendTransaction') { var tx = payload.params[0]; wallet = getWallet((!!tx && typeof tx === 'object') ? tx.from : null, method.accounts); // If wallet was found, sign tx, and send using sendRawTransaction if (wallet && wallet.privateKey) { var tx = JSON.parse(JSON.stringify(tx)); delete tx.from; if (method.defaultChain && !tx.chain) { tx.chain = method.defaultChain; } if (method.defaultHardfork && !tx.hardfork) { tx.hardfork = method.defaultHardfork; } if (method.defaultCommon && !tx.common) { tx.common = method.defaultCommon; } method.accounts.signTransaction(tx, wallet.privateKey) .then(sendSignedTx) .catch(function (err) { if (typeof defer.eventEmitter.listeners === 'function' && defer.eventEmitter.listeners('error').length) { try { defer.eventEmitter.emit('error', err); } catch (err) { // Ignore userland error prevent it to bubble up within web3. } defer.eventEmitter.removeAllListeners(); defer.eventEmitter.catch(function () { }); } defer.reject(err); }); return; } // ETH_SIGN } else if (payload.method === 'eth_sign') { var data = payload.params[1]; wallet = getWallet(payload.params[0], method.accounts); // If wallet was found, sign tx, and send using sendRawTransaction if (wallet && wallet.privateKey) { var sign = method.accounts.sign(data, wallet.privateKey); if (payload.callback) { payload.callback(null, sign.signature); } defer.resolve(sign.signature); return; } } } return method.requestManager.send(payload, sendTxCallback); }; // Send the actual transaction if (isSendTx && !!payload.params[0] && typeof payload.params[0] === 'object' && (typeof payload.params[0].gasPrice === 'undefined' && (typeof payload.params[0].maxPriorityFeePerGas === 'undefined' || typeof payload.params[0].maxFeePerGas === 'undefined'))) { _handleTxPricing(method, payload.params[0]).then(txPricing => { if (txPricing.gasPrice !== undefined) { payload.params[0].gasPrice = txPricing.gasPrice; } else if (txPricing.maxPriorityFeePerGas !== undefined && txPricing.maxFeePerGas !== undefined) { payload.params[0].maxPriorityFeePerGas = txPricing.maxPriorityFeePerGas; payload.params[0].maxFeePerGas = txPricing.maxFeePerGas; } if (isSendTx) { setTimeout(() => { defer.eventEmitter.emit('sending', payload); }, 0); } sendRequest(payload, method); }); } else { if (isSendTx) { setTimeout(() => { defer.eventEmitter.emit('sending', payload); }, 0); } sendRequest(payload, method); } if (isSendTx) { setTimeout(() => { defer.eventEmitter.emit('sent', payload); }, 0); } return defer.eventEmitter; }; // necessary to attach things to the method send.method = method; // necessary for batch requests send.request = this.request.bind(this); return send; }; function _handleTxPricing(method, tx) { return new Promise((resolve, reject) => { try { var getBlockByNumber = (new Method({ name: 'getBlockByNumber', call: 'eth_getBlockByNumber', params: 2, inputFormatter: [function (blockNumber) { return blockNumber ? utils.toHex(blockNumber) : 'latest'; }, function () { return false; }] })).createFunction(method.requestManager); var getGasPrice = (new Method({ name: 'getGasPrice', call: 'eth_gasPrice', params: 0 })).createFunction(method.requestManager); Promise.all([ getBlockByNumber(), getGasPrice() ]).then(responses => { const [block, gasPrice] = responses; if ((tx.type === '0x2' || tx.type === undefined) && (block && block.baseFeePerGas)) { // The network supports EIP-1559 // Taken from https://github.com/ethers-io/ethers.js/blob/ba6854bdd5a912fe873d5da494cb5c62c190adde/packages/abstract-provider/src.ts/index.ts#L230 let maxPriorityFeePerGas, maxFeePerGas; if (tx.gasPrice) { // Using legacy gasPrice property on an eip-1559 network, // so use gasPrice as both fee properties maxPriorityFeePerGas = tx.gasPrice; maxFeePerGas = tx.gasPrice; delete tx.gasPrice; } else { maxPriorityFeePerGas = tx.maxPriorityFeePerGas || '0x9502F900'; // 2.5 Gwei maxFeePerGas = tx.maxFeePerGas || utils.toHex(utils.toBN(block.baseFeePerGas) .mul(utils.toBN(2)) .add(utils.toBN(maxPriorityFeePerGas))); } resolve({ maxFeePerGas, maxPriorityFeePerGas }); } else { if (tx.maxPriorityFeePerGas || tx.maxFeePerGas) throw Error("Network doesn't support eip-1559"); resolve({ gasPrice }); } }); } catch (error) { reject(error); } }); } /** * Returns the revert reason string if existing or otherwise false. * * @method getRevertReason * * @param {Object} txOptions * @param {Number} blockNumber * * @returns {Promise} */ Method.prototype.getRevertReason = function (txOptions, blockNumber) { var self = this; return new Promise(function (resolve, reject) { (new Method({ name: 'call', call: 'eth_call', params: 2, abiCoder: self.abiCoder, handleRevert: true })) .createFunction(self.requestManager)(txOptions, utils.numberToHex(blockNumber)) .then(function () { resolve(false); }) .catch(function (error) { if (error.reason) { resolve({ reason: error.reason, signature: error.signature }); } else { reject(error); } }); }); }; /** * Checks if the given hex string is a revert message from the EVM * * @method isRevertReasonString * * @param {String} data - Hex string prefixed with 0x * * @returns {Boolean} */ Method.prototype.isRevertReasonString = function (data) { return typeof data === 'string' && ((data.length - 2) / 2) % 32 === 4 && data.substring(0, 10) === '0x08c379a0'; }; /** * Should be called to create the pure JSONRPC request which can be used in a batch request * * @method request * @return {Object} jsonrpc request */ Method.prototype.request = function () { var payload = this.toPayload(Array.prototype.slice.call(arguments)); payload.format = this.formatOutput.bind(this); return payload; }; module.exports = Method; /***/ }), /***/ 24817: /*!****************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-promievent/lib/index.js ***! \****************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Fabian Vogelsteller * @date 2016 */ var EventEmitter = __webpack_require__(/*! eventemitter3 */ 83649); /** * This function generates a defer promise and adds eventEmitter functionality to it * * @method eventifiedPromise */ var PromiEvent = function PromiEvent(justPromise) { var resolve, reject, eventEmitter = new Promise(function () { resolve = arguments[0]; reject = arguments[1]; }); if (justPromise) { return { resolve: resolve, reject: reject, eventEmitter: eventEmitter }; } // get eventEmitter var emitter = new EventEmitter(); // add eventEmitter to the promise eventEmitter._events = emitter._events; eventEmitter.emit = emitter.emit; eventEmitter.on = emitter.on; eventEmitter.once = emitter.once; eventEmitter.off = emitter.off; eventEmitter.listeners = emitter.listeners; eventEmitter.addListener = emitter.addListener; eventEmitter.removeListener = emitter.removeListener; eventEmitter.removeAllListeners = emitter.removeAllListeners; return { resolve: resolve, reject: reject, eventEmitter: eventEmitter }; }; PromiEvent.resolve = function (value) { var promise = PromiEvent(true); promise.resolve(value); return promise.eventEmitter; }; module.exports = PromiEvent; /***/ }), /***/ 83649: /*!*********************!*\ !*** eventemitter3 ***! \*********************/ /***/ ((module) => { "use strict"; var has = Object.prototype.hasOwnProperty , prefix = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @private */ function Events() {} // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Add a listener for a given event. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} once Specify if the listener is a one-time listener. * @returns {EventEmitter} * @private */ function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } /** * Clear event by name. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} evt The Event name. * @private */ function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @public */ function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @public */ EventEmitter.prototype.eventNames = function eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Array} The registered listeners. * @public */ EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event , handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; /** * Return the number of listeners listening to a given event. * * @param {(String|Symbol)} event The event name. * @returns {Number} The number of listeners. * @public */ EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event , listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; /** * Calls each of the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; /** * Add a one-time listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; /** * Remove the listeners of a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {*} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {(String|Symbol)} [event] The event name. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // Expose the prefix. // EventEmitter.prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // EventEmitter.EventEmitter = EventEmitter; // // Expose the module. // if (true) { module.exports = EventEmitter; } /***/ }), /***/ 73340: /*!********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-requestmanager/lib/batch.js ***! \********************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file batch.js * @author Marek Kotewicz * @date 2015 */ var Jsonrpc = __webpack_require__(/*! ./jsonrpc */ 65214); var errors = __webpack_require__(/*! web3-core-helpers */ 20176).errors; var Batch = function (requestManager) { this.requestManager = requestManager; this.requests = []; }; /** * Should be called to add create new request to batch request * * @method add * @param {Object} jsonrpc requet object */ Batch.prototype.add = function (request) { this.requests.push(request); }; /** * Should be called to execute batch request * * @method execute */ Batch.prototype.execute = function () { var requests = this.requests; this.requestManager.sendBatch(requests, function (err, results) { results = results || []; requests.map(function (request, index) { return results[index] || {}; }).forEach(function (result, index) { if (requests[index].callback) { if (result && result.error) { return requests[index].callback(errors.ErrorResponse(result)); } if (!Jsonrpc.isValidResponse(result)) { return requests[index].callback(errors.InvalidResponse(result)); } try { requests[index].callback(null, requests[index].format ? requests[index].format(result.result) : result.result); } catch (err) { requests[index].callback(err); } } }); }); }; module.exports = Batch; /***/ }), /***/ 91174: /*!****************************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-requestmanager/lib/givenProvider.js ***! \****************************************************************************************************/ /***/ ((module) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file givenProvider.js * @author Fabian Vogelsteller * @date 2017 */ var givenProvider = null; // ADD GIVEN PROVIDER /* jshint ignore:start */ var global; try { global = Function('return this')(); } catch (e) { global = window; } // EIP-1193: window.ethereum if (typeof global.ethereum !== 'undefined') { givenProvider = global.ethereum; // Legacy web3.currentProvider } else if (typeof global.web3 !== 'undefined' && global.web3.currentProvider) { if (global.web3.currentProvider.sendAsync) { global.web3.currentProvider.send = global.web3.currentProvider.sendAsync; delete global.web3.currentProvider.sendAsync; } // if connection is 'ipcProviderWrapper', add subscription support if (!global.web3.currentProvider.on && global.web3.currentProvider.connection && global.web3.currentProvider.connection.constructor.name === 'ipcProviderWrapper') { global.web3.currentProvider.on = function (type, callback) { if (typeof callback !== 'function') throw new Error('The second parameter callback must be a function.'); switch (type) { case 'data': this.connection.on('data', function (data) { var result = ''; data = data.toString(); try { result = JSON.parse(data); } catch (e) { return callback(new Error('Couldn\'t parse response data' + data)); } // notification if (!result.id && result.method.indexOf('_subscription') !== -1) { callback(null, result); } }); break; default: this.connection.on(type, callback); break; } }; } givenProvider = global.web3.currentProvider; } /* jshint ignore:end */ module.exports = givenProvider; /***/ }), /***/ 83033: /*!********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-requestmanager/lib/index.js ***! \********************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Fabian Vogelsteller * @date 2017 */ const { callbackify } = __webpack_require__(/*! util */ 71732); var errors = __webpack_require__(/*! web3-core-helpers */ 20176).errors; var Jsonrpc = __webpack_require__(/*! ./jsonrpc.js */ 65214); var BatchManager = __webpack_require__(/*! ./batch.js */ 73340); var givenProvider = __webpack_require__(/*! ./givenProvider.js */ 91174); /** * It's responsible for passing messages to providers * It's also responsible for polling the ethereum node for incoming messages * Default poll timeout is 1 second * Singleton * * @param {string|Object}provider * @param {Net.Socket} net * * @constructor */ var RequestManager = function RequestManager(provider, net) { this.provider = null; this.providers = RequestManager.providers; this.setProvider(provider, net); this.subscriptions = new Map(); }; RequestManager.givenProvider = givenProvider; RequestManager.providers = { WebsocketProvider: __webpack_require__(/*! web3-providers-ws */ 48168), HttpProvider: __webpack_require__(/*! web3-providers-http */ 95982), IpcProvider: __webpack_require__(/*! web3-providers-ipc */ 39055) }; /** * Should be used to set provider of request manager * * @method setProvider * * @param {Object} provider * @param {net.Socket} net * * @returns void */ RequestManager.prototype.setProvider = function (provider, net) { var _this = this; // autodetect provider if (provider && typeof provider === 'string' && this.providers) { // HTTP if (/^http(s)?:\/\//i.test(provider)) { provider = new this.providers.HttpProvider(provider); // WS } else if (/^ws(s)?:\/\//i.test(provider)) { provider = new this.providers.WebsocketProvider(provider); // IPC } else if (provider && typeof net === 'object' && typeof net.connect === 'function') { provider = new this.providers.IpcProvider(provider, net); } else if (provider) { throw new Error('Can\'t autodetect provider for "' + provider + '"'); } } // reset the old one before changing, if still connected if (this.provider && this.provider.connected) this.clearSubscriptions(); this.provider = provider || null; // listen to incoming notifications if (this.provider && this.provider.on) { if (typeof provider.request === 'function') { // EIP-1193 provider this.provider.on('message', function (payload) { if (payload && payload.type === 'eth_subscription' && payload.data) { const data = payload.data; if (data.subscription && _this.subscriptions.has(data.subscription)) { _this.subscriptions.get(data.subscription).callback(null, data.result); } } }); } else { // legacy provider subscription event this.provider.on('data', function data(result, deprecatedResult) { result = result || deprecatedResult; // this is for possible old providers, which may had the error first handler // if result is a subscription, call callback for that subscription if (result.method && result.params && result.params.subscription && _this.subscriptions.has(result.params.subscription)) { _this.subscriptions.get(result.params.subscription).callback(null, result.params.result); } }); } // resubscribe if the provider has reconnected this.provider.on('connect', function connect() { _this.subscriptions.forEach(function (subscription) { subscription.subscription.resubscribe(); }); }); // notify all subscriptions about the error condition this.provider.on('error', function error(error) { _this.subscriptions.forEach(function (subscription) { subscription.callback(error); }); }); // notify all subscriptions about bad close conditions const disconnect = function disconnect(event) { if (!_this._isCleanCloseEvent(event) || _this._isIpcCloseError(event)) { _this.subscriptions.forEach(function (subscription) { subscription.callback(errors.ConnectionCloseError(event)); _this.subscriptions.delete(subscription.subscription.id); }); if (_this.provider && _this.provider.emit) { _this.provider.emit('error', errors.ConnectionCloseError(event)); } } if (_this.provider && _this.provider.emit) { _this.provider.emit('end', event); } }; // TODO: Remove close once the standard allows it this.provider.on('close', disconnect); this.provider.on('disconnect', disconnect); // TODO add end, timeout?? } }; /** * Asynchronously send request to provider. * Prefers to use the `request` method available on the provider as specified in [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193). * If `request` is not available, falls back to `sendAsync` and `send` respectively. * @method send * @param {Object} data * @param {Function} callback */ RequestManager.prototype.send = function (data, callback) { callback = callback || function () { }; if (!this.provider) { return callback(errors.InvalidProvider()); } const { method, params } = data; const jsonrpcPayload = Jsonrpc.toPayload(method, params); const jsonrpcResultCallback = this._jsonrpcResultCallback(callback, jsonrpcPayload); if (this.provider.request) { const callbackRequest = callbackify(this.provider.request.bind(this.provider)); const requestArgs = { method, params }; callbackRequest(requestArgs, callback); } else if (this.provider.sendAsync) { this.provider.sendAsync(jsonrpcPayload, jsonrpcResultCallback); } else if (this.provider.send) { this.provider.send(jsonrpcPayload, jsonrpcResultCallback); } else { throw new Error('Provider does not have a request or send method to use.'); } }; /** * Asynchronously send batch request. * Only works if provider supports batch methods through `sendAsync` or `send`. * @method sendBatch * @param {Array} data - array of payload objects * @param {Function} callback */ RequestManager.prototype.sendBatch = function (data, callback) { if (!this.provider) { return callback(errors.InvalidProvider()); } var payload = Jsonrpc.toBatchPayload(data); this.provider[this.provider.sendAsync ? 'sendAsync' : 'send'](payload, function (err, results) { if (err) { return callback(err); } if (!Array.isArray(results)) { return callback(errors.InvalidResponse(results)); } callback(null, results); }); }; /** * Waits for notifications * * @method addSubscription * @param {Subscription} subscription the subscription * @param {String} type the subscription namespace (eth, personal, etc) * @param {Function} callback the callback to call for incoming notifications */ RequestManager.prototype.addSubscription = function (subscription, callback) { if (this.provider.on) { this.subscriptions.set(subscription.id, { callback: callback, subscription: subscription }); } else { throw new Error('The provider doesn\'t support subscriptions: ' + this.provider.constructor.name); } }; /** * Waits for notifications * * @method removeSubscription * @param {String} id the subscription id * @param {Function} callback fired once the subscription is removed */ RequestManager.prototype.removeSubscription = function (id, callback) { if (this.subscriptions.has(id)) { var type = this.subscriptions.get(id).subscription.options.type; // remove subscription first to avoid reentry this.subscriptions.delete(id); // then, try to actually unsubscribe this.send({ method: type + '_unsubscribe', params: [id] }, callback); return; } if (typeof callback === 'function') { // call the callback if the subscription was already removed callback(null); } }; /** * Should be called to reset the subscriptions * * @method reset * * @returns {boolean} */ RequestManager.prototype.clearSubscriptions = function (keepIsSyncing) { try { var _this = this; // uninstall all subscriptions if (this.subscriptions.size > 0) { this.subscriptions.forEach(function (value, id) { if (!keepIsSyncing || value.name !== 'syncing') _this.removeSubscription(id); }); } // reset notification callbacks etc. if (this.provider.reset) this.provider.reset(); return true; } catch (e) { throw new Error(`Error while clearing subscriptions: ${e}`); } }; /** * Evaluates WS close event * * @method _isCleanClose * * @param {CloseEvent | boolean} event WS close event or exception flag * * @returns {boolean} */ RequestManager.prototype._isCleanCloseEvent = function (event) { return typeof event === 'object' && ([1000].includes(event.code) || event.wasClean === true); }; /** * Detects Ipc close error. The node.net module emits ('close', isException) * * @method _isIpcCloseError * * @param {CloseEvent | boolean} event WS close event or exception flag * * @returns {boolean} */ RequestManager.prototype._isIpcCloseError = function (event) { return typeof event === 'boolean' && event; }; /** * The jsonrpc result callback for RequestManager.send * * @method _jsonrpcResultCallback * * @param {Function} callback the callback to use * @param {Object} payload the jsonrpc payload * * @returns {Function} return callback of form (err, result) * */ RequestManager.prototype._jsonrpcResultCallback = function (callback, payload) { return function (err, result) { if (result && result.id && payload.id !== result.id) { return callback(new Error(`Wrong response id ${result.id} (expected: ${payload.id}) in ${JSON.stringify(payload)}`)); } if (err) { return callback(err); } if (result && result.error) { return callback(errors.ErrorResponse(result)); } if (!Jsonrpc.isValidResponse(result)) { return callback(errors.InvalidResponse(result)); } callback(null, result.result); }; }; module.exports = { Manager: RequestManager, BatchManager: BatchManager }; /***/ }), /***/ 65214: /*!**********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-requestmanager/lib/jsonrpc.js ***! \**********************************************************************************************/ /***/ ((module) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** @file jsonrpc.js * @authors: * Fabian Vogelsteller * Marek Kotewicz * Aaron Kumavis * @date 2015 */ // Initialize Jsonrpc as a simple object with utility functions. var Jsonrpc = { messageId: 0 }; /** * Should be called to valid json create payload object * * @method toPayload * @param {Function} method of jsonrpc call, required * @param {Array} params, an array of method params, optional * @returns {Object} valid jsonrpc payload object */ Jsonrpc.toPayload = function (method, params) { if (!method) { throw new Error('JSONRPC method should be specified for params: "' + JSON.stringify(params) + '"!'); } // advance message ID Jsonrpc.messageId++; return { jsonrpc: '2.0', id: Jsonrpc.messageId, method: method, params: params || [] }; }; /** * Should be called to check if jsonrpc response is valid * * @method isValidResponse * @param {Object} * @returns {Boolean} true if response is valid, otherwise false */ Jsonrpc.isValidResponse = function (response) { return Array.isArray(response) ? response.every(validateSingleMessage) : validateSingleMessage(response); function validateSingleMessage(message) { return !!message && !message.error && message.jsonrpc === '2.0' && (typeof message.id === 'number' || typeof message.id === 'string') && message.result !== undefined; // only undefined is not valid json object } }; /** * Should be called to create batch payload object * * @method toBatchPayload * @param {Array} messages, an array of objects with method (required) and params (optional) fields * @returns {Array} batch payload */ Jsonrpc.toBatchPayload = function (messages) { return messages.map(function (message) { return Jsonrpc.toPayload(message.method, message.params); }); }; module.exports = Jsonrpc; /***/ }), /***/ 54923: /*!*******************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-subscriptions/lib/index.js ***! \*******************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var console = __webpack_require__(/*! console-browserify */ 88883); /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Fabian Vogelsteller * @date 2017 */ var Subscription = __webpack_require__(/*! ./subscription.js */ 54125); var Subscriptions = function Subscriptions(options) { this.name = options.name; this.type = options.type; this.subscriptions = options.subscriptions || {}; this.requestManager = null; }; Subscriptions.prototype.setRequestManager = function (rm) { this.requestManager = rm; }; Subscriptions.prototype.attachToObject = function (obj) { var func = this.buildCall(); var name = this.name.split('.'); if (name.length > 1) { obj[name[0]] = obj[name[0]] || {}; obj[name[0]][name[1]] = func; } else { obj[name[0]] = func; } }; Subscriptions.prototype.buildCall = function () { var _this = this; return function () { if (!_this.subscriptions[arguments[0]]) { console.warn('Subscription ' + JSON.stringify(arguments[0]) + ' doesn\'t exist. Subscribing anyway.'); } var subscription = new Subscription({ subscription: _this.subscriptions[arguments[0]] || {}, requestManager: _this.requestManager, type: _this.type }); return subscription.subscribe.apply(subscription, arguments); }; }; module.exports = { subscriptions: Subscriptions, subscription: Subscription }; /***/ }), /***/ 54125: /*!**************************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-subscriptions/lib/subscription.js ***! \**************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file subscription.js * @author Fabian Vogelsteller * @date 2017 */ var errors = __webpack_require__(/*! web3-core-helpers */ 20176).errors; var EventEmitter = __webpack_require__(/*! eventemitter3 */ 15209); var formatters = __webpack_require__(/*! web3-core-helpers */ 20176).formatters; function identity(value) { return value; } function Subscription(options) { EventEmitter.call(this); this.id = null; this.callback = identity; this.arguments = null; this.lastBlock = null; // "from" block tracker for backfilling events on reconnection this.options = { subscription: options.subscription, type: options.type, requestManager: options.requestManager }; } // INHERIT Subscription.prototype = Object.create(EventEmitter.prototype); Subscription.prototype.constructor = Subscription; /** * Should be used to extract callback from array of arguments. Modifies input param * * @method extractCallback * @param {Array} arguments * @return {Function|Null} callback, if exists */ Subscription.prototype._extractCallback = function (args) { if (typeof args[args.length - 1] === 'function') { return args.pop(); // modify the args array! } }; /** * Should be called to check if the number of arguments is correct * * @method validateArgs * @param {Array} arguments * @throws {Error} if it is not */ Subscription.prototype._validateArgs = function (args) { var subscription = this.options.subscription; if (!subscription) subscription = {}; if (!subscription.params) subscription.params = 0; if (args.length !== subscription.params) { throw errors.InvalidNumberOfParams(args.length, subscription.params, subscription.subscriptionName); } }; /** * Should be called to format input args of method * * @method formatInput * @param {Array} * @return {Array} */ Subscription.prototype._formatInput = function (args) { var subscription = this.options.subscription; if (!subscription) { return args; } if (!subscription.inputFormatter) { return args; } var formattedArgs = subscription.inputFormatter.map(function (formatter, index) { return formatter ? formatter(args[index]) : args[index]; }); return formattedArgs; }; /** * Should be called to format output(result) of method * * @method formatOutput * @param result {Object} * @return {Object} */ Subscription.prototype._formatOutput = function (result) { var subscription = this.options.subscription; return (subscription && subscription.outputFormatter && result) ? subscription.outputFormatter(result) : result; }; /** * Should create payload from given input args * * @method toPayload * @param {Array} args * @return {Object} */ Subscription.prototype._toPayload = function (args) { var params = []; this.callback = this._extractCallback(args) || identity; if (!this.subscriptionMethod) { this.subscriptionMethod = args.shift(); // replace subscription with given name if (this.options.subscription.subscriptionName) { this.subscriptionMethod = this.options.subscription.subscriptionName; } } if (!this.arguments) { this.arguments = this._formatInput(args); this._validateArgs(this.arguments); args = []; // make empty after validation } // re-add subscriptionName params.push(this.subscriptionMethod); params = params.concat(this.arguments); if (args.length) { throw new Error('Only a callback is allowed as parameter on an already instantiated subscription.'); } return { method: this.options.type + '_subscribe', params: params }; }; /** * Unsubscribes and clears callbacks * * @method unsubscribe * @return {Object} */ Subscription.prototype.unsubscribe = function (callback) { this.options.requestManager.removeSubscription(this.id, callback); this.id = null; this.lastBlock = null; this.removeAllListeners(); }; /** * Subscribes and watches for changes * * @method subscribe * @param {String} subscription the subscription * @param {Object} options the options object with address topics and fromBlock * @return {Object} */ Subscription.prototype.subscribe = function () { var _this = this; var args = Array.prototype.slice.call(arguments); var payload = this._toPayload(args); if (!payload) { return this; } // throw error, if provider is not set if (!this.options.requestManager.provider) { setTimeout(function () { var err1 = new Error('No provider set.'); _this.callback(err1, null, _this); _this.emit('error', err1); }, 0); return this; } // throw error, if provider doesnt support subscriptions if (!this.options.requestManager.provider.on) { setTimeout(function () { var err2 = new Error('The current provider doesn\'t support subscriptions: ' + _this.options.requestManager.provider.constructor.name); _this.callback(err2, null, _this); _this.emit('error', err2); }, 0); return this; } // Re-subscription only: continue fetching from the last block we received. // a dropped connection may have resulted in gaps in the logs... if (this.lastBlock && !!this.options.params && typeof this.options.params === 'object') { payload.params[1] = this.options.params; payload.params[1].fromBlock = formatters.inputBlockNumberFormatter(this.lastBlock + 1); } // if id is there unsubscribe first if (this.id) { this.unsubscribe(); } // store the params in the options object this.options.params = payload.params[1]; // get past logs, if fromBlock is available if (payload.params[0] === 'logs' && !!payload.params[1] && typeof payload.params[1] === 'object' && payload.params[1].hasOwnProperty('fromBlock') && isFinite(payload.params[1].fromBlock)) { // send the subscription request // copy the params to avoid race-condition with deletion below this block var blockParams = Object.assign({}, payload.params[1]); this.options.requestManager.send({ method: 'eth_getLogs', params: [blockParams] }, function (err, logs) { if (!err) { logs.forEach(function (log) { var output = _this._formatOutput(log); _this.callback(null, output, _this); _this.emit('data', output); }); // TODO subscribe here? after the past logs? } else { setTimeout(function () { _this.callback(err, null, _this); _this.emit('error', err); }, 0); } }); } // create subscription // TODO move to separate function? so that past logs can go first? if (typeof payload.params[1] === 'object') delete payload.params[1].fromBlock; this.options.requestManager.send(payload, function (err, result) { if (!err && result) { _this.id = result; _this.method = payload.params[0]; _this.emit('connected', result); // call callback on notifications _this.options.requestManager.addSubscription(_this, function (error, result) { if (!error) { if (!Array.isArray(result)) { result = [result]; } result.forEach(function (resultItem) { var output = _this._formatOutput(resultItem); // Track current block (for gaps introduced by dropped connections) _this.lastBlock = !!output && typeof output === 'object' ? output.blockNumber : null; if (typeof _this.options.subscription.subscriptionHandler === 'function') { return _this.options.subscription.subscriptionHandler.call(_this, output); } else { _this.emit('data', output); } // call the callback, last so that unsubscribe there won't affect the emit above _this.callback(null, output, _this); }); } else { _this.callback(error, false, _this); _this.emit('error', error); } }); } else { setTimeout(function () { _this.callback(err, false, _this); _this.emit('error', err); }, 0); } }); // return an object to cancel the subscription return this; }; /** * Resubscribe * * @method resubscribe * * @returns {void} */ Subscription.prototype.resubscribe = function () { this.options.requestManager.removeSubscription(this.id); // unsubscribe this.id = null; this.subscribe(this.callback); }; module.exports = Subscription; /***/ }), /***/ 15209: /*!******************************************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core-subscriptions/node_modules/eventemitter3/index.js ***! \******************************************************************************************************************/ /***/ ((module) => { "use strict"; var has = Object.prototype.hasOwnProperty , prefix = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @private */ function Events() {} // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Add a listener for a given event. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} once Specify if the listener is a one-time listener. * @returns {EventEmitter} * @private */ function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } /** * Clear event by name. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} evt The Event name. * @private */ function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @public */ function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @public */ EventEmitter.prototype.eventNames = function eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Array} The registered listeners. * @public */ EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event , handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; /** * Return the number of listeners listening to a given event. * * @param {(String|Symbol)} event The event name. * @returns {Number} The number of listeners. * @public */ EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event , listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; /** * Calls each of the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; /** * Add a one-time listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; /** * Remove the listeners of a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {*} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {(String|Symbol)} [event] The event name. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // Expose the prefix. // EventEmitter.prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // EventEmitter.EventEmitter = EventEmitter; // // Expose the module. // if (true) { module.exports = EventEmitter; } /***/ }), /***/ 82086: /*!******************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core/lib/extend.js ***! \******************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file extend.js * @author Fabian Vogelsteller * @date 2017 */ var formatters = __webpack_require__(/*! web3-core-helpers */ 20176).formatters; var Method = __webpack_require__(/*! web3-core-method */ 50202); var utils = __webpack_require__(/*! web3-utils */ 60819); var extend = function (pckg) { /* jshint maxcomplexity:5 */ var ex = function (extension) { var extendedObject; if (extension.property) { if (!pckg[extension.property]) { pckg[extension.property] = {}; } extendedObject = pckg[extension.property]; } else { extendedObject = pckg; } if (extension.methods) { extension.methods.forEach(function (method) { if (!(method instanceof Method)) { method = new Method(method); } method.attachToObject(extendedObject); method.setRequestManager(pckg._requestManager); }); } return pckg; }; ex.formatters = formatters; ex.utils = utils; ex.Method = Method; return ex; }; module.exports = extend; /***/ }), /***/ 79517: /*!*****************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-core/lib/index.js ***! \*****************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Fabian Vogelsteller * @date 2017 */ const requestManager = __webpack_require__(/*! web3-core-requestmanager */ 83033); const extend = __webpack_require__(/*! ./extend */ 82086); const packageInit = (pkg, args) => { args = Array.prototype.slice.call(args); if (!pkg) { throw new Error('You need to instantiate using the "new" keyword.'); } // make property of pkg._provider, which can properly set providers Object.defineProperty(pkg, 'currentProvider', { get: () => { return pkg._provider; }, set: (value) => { return pkg.setProvider(value); }, enumerable: true, configurable: true }); // inherit from parent package or create a new RequestManager if (args[0] && args[0]._requestManager) { pkg._requestManager = args[0]._requestManager; } else { pkg._requestManager = new requestManager.Manager(args[0], args[1]); } // add givenProvider pkg.givenProvider = requestManager.Manager.givenProvider; pkg.providers = requestManager.Manager.providers; pkg._provider = pkg._requestManager.provider; // add SETPROVIDER function (don't overwrite if already existing) if (!pkg.setProvider) { pkg.setProvider = (provider, net) => { pkg._requestManager.setProvider(provider, net); pkg._provider = pkg._requestManager.provider; return true; }; } pkg.setRequestManager = (manager) => { pkg._requestManager = manager; pkg._provider = manager.provider; }; // attach batch request creation pkg.BatchRequest = requestManager.BatchManager.bind(null, pkg._requestManager); // attach extend function pkg.extend = extend(pkg); }; const addProviders = (pkg) => { pkg.givenProvider = requestManager.Manager.givenProvider; pkg.providers = requestManager.Manager.providers; }; module.exports = { packageInit, addProviders }; /***/ }), /***/ 74241: /*!********************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-abi/lib/index.js ***! \********************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Marek Kotewicz * @author Fabian Vogelsteller * @date 2018 */ var Buffer = __webpack_require__(/*! buffer */ 3875).Buffer; var utils = __webpack_require__(/*! web3-utils */ 60819); var EthersAbiCoder = __webpack_require__(/*! @ethersproject/abi */ 7910).AbiCoder; var ParamType = __webpack_require__(/*! @ethersproject/abi */ 7910).ParamType; var ethersAbiCoder = new EthersAbiCoder(function (type, value) { if (type.match(/^u?int/) && !Array.isArray(value) && (!(!!value && typeof value === 'object') || value.constructor.name !== 'BN')) { return value.toString(); } return value; }); // result method function Result() { } /** * ABICoder prototype should be used to encode/decode solidity params of any type */ var ABICoder = function () { }; /** * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. * * @method encodeFunctionSignature * @param {String|Object} functionName * @return {String} encoded function name */ ABICoder.prototype.encodeFunctionSignature = function (functionName) { if (typeof functionName === 'function' || typeof functionName === 'object' && functionName) { functionName = utils._jsonInterfaceMethodToString(functionName); } return utils.sha3(functionName).slice(0, 10); }; /** * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. * * @method encodeEventSignature * @param {String|Object} functionName * @return {String} encoded function name */ ABICoder.prototype.encodeEventSignature = function (functionName) { if (typeof functionName === 'function' || typeof functionName === 'object' && functionName) { functionName = utils._jsonInterfaceMethodToString(functionName); } return utils.sha3(functionName); }; /** * Should be used to encode plain param * * @method encodeParameter * * @param {String|Object} type * @param {any} param * * @return {String} encoded plain param */ ABICoder.prototype.encodeParameter = function (type, param) { return this.encodeParameters([type], [param]); }; /** * Should be used to encode list of params * * @method encodeParameters * * @param {Array} types * @param {Array} params * * @return {String} encoded list of params */ ABICoder.prototype.encodeParameters = function (types, params) { var self = this; types = self.mapTypes(types); params = params.map(function (param, index) { let type = types[index]; if (typeof type === 'object' && type.type) { // We may get a named type of shape {name, type} type = type.type; } param = self.formatParam(type, param); // Format params for tuples if (typeof type === 'string' && type.includes('tuple')) { const coder = ethersAbiCoder._getCoder(ParamType.from(type)); const modifyParams = (coder, param) => { if (coder.name === 'array') { return param.map(p => modifyParams(ethersAbiCoder._getCoder(ParamType.from(coder.type.replace('[]', ''))), p)); } coder.coders.forEach((c, i) => { if (c.name === 'tuple') { modifyParams(c, param[i]); } else { param[i] = self.formatParam(c.name, param[i]); } }); }; modifyParams(coder, param); } return param; }); return ethersAbiCoder.encode(types, params); }; /** * Map types if simplified format is used * * @method mapTypes * @param {Array} types * @return {Array} */ ABICoder.prototype.mapTypes = function (types) { var self = this; var mappedTypes = []; types.forEach(function (type) { // Remap `function` type params to bytes24 since Ethers does not // recognize former type. Solidity docs say `Function` is a bytes24 // encoding the contract address followed by the function selector hash. if (typeof type === 'object' && type.type === 'function') { type = Object.assign({}, type, { type: "bytes24" }); } if (self.isSimplifiedStructFormat(type)) { var structName = Object.keys(type)[0]; mappedTypes.push(Object.assign(self.mapStructNameAndType(structName), { components: self.mapStructToCoderFormat(type[structName]) })); return; } mappedTypes.push(type); }); return mappedTypes; }; /** * Check if type is simplified struct format * * @method isSimplifiedStructFormat * @param {string | Object} type * @returns {boolean} */ ABICoder.prototype.isSimplifiedStructFormat = function (type) { return typeof type === 'object' && typeof type.components === 'undefined' && typeof type.name === 'undefined'; }; /** * Maps the correct tuple type and name when the simplified format in encode/decodeParameter is used * * @method mapStructNameAndType * @param {string} structName * @return {{type: string, name: *}} */ ABICoder.prototype.mapStructNameAndType = function (structName) { var type = 'tuple'; if (structName.indexOf('[]') > -1) { type = 'tuple[]'; structName = structName.slice(0, -2); } return { type: type, name: structName }; }; /** * Maps the simplified format in to the expected format of the ABICoder * * @method mapStructToCoderFormat * @param {Object} struct * @return {Array} */ ABICoder.prototype.mapStructToCoderFormat = function (struct) { var self = this; var components = []; Object.keys(struct).forEach(function (key) { if (typeof struct[key] === 'object') { components.push(Object.assign(self.mapStructNameAndType(key), { components: self.mapStructToCoderFormat(struct[key]) })); return; } components.push({ name: key, type: struct[key] }); }); return components; }; /** * Handle some formatting of params for backwards compatability with Ethers V4 * * @method formatParam * @param {String} - type * @param {any} - param * @return {any} - The formatted param */ ABICoder.prototype.formatParam = function (type, param) { const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); const paramTypeBytesArray = new RegExp(/^bytes([0-9]*)\[\]$/); const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); const paramTypeNumberArray = new RegExp(/^(u?int)([0-9]*)\[\]$/); // Format BN to string if (utils.isBN(param) || utils.isBigNumber(param)) { return param.toString(10); } if (type.match(paramTypeBytesArray) || type.match(paramTypeNumberArray)) { return param.map(p => this.formatParam(type.replace('[]', ''), p)); } // Format correct width for u?int[0-9]* let match = type.match(paramTypeNumber); if (match) { let size = parseInt(match[2] || "256"); if (size / 8 < param.length) { // pad to correct bit width param = utils.leftPad(param, size); } } // Format correct length for bytes[0-9]+ match = type.match(paramTypeBytes); if (match) { if (Buffer.isBuffer(param)) { param = utils.toHex(param); } // format to correct length let size = parseInt(match[1]); if (size) { let maxSize = size * 2; if (param.substring(0, 2) === '0x') { maxSize += 2; } if (param.length < maxSize) { // pad to correct length param = utils.rightPad(param, size * 2); } } // format odd-length bytes to even-length if (param.length % 2 === 1) { param = '0x0' + param.substring(2); } } return param; }; /** * Encodes a function call from its json interface and parameters. * * @method encodeFunctionCall * @param {Array} jsonInterface * @param {Array} params * @return {String} The encoded ABI for this function call */ ABICoder.prototype.encodeFunctionCall = function (jsonInterface, params) { return this.encodeFunctionSignature(jsonInterface) + this.encodeParameters(jsonInterface.inputs, params).replace('0x', ''); }; /** * Should be used to decode bytes to plain param * * @method decodeParameter * @param {String} type * @param {String} bytes * @return {Object} plain param */ ABICoder.prototype.decodeParameter = function (type, bytes) { return this.decodeParameters([type], bytes)[0]; }; /** * Should be used to decode list of params * * @method decodeParameter * @param {Array} outputs * @param {String} bytes * @return {Array} array of plain params */ ABICoder.prototype.decodeParameters = function (outputs, bytes) { return this.decodeParametersWith(outputs, bytes, false); }; /** * Should be used to decode list of params * * @method decodeParameter * @param {Array} outputs * @param {String} bytes * @param {Boolean} loose * @return {Array} array of plain params */ ABICoder.prototype.decodeParametersWith = function (outputs, bytes, loose) { if (outputs.length > 0 && (!bytes || bytes === '0x' || bytes === '0X')) { throw new Error('Returned values aren\'t valid, did it run Out of Gas? ' + 'You might also see this error if you are not using the ' + 'correct ABI for the contract you are retrieving data from, ' + 'requesting data from a block number that does not exist, ' + 'or querying a node which is not fully synced.'); } var res = ethersAbiCoder.decode(this.mapTypes(outputs), '0x' + bytes.replace(/0x/i, ''), loose); var returnValue = new Result(); returnValue.__length__ = 0; outputs.forEach(function (output, i) { var decodedValue = res[returnValue.__length__]; decodedValue = (decodedValue === '0x') ? null : decodedValue; returnValue[i] = decodedValue; if ((typeof output === 'function' || !!output && typeof output === 'object') && output.name) { returnValue[output.name] = decodedValue; } returnValue.__length__++; }); return returnValue; }; /** * Decodes events non- and indexed parameters. * * @method decodeLog * @param {Object} inputs * @param {String} data * @param {Array} topics * @return {Array} array of plain params */ ABICoder.prototype.decodeLog = function (inputs, data, topics) { var _this = this; topics = Array.isArray(topics) ? topics : [topics]; data = data || ''; var notIndexedInputs = []; var indexedParams = []; var topicCount = 0; // TODO check for anonymous logs? inputs.forEach(function (input, i) { if (input.indexed) { indexedParams[i] = (['bool', 'int', 'uint', 'address', 'fixed', 'ufixed'].find(function (staticType) { return input.type.indexOf(staticType) !== -1; })) ? _this.decodeParameter(input.type, topics[topicCount]) : topics[topicCount]; topicCount++; } else { notIndexedInputs[i] = input; } }); var nonIndexedData = data; var notIndexedParams = (nonIndexedData) ? this.decodeParametersWith(notIndexedInputs, nonIndexedData, true) : []; var returnValue = new Result(); returnValue.__length__ = 0; inputs.forEach(function (res, i) { returnValue[i] = (res.type === 'string') ? '' : null; if (typeof notIndexedParams[i] !== 'undefined') { returnValue[i] = notIndexedParams[i]; } if (typeof indexedParams[i] !== 'undefined') { returnValue[i] = indexedParams[i]; } if (res.name) { returnValue[res.name] = returnValue[i]; } returnValue.__length__++; }); return returnValue; }; var coder = new ABICoder(); module.exports = coder; /***/ }), /***/ 2769: /*!*************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-accounts/lib/index.js ***! \*************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file accounts.js * @author Fabian Vogelsteller * @date 2017 */ var core = __webpack_require__(/*! web3-core */ 79517); var Method = __webpack_require__(/*! web3-core-method */ 50202); var Account = __webpack_require__(/*! eth-lib/lib/account */ 74450); var cryp = (typeof global === 'undefined') ? __webpack_require__(/*! crypto-browserify */ 19726) : __webpack_require__(/*! crypto */ 19726); var scrypt = __webpack_require__(/*! scrypt-js */ 21719); var uuid = __webpack_require__(/*! uuid */ 55599); var utils = __webpack_require__(/*! web3-utils */ 60819); var helpers = __webpack_require__(/*! web3-core-helpers */ 20176); var { TransactionFactory } = __webpack_require__(/*! @ethereumjs/tx */ 50470); var Common = __webpack_require__(/*! @ethereumjs/common */ 21669).default; var HardForks = __webpack_require__(/*! @ethereumjs/common */ 21669).Hardfork; var ethereumjsUtil = __webpack_require__(/*! ethereumjs-util */ 34692); var isNot = function (value) { return (typeof value === 'undefined') || value === null; }; var Accounts = function Accounts() { var _this = this; // sets _requestmanager core.packageInit(this, arguments); // remove unecessary core functions delete this.BatchRequest; delete this.extend; var _ethereumCall = [ new Method({ name: 'getNetworkId', call: 'net_version', params: 0, outputFormatter: parseInt }), new Method({ name: 'getChainId', call: 'eth_chainId', params: 0, outputFormatter: utils.hexToNumber }), new Method({ name: 'getGasPrice', call: 'eth_gasPrice', params: 0 }), new Method({ name: 'getTransactionCount', call: 'eth_getTransactionCount', params: 2, inputFormatter: [function (address) { if (utils.isAddress(address)) { return address; } else { throw new Error('Address ' + address + ' is not a valid address to get the "transactionCount".'); } }, function () { return 'latest'; }] }), new Method({ name: 'getBlockByNumber', call: 'eth_getBlockByNumber', params: 2, inputFormatter: [function (blockNumber) { return blockNumber ? utils.toHex(blockNumber) : 'latest'; }, function () { return false; }] }), ]; // attach methods to this._ethereumCall this._ethereumCall = {}; _ethereumCall.forEach((method) => { method.attachToObject(_this._ethereumCall); method.setRequestManager(_this._requestManager); }); this.wallet = new Wallet(this); }; Accounts.prototype._addAccountFunctions = function (account) { var _this = this; // add sign functions account.signTransaction = function signTransaction(tx, callback) { return _this.signTransaction(tx, account.privateKey, callback); }; account.sign = function sign(data) { return _this.sign(data, account.privateKey); }; account.encrypt = function encrypt(password, options) { return _this.encrypt(account.privateKey, password, options); }; return account; }; Accounts.prototype.create = function create(entropy) { return this._addAccountFunctions(Account.create(entropy || utils.randomHex(32))); }; Accounts.prototype.privateKeyToAccount = function privateKeyToAccount(privateKey, ignoreLength) { if (!privateKey.startsWith('0x')) { privateKey = '0x' + privateKey; } // 64 hex characters + hex-prefix if (!ignoreLength && privateKey.length !== 66) { throw new Error("Private key must be 32 bytes long"); } return this._addAccountFunctions(Account.fromPrivate(privateKey)); }; Accounts.prototype.signTransaction = function signTransaction(tx, privateKey, callback) { var _this = this, error = false, transactionOptions = {}, hasTxSigningOptions = !!(tx && ((tx.chain && tx.hardfork) || tx.common)); callback = callback || function () { }; if (!tx) { error = new Error('No transaction object given!'); callback(error); return Promise.reject(error); } function signed(tx) { const error = _validateTransactionForSigning(tx); if (error) { callback(error); return Promise.reject(error); } try { var transaction = helpers.formatters.inputCallFormatter(Object.assign({}, tx)); transaction.data = transaction.data || '0x'; transaction.value = transaction.value || '0x'; transaction.gasLimit = transaction.gasLimit || transaction.gas; if (transaction.type === '0x1' && transaction.accessList === undefined) transaction.accessList = []; // Because tx has no @ethereumjs/tx signing options we use fetched vals. if (!hasTxSigningOptions) { transactionOptions.common = Common.forCustomChain('mainnet', { name: 'custom-network', networkId: transaction.networkId, chainId: transaction.chainId }, transaction.hardfork || HardForks.London); delete transaction.networkId; } else { if (transaction.common) { transactionOptions.common = Common.forCustomChain(transaction.common.baseChain || 'mainnet', { name: transaction.common.customChain.name || 'custom-network', networkId: transaction.common.customChain.networkId, chainId: transaction.common.customChain.chainId }, transaction.common.hardfork || HardForks.London); delete transaction.common; } if (transaction.chain) { transactionOptions.chain = transaction.chain; delete transaction.chain; } if (transaction.hardfork) { transactionOptions.hardfork = transaction.hardfork; delete transaction.hardfork; } } if (privateKey.startsWith('0x')) { privateKey = privateKey.substring(2); } var ethTx = TransactionFactory.fromTxData(transaction, transactionOptions); var signedTx = ethTx.sign(Buffer.from(privateKey, 'hex')); var validationErrors = signedTx.validate(true); if (validationErrors.length > 0) { let errorString = 'Signer Error: '; for (const validationError of validationErrors) { errorString += `${errorString} ${validationError}.`; } throw new Error(errorString); } var rlpEncoded = signedTx.serialize().toString('hex'); var rawTransaction = '0x' + rlpEncoded; var transactionHash = utils.keccak256(rawTransaction); var result = { messageHash: '0x' + Buffer.from(signedTx.getMessageToSign(true)).toString('hex'), v: '0x' + signedTx.v.toString('hex'), r: '0x' + signedTx.r.toString('hex'), s: '0x' + signedTx.s.toString('hex'), rawTransaction: rawTransaction, transactionHash: transactionHash }; callback(null, result); return result; } catch (e) { callback(e); return Promise.reject(e); } } tx.type = _handleTxType(tx); // Resolve immediately if nonce, chainId, price and signing options are provided if (tx.nonce !== undefined && tx.chainId !== undefined && (tx.gasPrice !== undefined || (tx.maxFeePerGas !== undefined && tx.maxPriorityFeePerGas !== undefined)) && hasTxSigningOptions) { return Promise.resolve(signed(tx)); } // Otherwise, get the missing info from the Ethereum Node return Promise.all([ isNot(tx.chainId) ? _this._ethereumCall.getChainId() : tx.chainId, isNot(tx.nonce) ? _this._ethereumCall.getTransactionCount(_this.privateKeyToAccount(privateKey).address) : tx.nonce, isNot(hasTxSigningOptions) ? _this._ethereumCall.getNetworkId() : 1, _handleTxPricing(_this, tx) ]).then(function (args) { if (isNot(args[0]) || isNot(args[1]) || isNot(args[2]) || isNot(args[3])) { throw new Error('One of the values "chainId", "networkId", "gasPrice", or "nonce" couldn\'t be fetched: ' + JSON.stringify(args)); } return signed({ ...tx, chainId: args[0], nonce: args[1], networkId: args[2], ...args[3] // Will either be gasPrice or maxFeePerGas and maxPriorityFeePerGas }); }); }; function _validateTransactionForSigning(tx) { if (tx.common && (tx.chain && tx.hardfork)) { return new Error('Please provide the @ethereumjs/common object or the chain and hardfork property but not all together.'); } if ((tx.chain && !tx.hardfork) || (tx.hardfork && !tx.chain)) { return new Error('When specifying chain and hardfork, both values must be defined. ' + 'Received "chain": ' + tx.chain + ', "hardfork": ' + tx.hardfork); } if ((!tx.gas && !tx.gasLimit) && (!tx.maxPriorityFeePerGas && !tx.maxFeePerGas)) { return new Error('"gas" is missing'); } if (tx.gas && tx.gasPrice) { if (tx.gas < 0 || tx.gasPrice < 0) { return new Error('Gas or gasPrice is lower than 0'); } } else { if (tx.maxPriorityFeePerGas < 0 || tx.maxFeePerGas < 0) { return new Error('maxPriorityFeePerGas or maxFeePerGas is lower than 0'); } } if (tx.nonce < 0 || tx.chainId < 0) { return new Error('Nonce or chainId is lower than 0'); } return; } function _handleTxType(tx) { // Taken from https://github.com/ethers-io/ethers.js/blob/2a7ce0e72a1e0c9469e10392b0329e75e341cf18/packages/abstract-signer/src.ts/index.ts#L215 const hasEip1559 = (tx.maxFeePerGas !== undefined || tx.maxPriorityFeePerGas !== undefined); let txType; if (tx.type !== undefined) { txType = utils.toHex(tx.type); } else if (tx.type === undefined && hasEip1559) { txType = '0x2'; } if (tx.gasPrice !== undefined && (txType === '0x2' || hasEip1559)) throw Error("eip-1559 transactions don't support gasPrice"); if ((txType === '0x1' || txType === '0x0') && hasEip1559) throw Error("pre-eip-1559 transaction don't support maxFeePerGas/maxPriorityFeePerGas"); if (hasEip1559 || ((tx.common && tx.common.hardfork && tx.common.hardfork.toLowerCase() === HardForks.London) || (tx.hardfork && tx.hardfork.toLowerCase() === HardForks.London))) { txType = '0x2'; } else if (tx.accessList || ((tx.common && tx.common.hardfork && tx.common.hardfork.toLowerCase() === HardForks.Berlin) || (tx.hardfork && tx.hardfork.toLowerCase() === HardForks.Berlin))) { txType = '0x1'; } return txType; } function _handleTxPricing(_this, tx) { return new Promise((resolve, reject) => { try { if ((tx.type === undefined || tx.type < '0x2') && tx.gasPrice !== undefined) { // Legacy transaction, return provided gasPrice resolve({ gasPrice: tx.gasPrice }); } else { Promise.all([ _this._ethereumCall.getBlockByNumber(), _this._ethereumCall.getGasPrice() ]).then(responses => { const [block, gasPrice] = responses; if ((tx.type === '0x2') && block && block.baseFeePerGas) { // The network supports EIP-1559 // Taken from https://github.com/ethers-io/ethers.js/blob/ba6854bdd5a912fe873d5da494cb5c62c190adde/packages/abstract-provider/src.ts/index.ts#L230 let maxPriorityFeePerGas, maxFeePerGas; if (tx.gasPrice) { // Using legacy gasPrice property on an eip-1559 network, // so use gasPrice as both fee properties maxPriorityFeePerGas = tx.gasPrice; maxFeePerGas = tx.gasPrice; delete tx.gasPrice; } else { maxPriorityFeePerGas = tx.maxPriorityFeePerGas || '0x9502F900'; // 2.5 Gwei maxFeePerGas = tx.maxFeePerGas || utils.toHex(utils.toBN(block.baseFeePerGas) .mul(utils.toBN(2)) .add(utils.toBN(maxPriorityFeePerGas))); } resolve({ maxFeePerGas, maxPriorityFeePerGas }); } else { if (tx.maxPriorityFeePerGas || tx.maxFeePerGas) throw Error("Network doesn't support eip-1559"); resolve({ gasPrice }); } }); } } catch (error) { reject(error); } }); } /* jshint ignore:start */ Accounts.prototype.recoverTransaction = function recoverTransaction(rawTx, txOptions = {}) { // Rely on EthereumJs/tx to determine the type of transaction const data = Buffer.from(rawTx.slice(2), "hex"); const tx = TransactionFactory.fromSerializedData(data); //update checksum return utils.toChecksumAddress(tx.getSenderAddress().toString("hex")); }; /* jshint ignore:end */ Accounts.prototype.hashMessage = function hashMessage(data) { var messageHex = utils.isHexStrict(data) ? data : utils.utf8ToHex(data); var messageBytes = utils.hexToBytes(messageHex); var messageBuffer = Buffer.from(messageBytes); var preamble = '\x19Ethereum Signed Message:\n' + messageBytes.length; var preambleBuffer = Buffer.from(preamble); var ethMessage = Buffer.concat([preambleBuffer, messageBuffer]); return ethereumjsUtil.bufferToHex(ethereumjsUtil.keccak256(ethMessage)); }; Accounts.prototype.sign = function sign(data, privateKey) { if (!privateKey.startsWith('0x')) { privateKey = '0x' + privateKey; } // 64 hex characters + hex-prefix if (privateKey.length !== 66) { throw new Error("Private key must be 32 bytes long"); } var hash = this.hashMessage(data); var signature = Account.sign(hash, privateKey); var vrs = Account.decodeSignature(signature); return { message: data, messageHash: hash, v: vrs[0], r: vrs[1], s: vrs[2], signature: signature }; }; Accounts.prototype.recover = function recover(message, signature, preFixed) { var args = [].slice.apply(arguments); if (!!message && typeof message === 'object') { return this.recover(message.messageHash, Account.encodeSignature([message.v, message.r, message.s]), true); } if (!preFixed) { message = this.hashMessage(message); } if (args.length >= 4) { preFixed = args.slice(-1)[0]; preFixed = typeof preFixed === 'boolean' ? !!preFixed : false; return this.recover(message, Account.encodeSignature(args.slice(1, 4)), preFixed); // v, r, s } return Account.recover(message, signature); }; // Taken from https://github.com/ethereumjs/ethereumjs-wallet Accounts.prototype.decrypt = function (v3Keystore, password, nonStrict) { /* jshint maxcomplexity: 10 */ if (!(typeof password === 'string')) { throw new Error('No password given.'); } var json = (!!v3Keystore && typeof v3Keystore === 'object') ? v3Keystore : JSON.parse(nonStrict ? v3Keystore.toLowerCase() : v3Keystore); if (json.version !== 3) { throw new Error('Not a valid V3 wallet'); } var derivedKey; var kdfparams; if (json.crypto.kdf === 'scrypt') { kdfparams = json.crypto.kdfparams; // FIXME: support progress reporting callback derivedKey = scrypt.syncScrypt(Buffer.from(password), Buffer.from(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); } else if (json.crypto.kdf === 'pbkdf2') { kdfparams = json.crypto.kdfparams; if (kdfparams.prf !== 'hmac-sha256') { throw new Error('Unsupported parameters to PBKDF2'); } derivedKey = cryp.pbkdf2Sync(Buffer.from(password), Buffer.from(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256'); } else { throw new Error('Unsupported key derivation scheme'); } var ciphertext = Buffer.from(json.crypto.ciphertext, 'hex'); var mac = utils.sha3(Buffer.from([...derivedKey.slice(16, 32), ...ciphertext])).replace('0x', ''); if (mac !== json.crypto.mac) { throw new Error('Key derivation failed - possibly wrong password'); } var decipher = cryp.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), Buffer.from(json.crypto.cipherparams.iv, 'hex')); var seed = '0x' + Buffer.from([...decipher.update(ciphertext), ...decipher.final()]).toString('hex'); return this.privateKeyToAccount(seed, true); }; Accounts.prototype.encrypt = function (privateKey, password, options) { /* jshint maxcomplexity: 20 */ var account = this.privateKeyToAccount(privateKey, true); options = options || {}; var salt = options.salt || cryp.randomBytes(32); var iv = options.iv || cryp.randomBytes(16); var derivedKey; var kdf = options.kdf || 'scrypt'; var kdfparams = { dklen: options.dklen || 32, salt: salt.toString('hex') }; if (kdf === 'pbkdf2') { kdfparams.c = options.c || 262144; kdfparams.prf = 'hmac-sha256'; derivedKey = cryp.pbkdf2Sync(Buffer.from(password), Buffer.from(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256'); } else if (kdf === 'scrypt') { // FIXME: support progress reporting callback kdfparams.n = options.n || 8192; // 2048 4096 8192 16384 kdfparams.r = options.r || 8; kdfparams.p = options.p || 1; derivedKey = scrypt.syncScrypt(Buffer.from(password), Buffer.from(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); } else { throw new Error('Unsupported kdf'); } var cipher = cryp.createCipheriv(options.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv); if (!cipher) { throw new Error('Unsupported cipher'); } var ciphertext = Buffer.from([ ...cipher.update(Buffer.from(account.privateKey.replace('0x', ''), 'hex')), ...cipher.final() ]); var mac = utils.sha3(Buffer.from([...derivedKey.slice(16, 32), ...ciphertext])).replace('0x', ''); return { version: 3, id: uuid.v4({ random: options.uuid || cryp.randomBytes(16) }), address: account.address.toLowerCase().replace('0x', ''), crypto: { ciphertext: ciphertext.toString('hex'), cipherparams: { iv: iv.toString('hex') }, cipher: options.cipher || 'aes-128-ctr', kdf: kdf, kdfparams: kdfparams, mac: mac.toString('hex') } }; }; // Note: this is trying to follow closely the specs on // http://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html function Wallet(accounts) { this._accounts = accounts; this.length = 0; this.defaultKeyName = 'web3js_wallet'; } Wallet.prototype._findSafeIndex = function (pointer) { pointer = pointer || 0; if (this.hasOwnProperty(pointer)) { return this._findSafeIndex(pointer + 1); } else { return pointer; } }; Wallet.prototype._currentIndexes = function () { var keys = Object.keys(this); var indexes = keys .map(function (key) { return parseInt(key); }) .filter(function (n) { return (n < 9e20); }); return indexes; }; Wallet.prototype.create = function (numberOfAccounts, entropy) { for (var i = 0; i < numberOfAccounts; ++i) { this.add(this._accounts.create(entropy).privateKey); } return this; }; Wallet.prototype.add = function (account) { if (typeof account === 'string') { account = this._accounts.privateKeyToAccount(account); } if (!this[account.address]) { account = this._accounts.privateKeyToAccount(account.privateKey); account.index = this._findSafeIndex(); this[account.index] = account; this[account.address] = account; this[account.address.toLowerCase()] = account; this.length++; return account; } else { return this[account.address]; } }; Wallet.prototype.remove = function (addressOrIndex) { var account = this[addressOrIndex]; if (account && account.address) { // address this[account.address].privateKey = null; delete this[account.address]; // address lowercase this[account.address.toLowerCase()].privateKey = null; delete this[account.address.toLowerCase()]; // index this[account.index].privateKey = null; delete this[account.index]; this.length--; return true; } else { return false; } }; Wallet.prototype.clear = function () { var _this = this; var indexes = this._currentIndexes(); indexes.forEach(function (index) { _this.remove(index); }); return this; }; Wallet.prototype.encrypt = function (password, options) { var _this = this; var indexes = this._currentIndexes(); var accounts = indexes.map(function (index) { return _this[index].encrypt(password, options); }); return accounts; }; Wallet.prototype.decrypt = function (encryptedWallet, password) { var _this = this; encryptedWallet.forEach(function (keystore) { var account = _this._accounts.decrypt(keystore, password); if (account) { _this.add(account); } else { throw new Error('Couldn\'t decrypt accounts. Password wrong?'); } }); return this; }; Wallet.prototype.save = function (password, keyName) { localStorage.setItem(keyName || this.defaultKeyName, JSON.stringify(this.encrypt(password))); return true; }; Wallet.prototype.load = function (password, keyName) { var keystore = localStorage.getItem(keyName || this.defaultKeyName); if (keystore) { try { keystore = JSON.parse(keystore); } catch (e) { } } return this.decrypt(keystore || [], password); }; if (!storageAvailable('localStorage')) { delete Wallet.prototype.save; delete Wallet.prototype.load; } /** * Checks whether a storage type is available or not * For more info on how this works, please refer to MDN documentation * https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Feature-detecting_localStorage * * @method storageAvailable * @param {String} type the type of storage ('localStorage', 'sessionStorage') * @returns {Boolean} a boolean indicating whether the specified storage is available or not */ function storageAvailable(type) { var storage; try { storage = window[type]; var x = '__storage_test__'; storage.setItem(x, x); storage.removeItem(x); return true; } catch (e) { return e && ( // everything except Firefox e.code === 22 || // Firefox e.code === 1014 || // test name field too, because code might not be present // everything except Firefox e.name === 'QuotaExceededError' || // Firefox e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && // acknowledge QuotaExceededError only if there's something already stored (storage && storage.length !== 0); } } module.exports = Accounts; /***/ }), /***/ 86156: /*!*************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-contract/lib/index.js ***! \*************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var console = __webpack_require__(/*! console-browserify */ 88883); /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file contract.js * * To initialize a contract use: * * var Contract = require('web3-eth-contract'); * Contract.setProvider('ws://localhost:8546'); * var contract = new Contract(abi, address, ...); * * @author Fabian Vogelsteller * @date 2017 */ var core = __webpack_require__(/*! web3-core */ 79517); var Method = __webpack_require__(/*! web3-core-method */ 50202); var utils = __webpack_require__(/*! web3-utils */ 60819); var Subscription = __webpack_require__(/*! web3-core-subscriptions */ 54923).subscription; var formatters = __webpack_require__(/*! web3-core-helpers */ 20176).formatters; var errors = __webpack_require__(/*! web3-core-helpers */ 20176).errors; var promiEvent = __webpack_require__(/*! web3-core-promievent */ 24817); var abi = __webpack_require__(/*! web3-eth-abi */ 74241); /** * Should be called to create new contract instance * * @method Contract * @constructor * @param {Array} jsonInterface * @param {String} address * @param {Object} options */ var Contract = function Contract(jsonInterface, address, options) { var _this = this, args = Array.prototype.slice.call(arguments); if (!(this instanceof Contract)) { throw new Error('Please use the "new" keyword to instantiate a web3.eth.Contract() object!'); } this.setProvider = function () { core.packageInit(_this, arguments); _this.clearSubscriptions = _this._requestManager.clearSubscriptions; }; // sets _requestmanager core.packageInit(this, [this.constructor]); this.clearSubscriptions = this._requestManager.clearSubscriptions; if (!jsonInterface || !(Array.isArray(jsonInterface))) { throw errors.ContractMissingABIError(); } // create the options object this.options = {}; var lastArg = args[args.length - 1]; if (!!lastArg && typeof lastArg === 'object' && !Array.isArray(lastArg)) { options = lastArg; this.options = { ...this.options, ...this._getOrSetDefaultOptions(options) }; if (!!address && typeof address === 'object') { address = null; } } // set address Object.defineProperty(this.options, 'address', { set: function (value) { if (value) { _this._address = utils.toChecksumAddress(formatters.inputAddressFormatter(value)); } }, get: function () { return _this._address; }, enumerable: true }); // add method and event signatures, when the jsonInterface gets set Object.defineProperty(this.options, 'jsonInterface', { set: function (value) { _this.methods = {}; _this.events = {}; _this._jsonInterface = value.map(function (method) { var func, funcName; // make constant and payable backwards compatible method.constant = (method.stateMutability === "view" || method.stateMutability === "pure" || method.constant); method.payable = (method.stateMutability === "payable" || method.payable); if (method.name) { funcName = utils._jsonInterfaceMethodToString(method); } // function if (method.type === 'function') { method.signature = abi.encodeFunctionSignature(funcName); func = _this._createTxObject.bind({ method: method, parent: _this }); // add method only if not one already exists if (!_this.methods[method.name]) { _this.methods[method.name] = func; } else { var cascadeFunc = _this._createTxObject.bind({ method: method, parent: _this, nextMethod: _this.methods[method.name] }); _this.methods[method.name] = cascadeFunc; } // definitely add the method based on its signature _this.methods[method.signature] = func; // add method by name _this.methods[funcName] = func; // event } else if (method.type === 'event') { method.signature = abi.encodeEventSignature(funcName); var event = _this._on.bind(_this, method.signature); // add method only if not already exists if (!_this.events[method.name] || _this.events[method.name].name === 'bound ') _this.events[method.name] = event; // definitely add the method based on its signature _this.events[method.signature] = event; // add event by name _this.events[funcName] = event; } return method; }); // add allEvents _this.events.allEvents = _this._on.bind(_this, 'allevents'); return _this._jsonInterface; }, get: function () { return _this._jsonInterface; }, enumerable: true }); // get default account from the Class var defaultAccount = this.constructor.defaultAccount; var defaultBlock = this.constructor.defaultBlock || 'latest'; Object.defineProperty(this, 'handleRevert', { get: function () { if (_this.options.handleRevert === false || _this.options.handleRevert === true) { return _this.options.handleRevert; } return this.constructor.handleRevert; }, set: function (val) { _this.options.handleRevert = val; }, enumerable: true }); Object.defineProperty(this, 'defaultCommon', { get: function () { return _this.options.common || this.constructor.defaultCommon; }, set: function (val) { _this.options.common = val; }, enumerable: true }); Object.defineProperty(this, 'defaultHardfork', { get: function () { return _this.options.hardfork || this.constructor.defaultHardfork; }, set: function (val) { _this.options.hardfork = val; }, enumerable: true }); Object.defineProperty(this, 'defaultChain', { get: function () { return _this.options.chain || this.constructor.defaultChain; }, set: function (val) { _this.options.chain = val; }, enumerable: true }); Object.defineProperty(this, 'transactionPollingTimeout', { get: function () { if (_this.options.transactionPollingTimeout === 0) { return _this.options.transactionPollingTimeout; } return _this.options.transactionPollingTimeout || this.constructor.transactionPollingTimeout; }, set: function (val) { _this.options.transactionPollingTimeout = val; }, enumerable: true }); Object.defineProperty(this, 'transactionConfirmationBlocks', { get: function () { if (_this.options.transactionConfirmationBlocks === 0) { return _this.options.transactionConfirmationBlocks; } return _this.options.transactionConfirmationBlocks || this.constructor.transactionConfirmationBlocks; }, set: function (val) { _this.options.transactionConfirmationBlocks = val; }, enumerable: true }); Object.defineProperty(this, 'transactionBlockTimeout', { get: function () { if (_this.options.transactionBlockTimeout === 0) { return _this.options.transactionBlockTimeout; } return _this.options.transactionBlockTimeout || this.constructor.transactionBlockTimeout; }, set: function (val) { _this.options.transactionBlockTimeout = val; }, enumerable: true }); Object.defineProperty(this, 'defaultAccount', { get: function () { return defaultAccount; }, set: function (val) { if (val) { defaultAccount = utils.toChecksumAddress(formatters.inputAddressFormatter(val)); } return val; }, enumerable: true }); Object.defineProperty(this, 'defaultBlock', { get: function () { return defaultBlock; }, set: function (val) { defaultBlock = val; return val; }, enumerable: true }); // properties this.methods = {}; this.events = {}; this._address = null; this._jsonInterface = []; // set getter/setter properties this.options.address = address; this.options.jsonInterface = jsonInterface; }; /** * Sets the new provider, creates a new requestManager, registers the "data" listener on the provider and sets the * accounts module for the Contract class. * * @method setProvider * * @param {string|provider} provider * @param {Accounts} accounts * * @returns void */ Contract.setProvider = function (provider, accounts) { // Contract.currentProvider = provider; core.packageInit(this, [provider]); this._ethAccounts = accounts; }; /** * Get the callback and modify the array if necessary * * @method _getCallback * @param {Array} args * @return {Function} the callback */ Contract.prototype._getCallback = function getCallback(args) { if (args && !!args[args.length - 1] && typeof args[args.length - 1] === 'function') { return args.pop(); // modify the args array! } }; /** * Checks that no listener with name "newListener" or "removeListener" is added. * * @method _checkListener * @param {String} type * @param {String} event * @return {Object} the contract instance */ Contract.prototype._checkListener = function (type, event) { if (event === type) { throw errors.ContractReservedEventError(type); } }; /** * Use default values, if options are not available * * @method _getOrSetDefaultOptions * @param {Object} options the options gived by the user * @return {Object} the options with gaps filled by defaults */ Contract.prototype._getOrSetDefaultOptions = function getOrSetDefaultOptions(options) { var gasPrice = options.gasPrice ? String(options.gasPrice) : null; var from = options.from ? utils.toChecksumAddress(formatters.inputAddressFormatter(options.from)) : null; options.data = options.data || this.options.data; options.from = from || this.options.from; options.gasPrice = gasPrice || this.options.gasPrice; options.gas = options.gas || options.gasLimit || this.options.gas; // TODO replace with only gasLimit? delete options.gasLimit; return options; }; /** * Should be used to encode indexed params and options to one final object * * @method _encodeEventABI * @param {Object} event * @param {Object} options * @return {Object} everything combined together and encoded */ Contract.prototype._encodeEventABI = function (event, options) { options = options || {}; var filter = options.filter || {}, result = {}; ['fromBlock', 'toBlock'].filter(function (f) { return options[f] !== undefined; }).forEach(function (f) { result[f] = formatters.inputBlockNumberFormatter(options[f]); }); // use given topics if (Array.isArray(options.topics)) { result.topics = options.topics; // create topics based on filter } else { result.topics = []; // add event signature if (event && !event.anonymous && event.name !== 'ALLEVENTS') { result.topics.push(event.signature); } // add event topics (indexed arguments) if (event.name !== 'ALLEVENTS') { var indexedTopics = event.inputs.filter(function (i) { return i.indexed === true; }).map(function (i) { var value = filter[i.name]; if (!value) { return null; } // TODO: https://github.com/ethereum/web3.js/issues/344 // TODO: deal properly with components if (Array.isArray(value)) { return value.map(function (v) { return abi.encodeParameter(i.type, v); }); } return abi.encodeParameter(i.type, value); }); result.topics = result.topics.concat(indexedTopics); } if (!result.topics.length) delete result.topics; } if (this.options.address) { result.address = this.options.address.toLowerCase(); } return result; }; /** * Should be used to decode indexed params and options * * @method _decodeEventABI * @param {Object} data * @return {Object} result object with decoded indexed && not indexed params */ Contract.prototype._decodeEventABI = function (data) { var event = this; data.data = data.data || ''; data.topics = data.topics || []; var result = formatters.outputLogFormatter(data); // if allEvents get the right event if (event.name === 'ALLEVENTS') { event = event.jsonInterface.find(function (intf) { return (intf.signature === data.topics[0]); }) || { anonymous: true }; } // create empty inputs if none are present (e.g. anonymous events on allEvents) event.inputs = event.inputs || []; // Handle case where an event signature shadows the current ABI with non-identical // arg indexing. If # of topics doesn't match, event is anon. if (!event.anonymous) { let indexedInputs = 0; event.inputs.forEach(input => input.indexed ? indexedInputs++ : null); if (indexedInputs > 0 && (data.topics.length !== indexedInputs + 1)) { event = { anonymous: true, inputs: [] }; } } var argTopics = event.anonymous ? data.topics : data.topics.slice(1); result.returnValues = abi.decodeLog(event.inputs, data.data, argTopics); delete result.returnValues.__length__; // add name result.event = event.name; // add signature result.signature = (event.anonymous || !data.topics[0]) ? null : data.topics[0]; // move the data and topics to "raw" result.raw = { data: result.data, topics: result.topics }; delete result.data; delete result.topics; return result; }; /** * Encodes an ABI for a method, including signature or the method. * Or when constructor encodes only the constructor parameters. * * @method _encodeMethodABI * @param {Mixed} args the arguments to encode * @param {String} the encoded ABI */ Contract.prototype._encodeMethodABI = function _encodeMethodABI() { var methodSignature = this._method.signature, args = this.arguments || []; var signature = false, paramsABI = this._parent.options.jsonInterface.filter(function (json) { return ((methodSignature === 'constructor' && json.type === methodSignature) || ((json.signature === methodSignature || json.signature === methodSignature.replace('0x', '') || json.name === methodSignature) && json.type === 'function')); }).map(function (json) { var inputLength = (Array.isArray(json.inputs)) ? json.inputs.length : 0; if (inputLength !== args.length) { throw new Error('The number of arguments is not matching the methods required number. You need to pass ' + inputLength + ' arguments.'); } if (json.type === 'function') { signature = json.signature; } return Array.isArray(json.inputs) ? json.inputs : []; }).map(function (inputs) { return abi.encodeParameters(inputs, args).replace('0x', ''); })[0] || ''; // return constructor if (methodSignature === 'constructor') { if (!this._deployData) throw new Error('The contract has no contract data option set. This is necessary to append the constructor parameters.'); if (!this._deployData.startsWith('0x')) { this._deployData = '0x' + this._deployData; } return this._deployData + paramsABI; } // return method var returnValue = (signature) ? signature + paramsABI : paramsABI; if (!returnValue) { throw new Error('Couldn\'t find a matching contract method named "' + this._method.name + '".'); } return returnValue; }; /** * Decode method return values * * @method _decodeMethodReturn * @param {Array} outputs * @param {String} returnValues * @return {Object} decoded output return values */ Contract.prototype._decodeMethodReturn = function (outputs, returnValues) { if (!returnValues) { return null; } returnValues = returnValues.length >= 2 ? returnValues.slice(2) : returnValues; var result = abi.decodeParameters(outputs, returnValues); if (result.__length__ === 1) { return result[0]; } delete result.__length__; return result; }; /** * Deploys a contract and fire events based on its state: transactionHash, receipt * * All event listeners will be removed, once the last possible event is fired ("error", or "receipt") * * @method deploy * @param {Object} options * @param {Function} callback * @return {Object} EventEmitter possible events are "error", "transactionHash" and "receipt" */ Contract.prototype.deploy = function (options, callback) { options = options || {}; options.arguments = options.arguments || []; options = this._getOrSetDefaultOptions(options); // throw error, if no "data" is specified if (!options.data) { if (typeof callback === 'function') { return callback(errors.ContractMissingDeployDataError()); } throw errors.ContractMissingDeployDataError(); } var constructor = this.options.jsonInterface.find((method) => { return (method.type === 'constructor'); }) || {}; constructor.signature = 'constructor'; return this._createTxObject.apply({ method: constructor, parent: this, deployData: options.data, _ethAccounts: this.constructor._ethAccounts }, options.arguments); }; /** * Gets the event signature and outputFormatters * * @method _generateEventOptions * @param {Object} event * @param {Object} options * @param {Function} callback * @return {Object} the event options object */ Contract.prototype._generateEventOptions = function () { var args = Array.prototype.slice.call(arguments); // get the callback var callback = this._getCallback(args); // get the options var options = (!!args[args.length - 1] && typeof args[args.length - 1]) === 'object' ? args.pop() : {}; var eventName = (typeof args[0] === 'string') ? args[0] : 'allevents'; var event = (eventName.toLowerCase() === 'allevents') ? { name: 'ALLEVENTS', jsonInterface: this.options.jsonInterface } : this.options.jsonInterface.find(function (json) { return (json.type === 'event' && (json.name === eventName || json.signature === '0x' + eventName.replace('0x', ''))); }); if (!event) { throw errors.ContractEventDoesNotExistError(eventName); } if (!utils.isAddress(this.options.address)) { throw errors.ContractNoAddressDefinedError(); } return { params: this._encodeEventABI(event, options), event: event, callback: callback }; }; /** * Adds event listeners and creates a subscription, and remove it once its fired. * * @method clone * @return {Object} the event subscription */ Contract.prototype.clone = function () { return new this.constructor(this.options.jsonInterface, this.options.address, this.options); }; /** * Adds event listeners and creates a subscription, and remove it once its fired. * * @method once * @param {String} event * @param {Object} options * @param {Function} callback * @return {Object} the event subscription */ Contract.prototype.once = function (event, options, callback) { var args = Array.prototype.slice.call(arguments); // get the callback callback = this._getCallback(args); if (!callback) { throw errors.ContractOnceRequiresCallbackError(); } // don't allow fromBlock if (options) delete options.fromBlock; // don't return as once shouldn't provide "on" this._on(event, options, function (err, res, sub) { sub.unsubscribe(); if (typeof callback === 'function') { callback(err, res, sub); } }); return undefined; }; /** * Adds event listeners and creates a subscription. * * @method _on * * @param {String} event * @param {Object} options * @param {Function} callback * * @return {Object} the event subscription */ Contract.prototype._on = function () { var subOptions = this._generateEventOptions.apply(this, arguments); if (subOptions.params && subOptions.params.toBlock) { delete subOptions.params.toBlock; console.warn('Invalid option: toBlock. Use getPastEvents for specific range.'); } // prevent the event "newListener" and "removeListener" from being overwritten this._checkListener('newListener', subOptions.event.name); this._checkListener('removeListener', subOptions.event.name); // TODO check if listener already exists? and reuse subscription if options are the same. // create new subscription var subscription = new Subscription({ subscription: { params: 1, inputFormatter: [formatters.inputLogFormatter], outputFormatter: this._decodeEventABI.bind(subOptions.event), // DUBLICATE, also in web3-eth subscriptionHandler: function (output) { if (output.removed) { this.emit('changed', output); } else { this.emit('data', output); } if (typeof this.callback === 'function') { this.callback(null, output, this); } } }, type: 'eth', requestManager: this._requestManager }); subscription.subscribe('logs', subOptions.params, subOptions.callback || function () { }); return subscription; }; /** * Get past events from contracts * * @method getPastEvents * @param {String} event * @param {Object} options * @param {Function} callback * @return {Object} the promievent */ Contract.prototype.getPastEvents = function () { var subOptions = this._generateEventOptions.apply(this, arguments); var getPastLogs = new Method({ name: 'getPastLogs', call: 'eth_getLogs', params: 1, inputFormatter: [formatters.inputLogFormatter], outputFormatter: this._decodeEventABI.bind(subOptions.event) }); getPastLogs.setRequestManager(this._requestManager); var call = getPastLogs.buildCall(); getPastLogs = null; return call(subOptions.params, subOptions.callback); }; /** * returns the an object with call, send, estimate functions * * @method _createTxObject * @returns {Object} an object with functions to call the methods */ Contract.prototype._createTxObject = function _createTxObject() { var args = Array.prototype.slice.call(arguments); var txObject = {}; if (this.method.type === 'function') { txObject.call = this.parent._executeMethod.bind(txObject, 'call'); txObject.call.request = this.parent._executeMethod.bind(txObject, 'call', true); // to make batch requests } txObject.send = this.parent._executeMethod.bind(txObject, 'send'); txObject.send.request = this.parent._executeMethod.bind(txObject, 'send', true); // to make batch requests txObject.encodeABI = this.parent._encodeMethodABI.bind(txObject); txObject.estimateGas = this.parent._executeMethod.bind(txObject, 'estimate'); if (args && this.method.inputs && args.length !== this.method.inputs.length) { if (this.nextMethod) { return this.nextMethod.apply(null, args); } throw errors.InvalidNumberOfParams(args.length, this.method.inputs.length, this.method.name); } txObject.arguments = args || []; txObject._method = this.method; txObject._parent = this.parent; txObject._ethAccounts = this.parent.constructor._ethAccounts || this._ethAccounts; if (this.deployData) { txObject._deployData = this.deployData; } return txObject; }; /** * Generates the options for the execute call * * @method _processExecuteArguments * @param {Array} args * @param {Promise} defer */ Contract.prototype._processExecuteArguments = function _processExecuteArguments(args, defer) { var processedArgs = {}; processedArgs.type = args.shift(); // get the callback processedArgs.callback = this._parent._getCallback(args); // get block number to use for call if (processedArgs.type === 'call' && args[args.length - 1] !== true && (typeof args[args.length - 1] === 'string' || isFinite(args[args.length - 1]))) processedArgs.defaultBlock = args.pop(); // get the options processedArgs.options = (!!args[args.length - 1] && typeof args[args.length - 1]) === 'object' ? args.pop() : {}; // get the generateRequest argument for batch requests processedArgs.generateRequest = (args[args.length - 1] === true) ? args.pop() : false; processedArgs.options = this._parent._getOrSetDefaultOptions(processedArgs.options); processedArgs.options.data = this.encodeABI(); // add contract address if (!this._deployData && !utils.isAddress(this._parent.options.address)) throw errors.ContractNoAddressDefinedError(); if (!this._deployData) processedArgs.options.to = this._parent.options.address; // return error, if no "data" is specified if (!processedArgs.options.data) return utils._fireError(new Error('Couldn\'t find a matching contract method, or the number of parameters is wrong.'), defer.eventEmitter, defer.reject, processedArgs.callback); return processedArgs; }; /** * Executes a call, transact or estimateGas on a contract function * * @method _executeMethod * @param {String} type the type this execute function should execute * @param {Boolean} makeRequest if true, it simply returns the request parameters, rather than executing it */ Contract.prototype._executeMethod = function _executeMethod() { var _this = this, args = this._parent._processExecuteArguments.call(this, Array.prototype.slice.call(arguments), defer), defer = promiEvent((args.type !== 'send')), ethAccounts = _this.constructor._ethAccounts || _this._ethAccounts; // simple return request for batch requests if (args.generateRequest) { var payload = { params: [formatters.inputCallFormatter.call(this._parent, args.options)], callback: args.callback }; if (args.type === 'call') { payload.params.push(formatters.inputDefaultBlockNumberFormatter.call(this._parent, args.defaultBlock)); payload.method = 'eth_call'; payload.format = this._parent._decodeMethodReturn.bind(null, this._method.outputs); } else { payload.method = 'eth_sendTransaction'; } return payload; } switch (args.type) { case 'estimate': var estimateGas = (new Method({ name: 'estimateGas', call: 'eth_estimateGas', params: 1, inputFormatter: [formatters.inputCallFormatter], outputFormatter: utils.hexToNumber, requestManager: _this._parent._requestManager, accounts: ethAccounts, defaultAccount: _this._parent.defaultAccount, defaultBlock: _this._parent.defaultBlock })).createFunction(); return estimateGas(args.options, args.callback); case 'call': // TODO check errors: missing "from" should give error on deploy and send, call ? var call = (new Method({ name: 'call', call: 'eth_call', params: 2, inputFormatter: [formatters.inputCallFormatter, formatters.inputDefaultBlockNumberFormatter], // add output formatter for decoding outputFormatter: function (result) { return _this._parent._decodeMethodReturn(_this._method.outputs, result); }, requestManager: _this._parent._requestManager, accounts: ethAccounts, defaultAccount: _this._parent.defaultAccount, defaultBlock: _this._parent.defaultBlock, handleRevert: _this._parent.handleRevert, abiCoder: abi })).createFunction(); return call(args.options, args.defaultBlock, args.callback); case 'send': // return error, if no "from" is specified if (!utils.isAddress(args.options.from)) { return utils._fireError(errors.ContractNoFromAddressDefinedError(), defer.eventEmitter, defer.reject, args.callback); } if (typeof this._method.payable === 'boolean' && !this._method.payable && args.options.value && args.options.value > 0) { return utils._fireError(new Error('Can not send value to non-payable contract method or constructor'), defer.eventEmitter, defer.reject, args.callback); } // make sure receipt logs are decoded var extraFormatters = { receiptFormatter: function (receipt) { if (Array.isArray(receipt.logs)) { // decode logs var events = receipt.logs.map((log) => { return _this._parent._decodeEventABI.call({ name: 'ALLEVENTS', jsonInterface: _this._parent.options.jsonInterface }, log); }); // make log names keys receipt.events = {}; var count = 0; events.forEach(function (ev) { if (ev.event) { // if > 1 of the same event, don't overwrite any existing events if (receipt.events[ev.event]) { if (Array.isArray(receipt.events[ev.event])) { receipt.events[ev.event].push(ev); } else { receipt.events[ev.event] = [receipt.events[ev.event], ev]; } } else { receipt.events[ev.event] = ev; } } else { receipt.events[count] = ev; count++; } }); delete receipt.logs; } return receipt; }, contractDeployFormatter: function (receipt) { var newContract = _this._parent.clone(); newContract.options.address = receipt.contractAddress; return newContract; } }; var sendTransaction = (new Method({ name: 'sendTransaction', call: 'eth_sendTransaction', params: 1, inputFormatter: [formatters.inputTransactionFormatter], requestManager: _this._parent._requestManager, accounts: _this.constructor._ethAccounts || _this._ethAccounts, defaultAccount: _this._parent.defaultAccount, defaultBlock: _this._parent.defaultBlock, transactionBlockTimeout: _this._parent.transactionBlockTimeout, transactionConfirmationBlocks: _this._parent.transactionConfirmationBlocks, transactionPollingTimeout: _this._parent.transactionPollingTimeout, defaultCommon: _this._parent.defaultCommon, defaultChain: _this._parent.defaultChain, defaultHardfork: _this._parent.defaultHardfork, handleRevert: _this._parent.handleRevert, extraFormatters: extraFormatters, abiCoder: abi })).createFunction(); return sendTransaction(args.options, args.callback); default: throw new Error('Method "' + args.type + '" not implemented.'); } }; module.exports = Contract; /***/ }), /***/ 52399: /*!******************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-ens/lib/ENS.js ***! \******************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file ENS.js * * @author Samuel Furter * @date 2018 */ var config = __webpack_require__(/*! ./config */ 83366); var formatters = __webpack_require__(/*! web3-core-helpers */ 20176).formatters; var utils = __webpack_require__(/*! web3-utils */ 60819); var Registry = __webpack_require__(/*! ./contracts/Registry */ 68281); var ResolverMethodHandler = __webpack_require__(/*! ./lib/ResolverMethodHandler */ 59397); var contenthash = __webpack_require__(/*! ./lib/contentHash */ 26021); /** * Constructs a new instance of ENS * * @param {Eth} eth * * @constructor */ function ENS(eth) { this.eth = eth; var registryAddress = null; this._detectedAddress = null; this._lastSyncCheck = null; Object.defineProperty(this, 'registry', { get: function () { return new Registry(this); }, enumerable: true }); Object.defineProperty(this, 'resolverMethodHandler', { get: function () { return new ResolverMethodHandler(this.registry); }, enumerable: true }); Object.defineProperty(this, 'registryAddress', { get: function () { return registryAddress; }, set: function (value) { if (value === null) { registryAddress = value; return; } registryAddress = formatters.inputAddressFormatter(value); }, enumerable: true }); } /** * Returns true if the given interfaceId is supported and otherwise false. * * @method supportsInterface * * @param {string} name * @param {string} interfaceId * @param {function} callback * * @callback callback callback(error, result) * @returns {Promise} */ ENS.prototype.supportsInterface = function (name, interfaceId, callback) { return this.getResolver(name).then(function (resolver) { if (!utils.isHexStrict(interfaceId)) { interfaceId = utils.sha3(interfaceId).slice(0, 10); } return resolver.methods.supportsInterface(interfaceId).call(callback); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } throw error; }); }; /** * Returns the Resolver by the given address * * @deprecated Please use the "getResolver" method instead of "resolver" * * @method resolver * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {Promise} */ ENS.prototype.resolver = function (name, callback) { return this.registry.resolver(name, callback); }; /** * Returns the Resolver by the given address * * @method getResolver * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {Promise} */ ENS.prototype.getResolver = function (name, callback) { return this.registry.getResolver(name, callback); }; /** * Does set the resolver of the given name * * @method setResolver * * @param {string} name * @param {string} address * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setResolver = function (name, address, txConfig, callback) { return this.registry.setResolver(name, address, txConfig, callback); }; /** * Sets the owner, resolver, and TTL for an ENS record in a single operation. * * @method setRecord * * @param {string} name * @param {string} owner * @param {string} resolver * @param {string | number} ttl * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setRecord = function (name, owner, resolver, ttl, txConfig, callback) { return this.registry.setRecord(name, owner, resolver, ttl, txConfig, callback); }; /** * Sets the owner, resolver and TTL for a subdomain, creating it if necessary. * * @method setSubnodeRecord * * @param {string} name * @param {string} label * @param {string} owner * @param {string} resolver * @param {string | number} ttl * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setSubnodeRecord = function (name, label, owner, resolver, ttl, txConfig, callback) { return this.registry.setSubnodeRecord(name, label, owner, resolver, ttl, txConfig, callback); }; /** * Sets or clears an approval by the given operator. * * @method setApprovalForAll * * @param {string} operator * @param {boolean} approved * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setApprovalForAll = function (operator, approved, txConfig, callback) { return this.registry.setApprovalForAll(operator, approved, txConfig, callback); }; /** * Returns true if the operator is approved * * @method isApprovedForAll * * @param {string} owner * @param {string} operator * @param {function} callback * * @callback callback callback(error, result) * @returns {Promise} */ ENS.prototype.isApprovedForAll = function (owner, operator, callback) { return this.registry.isApprovedForAll(owner, operator, callback); }; /** * Returns true if the record exists * * @method recordExists * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {Promise} */ ENS.prototype.recordExists = function (name, callback) { return this.registry.recordExists(name, callback); }; /** * Returns the address of the owner of an ENS name. * * @method setSubnodeOwner * * @param {string} name * @param {string} label * @param {string} address * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setSubnodeOwner = function (name, label, address, txConfig, callback) { return this.registry.setSubnodeOwner(name, label, address, txConfig, callback); }; /** * Returns the address of the owner of an ENS name. * * @method getTTL * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.getTTL = function (name, callback) { return this.registry.getTTL(name, callback); }; /** * Returns the address of the owner of an ENS name. * * @method setTTL * * @param {string} name * @param {number} ttl * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setTTL = function (name, ttl, txConfig, callback) { return this.registry.setTTL(name, ttl, txConfig, callback); }; /** * Returns the owner by the given name and current configured or detected Registry * * @method getOwner * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.getOwner = function (name, callback) { return this.registry.getOwner(name, callback); }; /** * Returns the address of the owner of an ENS name. * * @method setOwner * * @param {string} name * @param {string} address * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setOwner = function (name, address, txConfig, callback) { return this.registry.setOwner(name, address, txConfig, callback); }; /** * Returns the address record associated with a name. * * @method getAddress * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.getAddress = function (name, callback) { return this.resolverMethodHandler.method(name, 'addr', []).call(callback); }; /** * Sets a new address * * @method setAddress * * @param {string} name * @param {string} address * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setAddress = function (name, address, txConfig, callback) { return this.resolverMethodHandler.method(name, 'setAddr', [address]).send(txConfig, callback); }; /** * Returns the public key * * @method getPubkey * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.getPubkey = function (name, callback) { return this.resolverMethodHandler.method(name, 'pubkey', [], null, callback).call(callback); }; /** * Set the new public key * * @method setPubkey * * @param {string} name * @param {string} x * @param {string} y * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setPubkey = function (name, x, y, txConfig, callback) { return this.resolverMethodHandler.method(name, 'setPubkey', [x, y]).send(txConfig, callback); }; /** * Returns the content * * @method getContent * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.getContent = function (name, callback) { return this.resolverMethodHandler.method(name, 'content', []).call(callback); }; /** * Set the content * * @method setContent * * @param {string} name * @param {string} hash * @param {function} callback * @param {TransactionConfig} txConfig * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setContent = function (name, hash, txConfig, callback) { return this.resolverMethodHandler.method(name, 'setContent', [hash]).send(txConfig, callback); }; /** * Returns the contenthash * * @method getContenthash * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.getContenthash = function (name, callback) { return this.resolverMethodHandler.method(name, 'contenthash', [], contenthash.decode).call(callback); }; /** * Set the contenthash * * @method setContent * * @param {string} name * @param {string} hash * @param {function} callback * @param {TransactionConfig} txConfig * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setContenthash = function (name, hash, txConfig, callback) { var encoded; try { encoded = contenthash.encode(hash); } catch (err) { var error = new Error('Could not encode ' + hash + '. See docs for supported hash protocols.'); if (typeof callback === 'function') { callback(error, null); return; } throw error; } return this.resolverMethodHandler.method(name, 'setContenthash', [encoded]).send(txConfig, callback); }; /** * Get the multihash * * @method getMultihash * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.getMultihash = function (name, callback) { return this.resolverMethodHandler.method(name, 'multihash', []).call(callback); }; /** * Set the multihash * * @method setMultihash * * @param {string} name * @param {string} hash * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ ENS.prototype.setMultihash = function (name, hash, txConfig, callback) { return this.resolverMethodHandler.method(name, 'multihash', [hash]).send(txConfig, callback); }; /** * Checks if the current used network is synced and looks for ENS support there. * Throws an error if not. * * @returns {Promise} */ ENS.prototype.checkNetwork = async function () { var now = new Date() / 1000; if (!this._lastSyncCheck || (now - this._lastSyncCheck) > 3600) { var block = await this.eth.getBlock('latest'); var headAge = now - block.timestamp; if (headAge > 3600) { throw new Error("Network not synced; last block was " + headAge + " seconds ago"); } this._lastSyncCheck = now; } if (this.registryAddress) { return this.registryAddress; } if (!this._detectedAddress) { var networkType = await this.eth.net.getNetworkType(); var addr = config.addresses[networkType]; if (typeof addr === 'undefined') { throw new Error("ENS is not supported on network " + networkType); } this._detectedAddress = addr; return this._detectedAddress; } return this._detectedAddress; }; module.exports = ENS; /***/ }), /***/ 83366: /*!*********************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-ens/lib/config.js ***! \*********************************************************************************/ /***/ ((module) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file config.js * * @author Samuel Furter * @date 2017 */ /** * Source: https://docs.ens.domains/ens-deployments * * @type {{addresses: {main: string, rinkeby: string, goerli: string, ropsten: string}}} */ var config = { addresses: { main: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", ropsten: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", rinkeby: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", goerli: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e" }, // These ids obtained at ensdomains docs: // https://docs.ens.domains/contract-developer-guide/writing-a-resolver interfaceIds: { addr: "0x3b3b57de", setAddr: "0x3b3b57de", pubkey: "0xc8690233", setPubkey: "0xc8690233", contenthash: "0xbc1c58d1", setContenthash: "0xbc1c58d1", content: "0xd8389dc5", setContent: "0xd8389dc5" } }; module.exports = config; /***/ }), /***/ 68281: /*!*********************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-ens/lib/contracts/Registry.js ***! \*********************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var console = __webpack_require__(/*! console-browserify */ 88883); /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file Registry.js * * @author Samuel Furter * @date 2018 */ var Contract = __webpack_require__(/*! web3-eth-contract */ 86156); var namehash = __webpack_require__(/*! eth-ens-namehash */ 65319); var PromiEvent = __webpack_require__(/*! web3-core-promievent */ 24817); var formatters = __webpack_require__(/*! web3-core-helpers */ 20176).formatters; var utils = __webpack_require__(/*! web3-utils */ 60819); var REGISTRY_ABI = __webpack_require__(/*! ../resources/ABI/Registry */ 76542); var RESOLVER_ABI = __webpack_require__(/*! ../resources/ABI/Resolver */ 75340); /** * A wrapper around the ENS registry contract. * * @method Registry * @param {Ens} ens * @constructor */ function Registry(ens) { var self = this; this.ens = ens; this.contract = ens.checkNetwork().then(function (address) { var contract = new Contract(REGISTRY_ABI, address); contract.setProvider(self.ens.eth.currentProvider); return contract; }); } /** * Returns the address of the owner of an ENS name. * * @deprecated Please use the "getOwner" method instead of "owner" * * @method owner * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {Promise} */ Registry.prototype.owner = function (name, callback) { console.warn('Deprecated: Please use the "getOwner" method instead of "owner".'); return this.getOwner(name, callback); }; /** * Returns the address of the owner of an ENS name. * * @method getOwner * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {Promise} */ Registry.prototype.getOwner = function (name, callback) { var promiEvent = new PromiEvent(true); this.contract.then(function (contract) { return contract.methods.owner(namehash.hash(name)).call(); }).then(function (receipt) { if (typeof callback === 'function') { // It's required to pass the receipt to the first argument to be backward compatible and to have the required consistency callback(receipt, receipt); return; } promiEvent.resolve(receipt); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Returns the address of the owner of an ENS name. * * @method setOwner * * @param {string} name * @param {string} address * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ Registry.prototype.setOwner = function (name, address, txConfig, callback) { var promiEvent = new PromiEvent(true); this.contract.then(function (contract) { return contract.methods.setOwner(namehash.hash(name), formatters.inputAddressFormatter(address)).send(txConfig); }).then(function (receipt) { if (typeof callback === 'function') { // It's required to pass the receipt to the first argument to be backward compatible and to have the required consistency callback(receipt, receipt); return; } promiEvent.resolve(receipt); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Returns the TTL of the given node by his name * * @method getTTL * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returnss {Promise} */ Registry.prototype.getTTL = function (name, callback) { var promiEvent = new PromiEvent(true); this.contract.then(function (contract) { return contract.methods.ttl(namehash.hash(name)).call(); }).then(function (receipt) { if (typeof callback === 'function') { // It's required to pass the receipt to the first argument to be backward compatible and to have the required consistency callback(receipt, receipt); return; } promiEvent.resolve(receipt); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Returns the address of the owner of an ENS name. * * @method setTTL * * @param {string} name * @param {number} ttl * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ Registry.prototype.setTTL = function (name, ttl, txConfig, callback) { var promiEvent = new PromiEvent(true); this.contract.then(function (contract) { return contract.methods.setTTL(namehash.hash(name), ttl).send(txConfig); }).then(function (receipt) { if (typeof callback === 'function') { // It's required to pass the receipt to the first argument to be backward compatible and to have the required consistency callback(receipt, receipt); return; } promiEvent.resolve(receipt); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Returns the address of the owner of an ENS name. * * @method setSubnodeOwner * * @param {string} name * @param {string} label * @param {string} address * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ Registry.prototype.setSubnodeOwner = function (name, label, address, txConfig, callback) { var promiEvent = new PromiEvent(true); if (!utils.isHexStrict(label)) { label = utils.sha3(label); } this.contract.then(function (contract) { return contract.methods.setSubnodeOwner(namehash.hash(name), label, formatters.inputAddressFormatter(address)).send(txConfig); }).then(function (receipt) { if (typeof callback === 'function') { // It's required to pass the receipt to the first argument to be backward compatible and to have the required consistency callback(receipt, receipt); return; } promiEvent.resolve(receipt); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Sets the owner, resolver, and TTL for an ENS record in a single operation. * * @method setRecord * * @param {string} name * @param {string} owner * @param {string} resolver * @param {string | number} ttl * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ Registry.prototype.setRecord = function (name, owner, resolver, ttl, txConfig, callback) { var promiEvent = new PromiEvent(true); this.contract.then(function (contract) { return contract.methods.setRecord(namehash.hash(name), formatters.inputAddressFormatter(owner), formatters.inputAddressFormatter(resolver), ttl).send(txConfig); }).then(function (receipt) { if (typeof callback === 'function') { // It's required to pass the receipt to the first argument to be backward compatible and to have the required consistency callback(receipt, receipt); return; } promiEvent.resolve(receipt); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Sets the owner, resolver and TTL for a subdomain, creating it if necessary. * * @method setSubnodeRecord * * @param {string} name * @param {string} label * @param {string} owner * @param {string} resolver * @param {string | number} ttl * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ Registry.prototype.setSubnodeRecord = function (name, label, owner, resolver, ttl, txConfig, callback) { var promiEvent = new PromiEvent(true); if (!utils.isHexStrict(label)) { label = utils.sha3(label); } this.contract.then(function (contract) { return contract.methods.setSubnodeRecord(namehash.hash(name), label, formatters.inputAddressFormatter(owner), formatters.inputAddressFormatter(resolver), ttl).send(txConfig); }).then(function (receipt) { if (typeof callback === 'function') { // It's required to pass the receipt to the first argument to be backward compatible and to have the required consistency callback(receipt, receipt); return; } promiEvent.resolve(receipt); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Sets or clears an approval by the given operator. * * @method setApprovalForAll * * @param {string} operator * @param {boolean} approved * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ Registry.prototype.setApprovalForAll = function (operator, approved, txConfig, callback) { var promiEvent = new PromiEvent(true); this.contract.then(function (contract) { return contract.methods.setApprovalForAll(formatters.inputAddressFormatter(operator), approved).send(txConfig); }).then(function (receipt) { if (typeof callback === 'function') { // It's required to pass the receipt to the first argument to be backward compatible and to have the required consistency callback(receipt, receipt); return; } promiEvent.resolve(receipt); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Returns true if the operator is approved * * @method isApprovedForAll * * @param {string} owner * @param {string} operator * @param {function} callback * * @callback callback callback(error, result) * @returns {Promise} */ Registry.prototype.isApprovedForAll = function (owner, operator, callback) { var promiEvent = new PromiEvent(true); this.contract.then(function (contract) { return contract.methods.isApprovedForAll(formatters.inputAddressFormatter(owner), formatters.inputAddressFormatter(operator)).call(); }).then(function (receipt) { if (typeof callback === 'function') { // It's required to pass the receipt to the first argument to be backward compatible and to have the required consistency callback(receipt, receipt); return; } promiEvent.resolve(receipt); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Returns true if the record exists * * @method recordExists * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {Promise} */ Registry.prototype.recordExists = function (name, callback) { var promiEvent = new PromiEvent(true); this.contract.then(function (contract) { return contract.methods.recordExists(namehash.hash(name)).call(); }).then(function (receipt) { if (typeof callback === 'function') { // It's required to pass the receipt to the first argument to be backward compatible and to have the required consistency callback(receipt, receipt); return; } promiEvent.resolve(receipt); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Returns the resolver contract associated with a name. * * @deprecated Please use the "getResolver" method instead of "resolver" * * @method resolver * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {Promise} */ Registry.prototype.resolver = function (name, callback) { console.warn('Deprecated: Please use the "getResolver" method instead of "resolver".'); return this.getResolver(name, callback); }; /** * Returns the resolver contract associated with a name. * * @method getResolver * * @param {string} name * @param {function} callback * * @callback callback callback(error, result) * @returns {Promise} */ Registry.prototype.getResolver = function (name, callback) { var self = this; return this.contract.then(function (contract) { return contract.methods.resolver(namehash.hash(name)).call(); }).then(function (address) { var contract = new Contract(RESOLVER_ABI, address); contract.setProvider(self.ens.eth.currentProvider); if (typeof callback === 'function') { // It's required to pass the contract to the first argument to be backward compatible and to have the required consistency callback(contract, contract); return; } return contract; }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } throw error; }); }; /** * Returns the address of the owner of an ENS name. * * @method setResolver * * @param {string} name * @param {string} address * @param {TransactionConfig} txConfig * @param {function} callback * * @callback callback callback(error, result) * @returns {PromiEvent} */ Registry.prototype.setResolver = function (name, address, txConfig, callback) { var promiEvent = new PromiEvent(true); this.contract.then(function (contract) { return contract.methods.setResolver(namehash.hash(name), formatters.inputAddressFormatter(address)).send(txConfig); }).then(function (receipt) { if (typeof callback === 'function') { // It's required to pass the receipt to the first argument to be backward compatible and to have the required consistency callback(receipt, receipt); return; } promiEvent.resolve(receipt); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; module.exports = Registry; /***/ }), /***/ 75608: /*!********************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-ens/lib/index.js ***! \********************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * * @author Samuel Furter * @date 2018 */ var ENS = __webpack_require__(/*! ./ENS */ 52399); module.exports = ENS; /***/ }), /***/ 59397: /*!****************************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-ens/lib/lib/ResolverMethodHandler.js ***! \****************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var console = __webpack_require__(/*! console-browserify */ 88883); /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file ResolverMethodHandler.js * * @author Samuel Furter * @date 2018 */ var PromiEvent = __webpack_require__(/*! web3-core-promievent */ 24817); var namehash = __webpack_require__(/*! eth-ens-namehash */ 65319); var errors = __webpack_require__(/*! web3-core-helpers */ 20176).errors; var interfaceIds = __webpack_require__(/*! ../config */ 83366).interfaceIds; /** * @param {Registry} registry * @constructor */ function ResolverMethodHandler(registry) { this.registry = registry; } /** * Executes an resolver method and returns an eventifiedPromise * * @param {string} ensName * @param {string} methodName * @param {array} methodArguments * @param {function} callback * @returns {Object} */ ResolverMethodHandler.prototype.method = function (ensName, methodName, methodArguments, outputFormatter, callback) { return { call: this.call.bind({ ensName: ensName, methodName: methodName, methodArguments: methodArguments, callback: callback, parent: this, outputFormatter: outputFormatter }), send: this.send.bind({ ensName: ensName, methodName: methodName, methodArguments: methodArguments, callback: callback, parent: this }) }; }; /** * Executes call * * @returns {eventifiedPromise} */ ResolverMethodHandler.prototype.call = function (callback) { var self = this; var promiEvent = new PromiEvent(); var preparedArguments = this.parent.prepareArguments(this.ensName, this.methodArguments); var outputFormatter = this.outputFormatter || null; this.parent.registry.getResolver(this.ensName).then(async function (resolver) { await self.parent.checkInterfaceSupport(resolver, self.methodName); self.parent.handleCall(promiEvent, resolver.methods[self.methodName], preparedArguments, outputFormatter, callback); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Executes send * * @param {Object} sendOptions * @param {function} callback * @returns {eventifiedPromise} */ ResolverMethodHandler.prototype.send = function (sendOptions, callback) { var self = this; var promiEvent = new PromiEvent(); var preparedArguments = this.parent.prepareArguments(this.ensName, this.methodArguments); this.parent.registry.getResolver(this.ensName).then(async function (resolver) { await self.parent.checkInterfaceSupport(resolver, self.methodName); self.parent.handleSend(promiEvent, resolver.methods[self.methodName], preparedArguments, sendOptions, callback); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent.eventEmitter; }; /** * Handles a call method * * @param {eventifiedPromise} promiEvent * @param {function} method * @param {array} preparedArguments * @param {function} callback * @returns {eventifiedPromise} */ ResolverMethodHandler.prototype.handleCall = function (promiEvent, method, preparedArguments, outputFormatter, callback) { method.apply(this, preparedArguments).call() .then(function (result) { if (outputFormatter) { result = outputFormatter(result); } if (typeof callback === 'function') { // It's required to pass the receipt to the second argument to be backwards compatible and to have the required consistency callback(result, result); return; } promiEvent.resolve(result); }).catch(function (error) { if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent; }; /** * Handles a send method * * @param {eventifiedPromise} promiEvent * @param {function} method * @param {array} preparedArguments * @param {Object} sendOptions * @param {function} callback * @returns {eventifiedPromise} */ ResolverMethodHandler.prototype.handleSend = function (promiEvent, method, preparedArguments, sendOptions, callback) { method.apply(this, preparedArguments).send(sendOptions) .on('sending', function () { promiEvent.eventEmitter.emit('sending'); }) .on('sent', function () { promiEvent.eventEmitter.emit('sent'); }) .on('transactionHash', function (hash) { promiEvent.eventEmitter.emit('transactionHash', hash); }) .on('confirmation', function (confirmationNumber, receipt) { promiEvent.eventEmitter.emit('confirmation', confirmationNumber, receipt); }) .on('receipt', function (receipt) { promiEvent.eventEmitter.emit('receipt', receipt); promiEvent.resolve(receipt); if (typeof callback === 'function') { // It's required to pass the receipt to the second argument to be backwards compatible and to have the required consistency callback(receipt, receipt); } }) .on('error', function (error) { promiEvent.eventEmitter.emit('error', error); if (typeof callback === 'function') { callback(error, null); return; } promiEvent.reject(error); }); return promiEvent; }; /** * Adds the ENS node to the arguments * * @param {string} name * @param {array} methodArguments * * @returns {array} */ ResolverMethodHandler.prototype.prepareArguments = function (name, methodArguments) { var node = namehash.hash(name); if (methodArguments.length > 0) { methodArguments.unshift(node); return methodArguments; } return [node]; }; /** * * * @param {Contract} resolver * @param {string} methodName * * @returns {Promise} */ ResolverMethodHandler.prototype.checkInterfaceSupport = async function (resolver, methodName) { // Skip validation for undocumented interface ids (ex: multihash) if (!interfaceIds[methodName]) return; var supported = false; try { supported = await resolver .methods .supportsInterface(interfaceIds[methodName]) .call(); } catch (err) { console.warn('Could not verify interface of resolver contract at "' + resolver.options.address + '". '); } if (!supported) { throw errors.ResolverMethodMissingError(resolver.options.address, methodName); } }; module.exports = ResolverMethodHandler; /***/ }), /***/ 26021: /*!******************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-ens/lib/lib/contentHash.js ***! \******************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* Adapted from ensdomains/ui https://github.com/ensdomains/ui/blob/3e62e440b53466eeec9dd1c63d73924eefbd88c1/src/utils/contents.js#L1-L85 BSD 2-Clause License Copyright (c) 2019, Ethereum Name Service All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var contentHash = __webpack_require__(/*! content-hash */ 85719); function decode(encoded) { var decoded = null; var protocolType = null; var error = null; if (encoded && encoded.error) { return { protocolType: null, decoded: encoded.error }; } if (encoded) { try { decoded = contentHash.decode(encoded); var codec = contentHash.getCodec(encoded); if (codec === 'ipfs-ns') { protocolType = 'ipfs'; } else if (codec === 'swarm-ns') { protocolType = 'bzz'; } else if (codec === 'onion') { protocolType = 'onion'; } else if (codec === 'onion3') { protocolType = 'onion3'; } else { decoded = encoded; } } catch (e) { error = e.message; } } return { protocolType: protocolType, decoded: decoded, error: error }; } function encode(text) { var content, contentType; var encoded = false; if (!!text) { var matched = text.match(/^(ipfs|bzz|onion|onion3):\/\/(.*)/) || text.match(/\/(ipfs)\/(.*)/); if (matched) { contentType = matched[1]; content = matched[2]; } try { if (contentType === 'ipfs') { if (content.length >= 4) { encoded = '0x' + contentHash.fromIpfs(content); } } else if (contentType === 'bzz') { if (content.length >= 4) { encoded = '0x' + contentHash.fromSwarm(content); } } else if (contentType === 'onion') { if (content.length === 16) { encoded = '0x' + contentHash.encode('onion', content); } } else if (contentType === 'onion3') { if (content.length === 56) { encoded = '0x' + contentHash.encode('onion3', content); } } else { throw new Error('Could not encode content hash: unsupported content type'); } } catch (err) { throw err; } } return encoded; } module.exports = { decode: decode, encode: encode }; /***/ }), /***/ 76542: /*!*************************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-ens/lib/resources/ABI/Registry.js ***! \*************************************************************************************************/ /***/ ((module) => { "use strict"; var REGISTRY = [ { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "resolver", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "owner", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "label", "type": "bytes32" }, { "name": "owner", "type": "address" } ], "name": "setSubnodeOwner", "outputs": [], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "ttl", "type": "uint64" } ], "name": "setTTL", "outputs": [], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "ttl", "outputs": [ { "name": "", "type": "uint64" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "resolver", "type": "address" } ], "name": "setResolver", "outputs": [], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "owner", "type": "address" } ], "name": "setOwner", "outputs": [], "payable": false, "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "node", "type": "bytes32" }, { "indexed": false, "name": "owner", "type": "address" } ], "name": "Transfer", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "node", "type": "bytes32" }, { "indexed": true, "name": "label", "type": "bytes32" }, { "indexed": false, "name": "owner", "type": "address" } ], "name": "NewOwner", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "node", "type": "bytes32" }, { "indexed": false, "name": "resolver", "type": "address" } ], "name": "NewResolver", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "node", "type": "bytes32" }, { "indexed": false, "name": "ttl", "type": "uint64" } ], "name": "NewTTL", "type": "event" }, { "constant": false, "inputs": [ { "internalType": "bytes32", "name": "node", "type": "bytes32" }, { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "resolver", "type": "address" }, { "internalType": "uint64", "name": "ttl", "type": "uint64" } ], "name": "setRecord", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "internalType": "address", "name": "operator", "type": "address" }, { "internalType": "bool", "name": "approved", "type": "bool" } ], "name": "setApprovalForAll", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "operator", "type": "address" }, { "indexed": false, "internalType": "bool", "name": "approved", "type": "bool" } ], "name": "ApprovalForAll", "type": "event" }, { "constant": true, "inputs": [ { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "operator", "type": "address" } ], "name": "isApprovedForAll", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "internalType": "bytes32", "name": "node", "type": "bytes32" } ], "name": "recordExists", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "internalType": "bytes32", "name": "node", "type": "bytes32" }, { "internalType": "bytes32", "name": "label", "type": "bytes32" }, { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "resolver", "type": "address" }, { "internalType": "uint64", "name": "ttl", "type": "uint64" } ], "name": "setSubnodeRecord", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" } ]; module.exports = REGISTRY; /***/ }), /***/ 75340: /*!*************************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-ens/lib/resources/ABI/Resolver.js ***! \*************************************************************************************************/ /***/ ((module) => { "use strict"; var RESOLVER = [ { "constant": true, "inputs": [ { "name": "interfaceID", "type": "bytes4" } ], "name": "supportsInterface", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "contentTypes", "type": "uint256" } ], "name": "ABI", "outputs": [ { "name": "contentType", "type": "uint256" }, { "name": "data", "type": "bytes" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "hash", "type": "bytes" } ], "name": "setMultihash", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "multihash", "outputs": [ { "name": "", "type": "bytes" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "x", "type": "bytes32" }, { "name": "y", "type": "bytes32" } ], "name": "setPubkey", "outputs": [], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "content", "outputs": [ { "name": "ret", "type": "bytes32" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "addr", "outputs": [ { "name": "ret", "type": "address" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "contentType", "type": "uint256" }, { "name": "data", "type": "bytes" } ], "name": "setABI", "outputs": [], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "name", "outputs": [ { "name": "ret", "type": "string" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "name", "type": "string" } ], "name": "setName", "outputs": [], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "hash", "type": "bytes32" } ], "name": "setContent", "outputs": [], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "pubkey", "outputs": [ { "name": "x", "type": "bytes32" }, { "name": "y", "type": "bytes32" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "addr", "type": "address" } ], "name": "setAddr", "outputs": [], "payable": false, "type": "function" }, { "inputs": [ { "name": "ensAddr", "type": "address" } ], "payable": false, "type": "constructor" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "node", "type": "bytes32" }, { "indexed": false, "name": "a", "type": "address" } ], "name": "AddrChanged", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "node", "type": "bytes32" }, { "indexed": false, "name": "hash", "type": "bytes32" } ], "name": "ContentChanged", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "node", "type": "bytes32" }, { "indexed": false, "name": "name", "type": "string" } ], "name": "NameChanged", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "node", "type": "bytes32" }, { "indexed": true, "name": "contentType", "type": "uint256" } ], "name": "ABIChanged", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "node", "type": "bytes32" }, { "indexed": false, "name": "x", "type": "bytes32" }, { "indexed": false, "name": "y", "type": "bytes32" } ], "name": "PubkeyChanged", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "node", "type": "bytes32" }, { "indexed": false, "name": "hash", "type": "bytes" } ], "name": "ContenthashChanged", "type": "event" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "contenthash", "outputs": [ { "name": "", "type": "bytes" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "hash", "type": "bytes" } ], "name": "setContenthash", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" } ]; module.exports = RESOLVER; /***/ }), /***/ 19890: /*!*********************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-iban/lib/index.js ***! \*********************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file iban.js * * Details: https://github.com/ethereum/wiki/wiki/ICAP:-Inter-exchange-Client-Address-Protocol * * @author Marek Kotewicz * @date 2015 */ const utils = __webpack_require__(/*! web3-utils */ 60819); const BigNumber = __webpack_require__(/*! bn.js */ 62630); const leftPad = function (string, bytes) { let result = string; while (result.length < bytes * 2) { result = '0' + result; } return result; }; /** * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. * * @method iso13616Prepare * @param {String} iban the IBAN * @returns {String} the prepared IBAN */ const iso13616Prepare = function (iban) { const A = 'A'.charCodeAt(0); const Z = 'Z'.charCodeAt(0); iban = iban.toUpperCase(); iban = iban.substr(4) + iban.substr(0, 4); return iban.split('').map(function (n) { const code = n.charCodeAt(0); if (code >= A && code <= Z) { // A = 10, B = 11, ... Z = 35 return code - A + 10; } else { return n; } }).join(''); }; /** * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. * * @method mod9710 * @param {String} iban * @returns {Number} */ const mod9710 = function (iban) { let remainder = iban; let block; while (remainder.length > 2) { block = remainder.slice(0, 9); remainder = parseInt(block, 10) % 97 + remainder.slice(block.length); } return parseInt(remainder, 10) % 97; }; /** * This prototype should be used to create iban object from iban correct string * * @param {String} iban */ class Iban { constructor(iban) { this._iban = iban; } /** * This method should be used to create an ethereum address from a direct iban address * * @method toAddress * @param {String} iban address * @return {String} the ethereum address */ static toAddress(ib) { ib = new Iban(ib); if (!ib.isDirect()) { throw new Error('IBAN is indirect and can\'t be converted'); } return ib.toAddress(); } /** * This method should be used to create iban address from an ethereum address * * @method toIban * @param {String} address * @return {String} the IBAN address */ static toIban(address) { return Iban.fromAddress(address).toString(); } /** * This method should be used to create iban object from an ethereum address * * @method fromAddress * @param {String} address * @return {Iban} the IBAN object */ static fromAddress(address) { if (!utils.isAddress(address)) { throw new Error('Provided address is not a valid address: ' + address); } address = address.replace('0x', '').replace('0X', ''); const asBn = new BigNumber(address, 16); const base36 = asBn.toString(36); const padded = leftPad(base36, 15); return Iban.fromBban(padded.toUpperCase()); } /** * Convert the passed BBAN to an IBAN for this country specification. * Please note that "generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account". * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits * * @method fromBban * @param {String} bban the BBAN to convert to IBAN * @returns {Iban} the IBAN object */ static fromBban(bban) { const countryCode = 'XE'; const remainder = mod9710(iso13616Prepare(countryCode + '00' + bban)); const checkDigit = ('0' + (98 - remainder)).slice(-2); return new Iban(countryCode + checkDigit + bban); } /** * Should be used to create IBAN object for given institution and identifier * * @method createIndirect * @param {Object} options, required options are "institution" and "identifier" * @return {Iban} the IBAN object */ static createIndirect(options) { return Iban.fromBban('ETH' + options.institution + options.identifier); } /** * This method should be used to check if given string is valid iban object * * @method isValid * @param {String} iban string * @return {Boolean} true if it is valid IBAN */ static isValid(iban) { const i = new Iban(iban); return i.isValid(); } ; /** * Should be called to check if iban is correct * * @method isValid * @returns {Boolean} true if it is, otherwise false */ isValid() { return /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban) && mod9710(iso13616Prepare(this._iban)) === 1; } ; /** * Should be called to check if iban number is direct * * @method isDirect * @returns {Boolean} true if it is, otherwise false */ isDirect() { return this._iban.length === 34 || this._iban.length === 35; } ; /** * Should be called to check if iban number if indirect * * @method isIndirect * @returns {Boolean} true if it is, otherwise false */ isIndirect() { return this._iban.length === 20; } ; /** * Should be called to get iban checksum * Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003) * * @method checksum * @returns {String} checksum */ checksum() { return this._iban.substr(2, 2); } ; /** * Should be called to get institution identifier * eg. XREG * * @method institution * @returns {String} institution identifier */ institution() { return this.isIndirect() ? this._iban.substr(7, 4) : ''; } ; /** * Should be called to get client identifier within institution * eg. GAVOFYORK * * @method client * @returns {String} client identifier */ client() { return this.isIndirect() ? this._iban.substr(11) : ''; } ; /** * Should be called to get client direct address * * @method toAddress * @returns {String} ethereum address */ toAddress() { if (this.isDirect()) { const base36 = this._iban.substr(4); const asBn = new BigNumber(base36, 36); return utils.toChecksumAddress(asBn.toString(16, 20)); } return ''; } ; toString() { return this._iban; } ; } module.exports = Iban; /***/ }), /***/ 82330: /*!*************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth-personal/lib/index.js ***! \*************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Fabian Vogelsteller * @date 2017 */ var core = __webpack_require__(/*! web3-core */ 79517); var Method = __webpack_require__(/*! web3-core-method */ 50202); var utils = __webpack_require__(/*! web3-utils */ 60819); var Net = __webpack_require__(/*! web3-net */ 26293); var formatters = __webpack_require__(/*! web3-core-helpers */ 20176).formatters; var Personal = function Personal() { var _this = this; // sets _requestmanager core.packageInit(this, arguments); this.net = new Net(this); var defaultAccount = null; var defaultBlock = 'latest'; Object.defineProperty(this, 'defaultAccount', { get: function () { return defaultAccount; }, set: function (val) { if (val) { defaultAccount = utils.toChecksumAddress(formatters.inputAddressFormatter(val)); } // update defaultBlock methods.forEach(function (method) { method.defaultAccount = defaultAccount; }); return val; }, enumerable: true }); Object.defineProperty(this, 'defaultBlock', { get: function () { return defaultBlock; }, set: function (val) { defaultBlock = val; // update defaultBlock methods.forEach(function (method) { method.defaultBlock = defaultBlock; }); return val; }, enumerable: true }); var methods = [ new Method({ name: 'getAccounts', call: 'personal_listAccounts', params: 0, outputFormatter: utils.toChecksumAddress }), new Method({ name: 'newAccount', call: 'personal_newAccount', params: 1, inputFormatter: [null], outputFormatter: utils.toChecksumAddress }), new Method({ name: 'unlockAccount', call: 'personal_unlockAccount', params: 3, inputFormatter: [formatters.inputAddressFormatter, null, null] }), new Method({ name: 'lockAccount', call: 'personal_lockAccount', params: 1, inputFormatter: [formatters.inputAddressFormatter] }), new Method({ name: 'importRawKey', call: 'personal_importRawKey', params: 2 }), new Method({ name: 'sendTransaction', call: 'personal_sendTransaction', params: 2, inputFormatter: [formatters.inputTransactionFormatter, null] }), new Method({ name: 'signTransaction', call: 'personal_signTransaction', params: 2, inputFormatter: [formatters.inputTransactionFormatter, null] }), new Method({ name: 'sign', call: 'personal_sign', params: 3, inputFormatter: [formatters.inputSignFormatter, formatters.inputAddressFormatter, null] }), new Method({ name: 'ecRecover', call: 'personal_ecRecover', params: 2, inputFormatter: [formatters.inputSignFormatter, null] }) ]; methods.forEach(function (method) { method.attachToObject(_this); method.setRequestManager(_this._requestManager); method.defaultBlock = _this.defaultBlock; method.defaultAccount = _this.defaultAccount; }); }; core.addProviders(Personal); module.exports = Personal; /***/ }), /***/ 60664: /*!*************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth/lib/getNetworkType.js ***! \*************************************************************************************/ /***/ ((module) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file getNetworkType.js * @author Fabian Vogelsteller * @date 2017 */ var getNetworkType = function (callback) { var _this = this, id; return this.net.getId() .then(function (givenId) { id = givenId; return _this.getBlock(0); }) .then(function (genesis) { var returnValue = 'private'; if (genesis.hash === '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3' && id === 1) { returnValue = 'main'; } if (genesis.hash === '0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303' && id === 2) { returnValue = 'morden'; } if (genesis.hash === '0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d' && id === 3) { returnValue = 'ropsten'; } if (genesis.hash === '0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177' && id === 4) { returnValue = 'rinkeby'; } if (genesis.hash === '0xbf7e331f7f7c1dd2e05159666b3bf8bc7a8a3a9eb1d518969eab529dd9b88c1a' && id === 5) { returnValue = 'goerli'; } if (genesis.hash === '0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9' && id === 42) { returnValue = 'kovan'; } if (typeof callback === 'function') { callback(null, returnValue); } return returnValue; }) .catch(function (err) { if (typeof callback === 'function') { callback(err); } else { throw err; } }); }; module.exports = getNetworkType; /***/ }), /***/ 38805: /*!****************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-eth/lib/index.js ***! \****************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Fabian Vogelsteller * @date 2017 */ var core = __webpack_require__(/*! web3-core */ 79517); var helpers = __webpack_require__(/*! web3-core-helpers */ 20176); var Subscriptions = __webpack_require__(/*! web3-core-subscriptions */ 54923).subscriptions; var Method = __webpack_require__(/*! web3-core-method */ 50202); var utils = __webpack_require__(/*! web3-utils */ 60819); var Net = __webpack_require__(/*! web3-net */ 26293); var ENS = __webpack_require__(/*! web3-eth-ens */ 75608); var Personal = __webpack_require__(/*! web3-eth-personal */ 82330); var BaseContract = __webpack_require__(/*! web3-eth-contract */ 86156); var Iban = __webpack_require__(/*! web3-eth-iban */ 19890); var Accounts = __webpack_require__(/*! web3-eth-accounts */ 2769); var abi = __webpack_require__(/*! web3-eth-abi */ 74241); var getNetworkType = __webpack_require__(/*! ./getNetworkType.js */ 60664); var formatter = helpers.formatters; var blockCall = function (args) { return (typeof args[0] === 'string' && args[0].indexOf('0x') === 0) ? "eth_getBlockByHash" : "eth_getBlockByNumber"; }; var transactionFromBlockCall = function (args) { return (typeof args[0] === 'string' && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex'; }; var uncleCall = function (args) { return (typeof args[0] === 'string' && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex'; }; var getBlockTransactionCountCall = function (args) { return (typeof args[0] === 'string' && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber'; }; var uncleCountCall = function (args) { return (typeof args[0] === 'string' && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber'; }; var Eth = function Eth() { var _this = this; // sets _requestmanager core.packageInit(this, arguments); // overwrite package setRequestManager var setRequestManager = this.setRequestManager; this.setRequestManager = function (manager) { setRequestManager(manager); _this.net.setRequestManager(manager); _this.personal.setRequestManager(manager); _this.accounts.setRequestManager(manager); _this.Contract._requestManager = _this._requestManager; _this.Contract.currentProvider = _this._provider; return true; }; // overwrite setProvider var setProvider = this.setProvider; this.setProvider = function () { setProvider.apply(_this, arguments); _this.setRequestManager(_this._requestManager); // Set detectedAddress/lastSyncCheck back to null because the provider could be connected to a different chain now _this.ens._detectedAddress = null; _this.ens._lastSyncCheck = null; }; var handleRevert = false; var defaultAccount = null; var defaultBlock = 'latest'; var transactionBlockTimeout = 50; var transactionConfirmationBlocks = 24; var transactionPollingTimeout = 750; var maxListenersWarningThreshold = 100; var defaultChain, defaultHardfork, defaultCommon; Object.defineProperty(this, 'handleRevert', { get: function () { return handleRevert; }, set: function (val) { handleRevert = val; // also set on the Contract object _this.Contract.handleRevert = handleRevert; // update handleRevert methods.forEach(function (method) { method.handleRevert = handleRevert; }); }, enumerable: true }); Object.defineProperty(this, 'defaultCommon', { get: function () { return defaultCommon; }, set: function (val) { defaultCommon = val; // also set on the Contract object _this.Contract.defaultCommon = defaultCommon; // update defaultBlock methods.forEach(function (method) { method.defaultCommon = defaultCommon; }); }, enumerable: true }); Object.defineProperty(this, 'defaultHardfork', { get: function () { return defaultHardfork; }, set: function (val) { defaultHardfork = val; // also set on the Contract object _this.Contract.defaultHardfork = defaultHardfork; // update defaultBlock methods.forEach(function (method) { method.defaultHardfork = defaultHardfork; }); }, enumerable: true }); Object.defineProperty(this, 'defaultChain', { get: function () { return defaultChain; }, set: function (val) { defaultChain = val; // also set on the Contract object _this.Contract.defaultChain = defaultChain; // update defaultBlock methods.forEach(function (method) { method.defaultChain = defaultChain; }); }, enumerable: true }); Object.defineProperty(this, 'transactionPollingTimeout', { get: function () { return transactionPollingTimeout; }, set: function (val) { transactionPollingTimeout = val; // also set on the Contract object _this.Contract.transactionPollingTimeout = transactionPollingTimeout; // update defaultBlock methods.forEach(function (method) { method.transactionPollingTimeout = transactionPollingTimeout; }); }, enumerable: true }); Object.defineProperty(this, 'transactionConfirmationBlocks', { get: function () { return transactionConfirmationBlocks; }, set: function (val) { transactionConfirmationBlocks = val; // also set on the Contract object _this.Contract.transactionConfirmationBlocks = transactionConfirmationBlocks; // update defaultBlock methods.forEach(function (method) { method.transactionConfirmationBlocks = transactionConfirmationBlocks; }); }, enumerable: true }); Object.defineProperty(this, 'transactionBlockTimeout', { get: function () { return transactionBlockTimeout; }, set: function (val) { transactionBlockTimeout = val; // also set on the Contract object _this.Contract.transactionBlockTimeout = transactionBlockTimeout; // update defaultBlock methods.forEach(function (method) { method.transactionBlockTimeout = transactionBlockTimeout; }); }, enumerable: true }); Object.defineProperty(this, 'defaultAccount', { get: function () { return defaultAccount; }, set: function (val) { if (val) { defaultAccount = utils.toChecksumAddress(formatter.inputAddressFormatter(val)); } // also set on the Contract object _this.Contract.defaultAccount = defaultAccount; _this.personal.defaultAccount = defaultAccount; // update defaultBlock methods.forEach(function (method) { method.defaultAccount = defaultAccount; }); return val; }, enumerable: true }); Object.defineProperty(this, 'defaultBlock', { get: function () { return defaultBlock; }, set: function (val) { defaultBlock = val; // also set on the Contract object _this.Contract.defaultBlock = defaultBlock; _this.personal.defaultBlock = defaultBlock; // update defaultBlock methods.forEach(function (method) { method.defaultBlock = defaultBlock; }); return val; }, enumerable: true }); Object.defineProperty(this, 'maxListenersWarningThreshold', { get: function () { return maxListenersWarningThreshold; }, set: function (val) { if (_this.currentProvider && _this.currentProvider.setMaxListeners) { maxListenersWarningThreshold = val; _this.currentProvider.setMaxListeners(val); } }, enumerable: true }); this.clearSubscriptions = _this._requestManager.clearSubscriptions.bind(_this._requestManager); this.removeSubscriptionById = _this._requestManager.removeSubscription.bind(_this._requestManager); // add net this.net = new Net(this); // add chain detection this.net.getNetworkType = getNetworkType.bind(this); // add accounts this.accounts = new Accounts(this); // add personal this.personal = new Personal(this); this.personal.defaultAccount = this.defaultAccount; // set warnings threshold this.maxListenersWarningThreshold = maxListenersWarningThreshold; // create a proxy Contract type for this instance, as a Contract's provider // is stored as a class member rather than an instance variable. If we do // not create this proxy type, changing the provider in one instance of // web3-eth would subsequently change the provider for _all_ contract // instances! var self = this; var Contract = function Contract() { BaseContract.apply(this, arguments); // when Eth.setProvider is called, call packageInit // on all contract instances instantiated via this Eth // instances. This will update the currentProvider for // the contract instances var _this = this; var setProvider = self.setProvider; self.setProvider = function () { setProvider.apply(self, arguments); core.packageInit(_this, [self]); }; }; Contract.setProvider = function () { BaseContract.setProvider.apply(this, arguments); }; // make our proxy Contract inherit from web3-eth-contract so that it has all // the right functionality and so that instanceof and friends work properly Contract.prototype = Object.create(BaseContract.prototype); Contract.prototype.constructor = Contract; // add contract this.Contract = Contract; this.Contract.defaultAccount = this.defaultAccount; this.Contract.defaultBlock = this.defaultBlock; this.Contract.transactionBlockTimeout = this.transactionBlockTimeout; this.Contract.transactionConfirmationBlocks = this.transactionConfirmationBlocks; this.Contract.transactionPollingTimeout = this.transactionPollingTimeout; this.Contract.handleRevert = this.handleRevert; this.Contract._requestManager = this._requestManager; this.Contract._ethAccounts = this.accounts; this.Contract.currentProvider = this._requestManager.provider; // add IBAN this.Iban = Iban; // add ABI this.abi = abi; // add ENS this.ens = new ENS(this); var methods = [ new Method({ name: 'getNodeInfo', call: 'web3_clientVersion' }), new Method({ name: 'getProtocolVersion', call: 'eth_protocolVersion', params: 0 }), new Method({ name: 'getCoinbase', call: 'eth_coinbase', params: 0 }), new Method({ name: 'isMining', call: 'eth_mining', params: 0 }), new Method({ name: 'getHashrate', call: 'eth_hashrate', params: 0, outputFormatter: utils.hexToNumber }), new Method({ name: 'isSyncing', call: 'eth_syncing', params: 0, outputFormatter: formatter.outputSyncingFormatter }), new Method({ name: 'getGasPrice', call: 'eth_gasPrice', params: 0, outputFormatter: formatter.outputBigNumberFormatter }), new Method({ name: 'getFeeHistory', call: 'eth_feeHistory', params: 3, inputFormatter: [utils.toNumber, formatter.inputBlockNumberFormatter, null] }), new Method({ name: 'getAccounts', call: 'eth_accounts', params: 0, outputFormatter: utils.toChecksumAddress }), new Method({ name: 'getBlockNumber', call: 'eth_blockNumber', params: 0, outputFormatter: utils.hexToNumber }), new Method({ name: 'getBalance', call: 'eth_getBalance', params: 2, inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter], outputFormatter: formatter.outputBigNumberFormatter }), new Method({ name: 'getStorageAt', call: 'eth_getStorageAt', params: 3, inputFormatter: [formatter.inputAddressFormatter, utils.numberToHex, formatter.inputDefaultBlockNumberFormatter] }), new Method({ name: 'getCode', call: 'eth_getCode', params: 2, inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter] }), new Method({ name: 'getBlock', call: blockCall, params: 2, inputFormatter: [formatter.inputBlockNumberFormatter, function (val) { return !!val; }], outputFormatter: formatter.outputBlockFormatter }), new Method({ name: 'getUncle', call: uncleCall, params: 2, inputFormatter: [formatter.inputBlockNumberFormatter, utils.numberToHex], outputFormatter: formatter.outputBlockFormatter, }), new Method({ name: 'getBlockTransactionCount', call: getBlockTransactionCountCall, params: 1, inputFormatter: [formatter.inputBlockNumberFormatter], outputFormatter: utils.hexToNumber }), new Method({ name: 'getBlockUncleCount', call: uncleCountCall, params: 1, inputFormatter: [formatter.inputBlockNumberFormatter], outputFormatter: utils.hexToNumber }), new Method({ name: 'getTransaction', call: 'eth_getTransactionByHash', params: 1, inputFormatter: [null], outputFormatter: formatter.outputTransactionFormatter }), new Method({ name: 'getTransactionFromBlock', call: transactionFromBlockCall, params: 2, inputFormatter: [formatter.inputBlockNumberFormatter, utils.numberToHex], outputFormatter: formatter.outputTransactionFormatter }), new Method({ name: 'getTransactionReceipt', call: 'eth_getTransactionReceipt', params: 1, inputFormatter: [null], outputFormatter: formatter.outputTransactionReceiptFormatter }), new Method({ name: 'getTransactionCount', call: 'eth_getTransactionCount', params: 2, inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter], outputFormatter: utils.hexToNumber }), new Method({ name: 'sendSignedTransaction', call: 'eth_sendRawTransaction', params: 1, inputFormatter: [null], abiCoder: abi }), new Method({ name: 'signTransaction', call: 'eth_signTransaction', params: 1, inputFormatter: [formatter.inputTransactionFormatter] }), new Method({ name: 'sendTransaction', call: 'eth_sendTransaction', params: 1, inputFormatter: [formatter.inputTransactionFormatter], abiCoder: abi }), new Method({ name: 'sign', call: 'eth_sign', params: 2, inputFormatter: [formatter.inputSignFormatter, formatter.inputAddressFormatter], transformPayload: function (payload) { payload.params.reverse(); return payload; } }), new Method({ name: 'call', call: 'eth_call', params: 2, inputFormatter: [formatter.inputCallFormatter, formatter.inputDefaultBlockNumberFormatter], abiCoder: abi }), new Method({ name: 'estimateGas', call: 'eth_estimateGas', params: 1, inputFormatter: [formatter.inputCallFormatter], outputFormatter: utils.hexToNumber }), new Method({ name: 'submitWork', call: 'eth_submitWork', params: 3 }), new Method({ name: 'getWork', call: 'eth_getWork', params: 0 }), new Method({ name: 'getPastLogs', call: 'eth_getLogs', params: 1, inputFormatter: [formatter.inputLogFormatter], outputFormatter: formatter.outputLogFormatter }), new Method({ name: 'getChainId', call: 'eth_chainId', params: 0, outputFormatter: utils.hexToNumber }), new Method({ name: 'requestAccounts', call: 'eth_requestAccounts', params: 0, outputFormatter: utils.toChecksumAddress }), new Method({ name: 'getProof', call: 'eth_getProof', params: 3, inputFormatter: [formatter.inputAddressFormatter, formatter.inputStorageKeysFormatter, formatter.inputDefaultBlockNumberFormatter], outputFormatter: formatter.outputProofFormatter }), new Method({ name: 'getPendingTransactions', call: 'eth_pendingTransactions', params: 0, outputFormatter: formatter.outputTransactionFormatter }), // subscriptions new Subscriptions({ name: 'subscribe', type: 'eth', subscriptions: { 'newBlockHeaders': { // TODO rename on RPC side? subscriptionName: 'newHeads', params: 0, outputFormatter: formatter.outputBlockFormatter }, 'pendingTransactions': { subscriptionName: 'newPendingTransactions', params: 0 }, 'logs': { params: 1, inputFormatter: [formatter.inputLogFormatter], outputFormatter: formatter.outputLogFormatter, // DUBLICATE, also in web3-eth-contract subscriptionHandler: function (output) { if (output.removed) { this.emit('changed', output); } else { this.emit('data', output); } if (typeof this.callback === 'function') { this.callback(null, output, this); } } }, 'syncing': { params: 0, outputFormatter: formatter.outputSyncingFormatter, subscriptionHandler: function (output) { var _this = this; // fire TRUE at start if (this._isSyncing !== true) { this._isSyncing = true; this.emit('changed', _this._isSyncing); if (typeof this.callback === 'function') { this.callback(null, _this._isSyncing, this); } setTimeout(function () { _this.emit('data', output); if (typeof _this.callback === 'function') { _this.callback(null, output, _this); } }, 0); // fire sync status } else { this.emit('data', output); if (typeof _this.callback === 'function') { this.callback(null, output, this); } // wait for some time before fireing the FALSE clearTimeout(this._isSyncingTimeout); this._isSyncingTimeout = setTimeout(function () { if (output.currentBlock > output.highestBlock - 200) { _this._isSyncing = false; _this.emit('changed', _this._isSyncing); if (typeof _this.callback === 'function') { _this.callback(null, _this._isSyncing, _this); } } }, 500); } } } } }) ]; methods.forEach(function (method) { method.attachToObject(_this); method.setRequestManager(_this._requestManager, _this.accounts); // second param is the eth.accounts module (necessary for signing transactions locally) method.defaultBlock = _this.defaultBlock; method.defaultAccount = _this.defaultAccount; method.transactionBlockTimeout = _this.transactionBlockTimeout; method.transactionConfirmationBlocks = _this.transactionConfirmationBlocks; method.transactionPollingTimeout = _this.transactionPollingTimeout; method.handleRevert = _this.handleRevert; }); }; // Adds the static givenProvider and providers property to the Eth module core.addProviders(Eth); module.exports = Eth; /***/ }), /***/ 26293: /*!****************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-net/lib/index.js ***! \****************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Fabian Vogelsteller * @date 2017 */ var core = __webpack_require__(/*! web3-core */ 79517); var Method = __webpack_require__(/*! web3-core-method */ 50202); var utils = __webpack_require__(/*! web3-utils */ 60819); var Net = function () { var _this = this; // sets _requestmanager core.packageInit(this, arguments); [ new Method({ name: 'getId', call: 'net_version', params: 0, outputFormatter: parseInt }), new Method({ name: 'isListening', call: 'net_listening', params: 0 }), new Method({ name: 'getPeerCount', call: 'net_peerCount', params: 0, outputFormatter: utils.hexToNumber }) ].forEach(function (method) { method.attachToObject(_this); method.setRequestManager(_this._requestManager); }); }; core.addProviders(Net); module.exports = Net; /***/ }), /***/ 95982: /*!***************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-providers-http/lib/index.js ***! \***************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** @file httpprovider.js * @authors: * Marek Kotewicz * Marian Oancea * Fabian Vogelsteller * @date 2015 */ var errors = __webpack_require__(/*! web3-core-helpers */ 20176).errors; var XHR2 = __webpack_require__(/*! xhr2-cookies */ 62842).XMLHttpRequest; // jshint ignore: line var http = __webpack_require__(/*! http */ 12703); var https = __webpack_require__(/*! https */ 54557); /** * HttpProvider should be used to send rpc calls over http */ var HttpProvider = function HttpProvider(host, options) { options = options || {}; this.withCredentials = options.withCredentials || false; this.timeout = options.timeout || 0; this.headers = options.headers; this.agent = options.agent; this.connected = false; // keepAlive is true unless explicitly set to false const keepAlive = options.keepAlive !== false; this.host = host || 'http://localhost:8545'; if (!this.agent) { if (this.host.substring(0, 5) === "https") { this.httpsAgent = new https.Agent({ keepAlive }); } else { this.httpAgent = new http.Agent({ keepAlive }); } } }; HttpProvider.prototype._prepareRequest = function () { var request; // the current runtime is a browser if (typeof XMLHttpRequest !== 'undefined') { request = new XMLHttpRequest(); } else { request = new XHR2(); var agents = { httpsAgent: this.httpsAgent, httpAgent: this.httpAgent, baseUrl: this.baseUrl }; if (this.agent) { agents.httpsAgent = this.agent.https; agents.httpAgent = this.agent.http; agents.baseUrl = this.agent.baseUrl; } request.nodejsSet(agents); } request.open('POST', this.host, true); request.setRequestHeader('Content-Type', 'application/json'); request.timeout = this.timeout; request.withCredentials = this.withCredentials; if (this.headers) { this.headers.forEach(function (header) { request.setRequestHeader(header.name, header.value); }); } return request; }; /** * Should be used to make async request * * @method send * @param {Object} payload * @param {Function} callback triggered on end with (err, result) */ HttpProvider.prototype.send = function (payload, callback) { var _this = this; var request = this._prepareRequest(); request.onreadystatechange = function () { if (request.readyState === 4 && request.timeout !== 1) { var result = request.responseText; var error = null; try { result = JSON.parse(result); } catch (e) { error = errors.InvalidResponse(request.responseText); } _this.connected = true; callback(error, result); } }; request.ontimeout = function () { _this.connected = false; callback(errors.ConnectionTimeout(this.timeout)); }; try { request.send(JSON.stringify(payload)); } catch (error) { this.connected = false; callback(errors.InvalidConnection(this.host)); } }; HttpProvider.prototype.disconnect = function () { //NO OP }; /** * Returns the desired boolean. * * @method supportsSubscriptions * @returns {boolean} */ HttpProvider.prototype.supportsSubscriptions = function () { return false; }; module.exports = HttpProvider; /***/ }), /***/ 39055: /*!**************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-providers-ipc/lib/index.js ***! \**************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** @file index.js * @authors: * Fabian Vogelsteller * @date 2017 */ var errors = __webpack_require__(/*! web3-core-helpers */ 20176).errors; var oboe = __webpack_require__(/*! oboe */ 71593); var IpcProvider = function IpcProvider(path, net) { var _this = this; this.responseCallbacks = {}; this.notificationCallbacks = []; this.path = path; this.connected = false; this.connection = net.connect({ path: this.path }); this.addDefaultEvents(); // LISTEN FOR CONNECTION RESPONSES var callback = function (result) { /*jshint maxcomplexity: 6 */ var id = null; // get the id which matches the returned id if (Array.isArray(result)) { result.forEach(function (load) { if (_this.responseCallbacks[load.id]) id = load.id; }); } else { id = result.id; } // notification if (!id && result.method.indexOf('_subscription') !== -1) { _this.notificationCallbacks.forEach(function (callback) { if (typeof callback === 'function') callback(result); }); // fire the callback } else if (_this.responseCallbacks[id]) { _this.responseCallbacks[id](null, result); delete _this.responseCallbacks[id]; } }; // use oboe.js for Sockets if (net.constructor.name === 'Socket') { oboe(this.connection) .done(callback); } else { this.connection.on('data', function (data) { _this._parseResponse(data.toString()).forEach(callback); }); } }; /** Will add the error and end event to timeout existing calls @method addDefaultEvents */ IpcProvider.prototype.addDefaultEvents = function () { var _this = this; this.connection.on('connect', function () { _this.connected = true; }); this.connection.on('close', function () { _this.connected = false; }); this.connection.on('error', function () { _this._timeout(); }); this.connection.on('end', function () { _this._timeout(); }); this.connection.on('timeout', function () { _this._timeout(); }); }; /** Will parse the response and make an array out of it. NOTE, this exists for backwards compatibility reasons. @method _parseResponse @param {String} data */ IpcProvider.prototype._parseResponse = function (data) { var _this = this, returnValues = []; // DE-CHUNKER var dechunkedData = data .replace(/\}[\n\r]?\{/g, '}|--|{') // }{ .replace(/\}\][\n\r]?\[\{/g, '}]|--|[{') // }][{ .replace(/\}[\n\r]?\[\{/g, '}|--|[{') // }[{ .replace(/\}\][\n\r]?\{/g, '}]|--|{') // }]{ .split('|--|'); dechunkedData.forEach(function (data) { // prepend the last chunk if (_this.lastChunk) data = _this.lastChunk + data; var result = null; try { result = JSON.parse(data); } catch (e) { _this.lastChunk = data; // start timeout to cancel all requests clearTimeout(_this.lastChunkTimeout); _this.lastChunkTimeout = setTimeout(function () { _this._timeout(); throw errors.InvalidResponse(data); }, 1000 * 15); return; } // cancel timeout and set chunk to null clearTimeout(_this.lastChunkTimeout); _this.lastChunk = null; if (result) returnValues.push(result); }); return returnValues; }; /** Get the adds a callback to the responseCallbacks object, which will be called if a response matching the response Id will arrive. @method _addResponseCallback */ IpcProvider.prototype._addResponseCallback = function (payload, callback) { var id = payload.id || payload[0].id; var method = payload.method || payload[0].method; this.responseCallbacks[id] = callback; this.responseCallbacks[id].method = method; }; /** Timeout all requests when the end/error event is fired @method _timeout */ IpcProvider.prototype._timeout = function () { for (var key in this.responseCallbacks) { if (this.responseCallbacks.hasOwnProperty(key)) { this.responseCallbacks[key](errors.InvalidConnection('on IPC')); delete this.responseCallbacks[key]; } } }; /** Try to reconnect @method reconnect */ IpcProvider.prototype.reconnect = function () { this.connection.connect({ path: this.path }); }; IpcProvider.prototype.send = function (payload, callback) { // try reconnect, when connection is gone if (!this.connection.writable) this.connection.connect({ path: this.path }); this.connection.write(JSON.stringify(payload)); this._addResponseCallback(payload, callback); }; /** Subscribes to provider events.provider @method on @param {String} type 'notification', 'connect', 'error', 'end' or 'data' @param {Function} callback the callback to call */ IpcProvider.prototype.on = function (type, callback) { if (typeof callback !== 'function') throw new Error('The second parameter callback must be a function.'); switch (type) { case 'data': this.notificationCallbacks.push(callback); break; // adds error, end, timeout, connect default: this.connection.on(type, callback); break; } }; /** Subscribes to provider events.provider @method on @param {String} type 'connect', 'error', 'end' or 'data' @param {Function} callback the callback to call */ IpcProvider.prototype.once = function (type, callback) { if (typeof callback !== 'function') throw new Error('The second parameter callback must be a function.'); this.connection.once(type, callback); }; /** Removes event listener @method removeListener @param {String} type 'data', 'connect', 'error', 'end' or 'data' @param {Function} callback the callback to call */ IpcProvider.prototype.removeListener = function (type, callback) { var _this = this; switch (type) { case 'data': this.notificationCallbacks.forEach(function (cb, index) { if (cb === callback) _this.notificationCallbacks.splice(index, 1); }); break; default: this.connection.removeListener(type, callback); break; } }; /** Removes all event listeners @method removeAllListeners @param {String} type 'data', 'connect', 'error', 'end' or 'data' */ IpcProvider.prototype.removeAllListeners = function (type) { switch (type) { case 'data': this.notificationCallbacks = []; break; default: this.connection.removeAllListeners(type); break; } }; /** Resets the providers, clears all callbacks @method reset */ IpcProvider.prototype.reset = function () { this._timeout(); this.notificationCallbacks = []; this.connection.removeAllListeners('error'); this.connection.removeAllListeners('end'); this.connection.removeAllListeners('timeout'); this.addDefaultEvents(); }; /** * Returns the desired boolean. * * @method supportsSubscriptions * @returns {boolean} */ IpcProvider.prototype.supportsSubscriptions = function () { return true; }; module.exports = IpcProvider; /***/ }), /***/ 80254: /*!***************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-providers-ws/lib/helpers.js ***! \***************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* provided dependency */ var process = __webpack_require__(/*! process/browser.js */ 29849); /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; var isRN = typeof navigator !== 'undefined' && navigator.product === 'ReactNative'; var _btoa = null; var helpers = null; if (isNode || isRN) { _btoa = function (str) { return Buffer.from(str).toString('base64'); }; var url = __webpack_require__(/*! url */ 38505); if (url.URL) { // Use the new Node 6+ API for parsing URLs that supports username/password var newURL = url.URL; helpers = function (url) { return new newURL(url); }; } else { // Web3 supports Node.js 5, so fall back to the legacy URL API if necessary helpers = __webpack_require__(/*! url */ 38505).parse; } } else { _btoa = btoa.bind(window); helpers = function (url) { return new URL(url); }; } module.exports = { parseURL: helpers, btoa: _btoa }; /***/ }), /***/ 48168: /*!*************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-providers-ws/lib/index.js ***! \*************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file WebsocketProvider.js * @authors: Samuel Furter , Fabian Vogelsteller * @date 2019 */ var EventEmitter = __webpack_require__(/*! eventemitter3 */ 38572); var helpers = __webpack_require__(/*! ./helpers.js */ 80254); var errors = __webpack_require__(/*! web3-core-helpers */ 20176).errors; var Ws = __webpack_require__(/*! websocket */ 66033).w3cwebsocket; /** * @param {string} url * @param {Object} options * * @constructor */ var WebsocketProvider = function WebsocketProvider(url, options) { EventEmitter.call(this); options = options || {}; this.url = url; this._customTimeout = options.timeout || 1000 * 15; this.headers = options.headers || {}; this.protocol = options.protocol || undefined; this.reconnectOptions = Object.assign({ auto: false, delay: 5000, maxAttempts: false, onTimeout: false }, options.reconnect); this.clientConfig = options.clientConfig || undefined; // Allow a custom client configuration this.requestOptions = options.requestOptions || undefined; // Allow a custom request options (https://github.com/theturtle32/WebSocket-Node/blob/master/docs/WebSocketClient.md#connectrequesturl-requestedprotocols-origin-headers-requestoptions) this.DATA = 'data'; this.CLOSE = 'close'; this.ERROR = 'error'; this.CONNECT = 'connect'; this.RECONNECT = 'reconnect'; this.connection = null; this.requestQueue = new Map(); this.responseQueue = new Map(); this.reconnectAttempts = 0; this.reconnecting = false; // The w3cwebsocket implementation does not support Basic Auth // username/password in the URL. So generate the basic auth header, and // pass through with any additional headers supplied in constructor var parsedURL = helpers.parseURL(url); if (parsedURL.username && parsedURL.password) { this.headers.authorization = 'Basic ' + helpers.btoa(parsedURL.username + ':' + parsedURL.password); } // When all node core implementations that do not have the // WHATWG compatible URL parser go out of service this line can be removed. if (parsedURL.auth) { this.headers.authorization = 'Basic ' + helpers.btoa(parsedURL.auth); } // make property `connected` which will return the current connection status Object.defineProperty(this, 'connected', { get: function () { return this.connection && this.connection.readyState === this.connection.OPEN; }, enumerable: true }); this.connect(); }; // Inherit from EventEmitter WebsocketProvider.prototype = Object.create(EventEmitter.prototype); WebsocketProvider.prototype.constructor = WebsocketProvider; /** * Connects to the configured node * * @method connect * * @returns {void} */ WebsocketProvider.prototype.connect = function () { this.connection = new Ws(this.url, this.protocol, undefined, this.headers, this.requestOptions, this.clientConfig); this._addSocketListeners(); }; /** * Listener for the `data` event of the underlying WebSocket object * * @method _onMessage * * @returns {void} */ WebsocketProvider.prototype._onMessage = function (e) { var _this = this; this._parseResponse((typeof e.data === 'string') ? e.data : '').forEach(function (result) { if (result.method && result.method.indexOf('_subscription') !== -1) { _this.emit(_this.DATA, result); return; } var id = result.id; // get the id which matches the returned id if (Array.isArray(result)) { id = result[0].id; } if (_this.responseQueue.has(id)) { if (_this.responseQueue.get(id).callback !== undefined) { _this.responseQueue.get(id).callback(false, result); } _this.responseQueue.delete(id); } }); }; /** * Listener for the `open` event of the underlying WebSocket object * * @method _onConnect * * @returns {void} */ WebsocketProvider.prototype._onConnect = function () { this.emit(this.CONNECT); this.reconnectAttempts = 0; this.reconnecting = false; if (this.requestQueue.size > 0) { var _this = this; this.requestQueue.forEach(function (request, key) { _this.send(request.payload, request.callback); _this.requestQueue.delete(key); }); } }; /** * Listener for the `close` event of the underlying WebSocket object * * @method _onClose * * @returns {void} */ WebsocketProvider.prototype._onClose = function (event) { var _this = this; if (this.reconnectOptions.auto && (![1000, 1001].includes(event.code) || event.wasClean === false)) { this.reconnect(); return; } this.emit(this.CLOSE, event); if (this.requestQueue.size > 0) { this.requestQueue.forEach(function (request, key) { request.callback(errors.ConnectionNotOpenError(event)); _this.requestQueue.delete(key); }); } if (this.responseQueue.size > 0) { this.responseQueue.forEach(function (request, key) { request.callback(errors.InvalidConnection('on WS', event)); _this.responseQueue.delete(key); }); } this._removeSocketListeners(); this.removeAllListeners(); }; /** * Will add the required socket listeners * * @method _addSocketListeners * * @returns {void} */ WebsocketProvider.prototype._addSocketListeners = function () { this.connection.addEventListener('message', this._onMessage.bind(this)); this.connection.addEventListener('open', this._onConnect.bind(this)); this.connection.addEventListener('close', this._onClose.bind(this)); }; /** * Will remove all socket listeners * * @method _removeSocketListeners * * @returns {void} */ WebsocketProvider.prototype._removeSocketListeners = function () { this.connection.removeEventListener('message', this._onMessage); this.connection.removeEventListener('open', this._onConnect); this.connection.removeEventListener('close', this._onClose); }; /** * Will parse the response and make an array out of it. * * @method _parseResponse * * @param {String} data * * @returns {Array} */ WebsocketProvider.prototype._parseResponse = function (data) { var _this = this, returnValues = []; // DE-CHUNKER var dechunkedData = data .replace(/\}[\n\r]?\{/g, '}|--|{') // }{ .replace(/\}\][\n\r]?\[\{/g, '}]|--|[{') // }][{ .replace(/\}[\n\r]?\[\{/g, '}|--|[{') // }[{ .replace(/\}\][\n\r]?\{/g, '}]|--|{') // }]{ .split('|--|'); dechunkedData.forEach(function (data) { // prepend the last chunk if (_this.lastChunk) data = _this.lastChunk + data; var result = null; try { result = JSON.parse(data); } catch (e) { _this.lastChunk = data; // start timeout to cancel all requests clearTimeout(_this.lastChunkTimeout); _this.lastChunkTimeout = setTimeout(function () { if (_this.reconnectOptions.auto && _this.reconnectOptions.onTimeout) { _this.reconnect(); return; } _this.emit(_this.ERROR, errors.ConnectionTimeout(_this._customTimeout)); if (_this.requestQueue.size > 0) { _this.requestQueue.forEach(function (request, key) { request.callback(errors.ConnectionTimeout(_this._customTimeout)); _this.requestQueue.delete(key); }); } }, _this._customTimeout); return; } // cancel timeout and set chunk to null clearTimeout(_this.lastChunkTimeout); _this.lastChunk = null; if (result) returnValues.push(result); }); return returnValues; }; /** * Does check if the provider is connecting and will add it to the queue or will send it directly * * @method send * * @param {Object} payload * @param {Function} callback * * @returns {void} */ WebsocketProvider.prototype.send = function (payload, callback) { var _this = this; var id = payload.id; var request = { payload: payload, callback: callback }; if (Array.isArray(payload)) { id = payload[0].id; } if (this.connection.readyState === this.connection.CONNECTING || this.reconnecting) { this.requestQueue.set(id, request); return; } if (this.connection.readyState !== this.connection.OPEN) { this.requestQueue.delete(id); this.emit(this.ERROR, errors.ConnectionNotOpenError()); request.callback(errors.ConnectionNotOpenError()); return; } this.responseQueue.set(id, request); this.requestQueue.delete(id); try { this.connection.send(JSON.stringify(request.payload)); } catch (error) { request.callback(error); _this.responseQueue.delete(id); } }; /** * Resets the providers, clears all callbacks * * @method reset * * @returns {void} */ WebsocketProvider.prototype.reset = function () { this.responseQueue.clear(); this.requestQueue.clear(); this.removeAllListeners(); this._removeSocketListeners(); this._addSocketListeners(); }; /** * Closes the current connection with the given code and reason arguments * * @method disconnect * * @param {number} code * @param {string} reason * * @returns {void} */ WebsocketProvider.prototype.disconnect = function (code, reason) { this._removeSocketListeners(); this.connection.close(code || 1000, reason); }; /** * Returns the desired boolean. * * @method supportsSubscriptions * * @returns {boolean} */ WebsocketProvider.prototype.supportsSubscriptions = function () { return true; }; /** * Removes the listeners and reconnects to the socket. * * @method reconnect * * @returns {void} */ WebsocketProvider.prototype.reconnect = function () { var _this = this; this.reconnecting = true; if (this.responseQueue.size > 0) { this.responseQueue.forEach(function (request, key) { request.callback(errors.PendingRequestsOnReconnectingError()); _this.responseQueue.delete(key); }); } if (!this.reconnectOptions.maxAttempts || this.reconnectAttempts < this.reconnectOptions.maxAttempts) { setTimeout(function () { _this.reconnectAttempts++; _this._removeSocketListeners(); _this.emit(_this.RECONNECT, _this.reconnectAttempts); _this.connect(); }, this.reconnectOptions.delay); return; } this.emit(this.ERROR, errors.MaxAttemptsReachedOnReconnectingError()); this.reconnecting = false; if (this.requestQueue.size > 0) { this.requestQueue.forEach(function (request, key) { request.callback(errors.MaxAttemptsReachedOnReconnectingError()); _this.requestQueue.delete(key); }); } }; module.exports = WebsocketProvider; /***/ }), /***/ 38572: /*!*********************!*\ !*** eventemitter3 ***! \*********************/ /***/ ((module) => { "use strict"; var has = Object.prototype.hasOwnProperty , prefix = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @private */ function Events() {} // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Add a listener for a given event. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} once Specify if the listener is a one-time listener. * @returns {EventEmitter} * @private */ function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } /** * Clear event by name. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} evt The Event name. * @private */ function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @public */ function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @public */ EventEmitter.prototype.eventNames = function eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Array} The registered listeners. * @public */ EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event , handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; /** * Return the number of listeners listening to a given event. * * @param {(String|Symbol)} event The event name. * @returns {Number} The number of listeners. * @public */ EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event , listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; /** * Calls each of the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; /** * Add a one-time listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; /** * Remove the listeners of a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {*} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {(String|Symbol)} [event] The event name. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // Expose the prefix. // EventEmitter.prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // EventEmitter.EventEmitter = EventEmitter; // // Expose the module. // if (true) { module.exports = EventEmitter; } /***/ }), /***/ 69053: /*!****************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-shh/lib/index.js ***! \****************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @author Fabian Vogelsteller * @date 2017 */ var core = __webpack_require__(/*! web3-core */ 79517); var Subscriptions = __webpack_require__(/*! web3-core-subscriptions */ 54923).subscriptions; var Method = __webpack_require__(/*! web3-core-method */ 50202); // var formatters = require('web3-core-helpers').formatters; var Net = __webpack_require__(/*! web3-net */ 26293); var Shh = function Shh() { var _this = this; // sets _requestmanager core.packageInit(this, arguments); // overwrite package setRequestManager var setRequestManager = this.setRequestManager; this.setRequestManager = function (manager) { setRequestManager(manager); _this.net.setRequestManager(manager); return true; }; // overwrite setProvider var setProvider = this.setProvider; this.setProvider = function () { setProvider.apply(_this, arguments); _this.setRequestManager(_this._requestManager); }; this.net = new Net(this); [ new Subscriptions({ name: 'subscribe', type: 'shh', subscriptions: { 'messages': { params: 1 // inputFormatter: [formatters.inputPostFormatter], // outputFormatter: formatters.outputPostFormatter } } }), new Method({ name: 'getVersion', call: 'shh_version', params: 0 }), new Method({ name: 'getInfo', call: 'shh_info', params: 0 }), new Method({ name: 'setMaxMessageSize', call: 'shh_setMaxMessageSize', params: 1 }), new Method({ name: 'setMinPoW', call: 'shh_setMinPoW', params: 1 }), new Method({ name: 'markTrustedPeer', call: 'shh_markTrustedPeer', params: 1 }), new Method({ name: 'newKeyPair', call: 'shh_newKeyPair', params: 0 }), new Method({ name: 'addPrivateKey', call: 'shh_addPrivateKey', params: 1 }), new Method({ name: 'deleteKeyPair', call: 'shh_deleteKeyPair', params: 1 }), new Method({ name: 'hasKeyPair', call: 'shh_hasKeyPair', params: 1 }), new Method({ name: 'getPublicKey', call: 'shh_getPublicKey', params: 1 }), new Method({ name: 'getPrivateKey', call: 'shh_getPrivateKey', params: 1 }), new Method({ name: 'newSymKey', call: 'shh_newSymKey', params: 0 }), new Method({ name: 'addSymKey', call: 'shh_addSymKey', params: 1 }), new Method({ name: 'generateSymKeyFromPassword', call: 'shh_generateSymKeyFromPassword', params: 1 }), new Method({ name: 'hasSymKey', call: 'shh_hasSymKey', params: 1 }), new Method({ name: 'getSymKey', call: 'shh_getSymKey', params: 1 }), new Method({ name: 'deleteSymKey', call: 'shh_deleteSymKey', params: 1 }), new Method({ name: 'newMessageFilter', call: 'shh_newMessageFilter', params: 1 }), new Method({ name: 'getFilterMessages', call: 'shh_getFilterMessages', params: 1 }), new Method({ name: 'deleteMessageFilter', call: 'shh_deleteMessageFilter', params: 1 }), new Method({ name: 'post', call: 'shh_post', params: 1, inputFormatter: [null] }), new Method({ name: 'unsubscribe', call: 'shh_unsubscribe', params: 1 }) ].forEach(function (method) { method.attachToObject(_this); method.setRequestManager(_this._requestManager); }); }; Shh.prototype.clearSubscriptions = function () { this._requestManager.clearSubscriptions(); }; core.addProviders(Shh); module.exports = Shh; /***/ }), /***/ 60819: /*!******************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-utils/lib/index.js ***! \******************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file utils.js * @author Marek Kotewicz * @author Fabian Vogelsteller * @date 2017 */ var ethjsUnit = __webpack_require__(/*! ethjs-unit */ 16128); var utils = __webpack_require__(/*! ./utils.js */ 24612); var soliditySha3 = __webpack_require__(/*! ./soliditySha3.js */ 78529); var randombytes = __webpack_require__(/*! randombytes */ 16589); var BN = __webpack_require__(/*! bn.js */ 62630); /** * Fires an error in an event emitter and callback and returns the eventemitter * * @method _fireError * @param {Object} error a string, a error, or an object with {message, data} * @param {Object} emitter * @param {Function} reject * @param {Function} callback * @param {any} optionalData * @return {Object} the emitter */ var _fireError = function (error, emitter, reject, callback, optionalData) { /*jshint maxcomplexity: 10 */ // add data if given if (!!error && typeof error === 'object' && !(error instanceof Error) && error.data) { if (!!error.data && typeof error.data === 'object' || Array.isArray(error.data)) { error.data = JSON.stringify(error.data, null, 2); } error = error.message + "\n" + error.data; } if (typeof error === 'string') { error = new Error(error); } if (typeof callback === 'function') { callback(error, optionalData); } if (typeof reject === 'function') { // suppress uncatched error if an error listener is present // OR suppress uncatched error if an callback listener is present if (emitter && (typeof emitter.listeners === 'function' && emitter.listeners('error').length) || typeof callback === 'function') { emitter.catch(function () { }); } // reject later, to be able to return emitter setTimeout(function () { reject(error); }, 1); } if (emitter && typeof emitter.emit === 'function') { // emit later, to be able to return emitter setTimeout(function () { emitter.emit('error', error, optionalData); emitter.removeAllListeners(); }, 1); } return emitter; }; /** * Should be used to create full function/event name from json abi * * @method _jsonInterfaceMethodToString * @param {Object} json * @return {String} full function/event name */ var _jsonInterfaceMethodToString = function (json) { if (!!json && typeof json === 'object' && json.name && json.name.indexOf('(') !== -1) { return json.name; } return json.name + '(' + _flattenTypes(false, json.inputs).join(',') + ')'; }; /** * Should be used to flatten json abi inputs/outputs into an array of type-representing-strings * * @method _flattenTypes * @param {bool} includeTuple * @param {Object} puts * @return {Array} parameters as strings */ var _flattenTypes = function (includeTuple, puts) { // console.log("entered _flattenTypes. inputs/outputs: " + puts) var types = []; puts.forEach(function (param) { if (typeof param.components === 'object') { if (param.type.substring(0, 5) !== 'tuple') { throw new Error('components found but type is not tuple; report on GitHub'); } var suffix = ''; var arrayBracket = param.type.indexOf('['); if (arrayBracket >= 0) { suffix = param.type.substring(arrayBracket); } var result = _flattenTypes(includeTuple, param.components); // console.log("result should have things: " + result) if (Array.isArray(result) && includeTuple) { // console.log("include tuple word, and its an array. joining...: " + result.types) types.push('tuple(' + result.join(',') + ')' + suffix); } else if (!includeTuple) { // console.log("don't include tuple, but its an array. joining...: " + result) types.push('(' + result.join(',') + ')' + suffix); } else { // console.log("its a single type within a tuple: " + result.types) types.push('(' + result + ')'); } } else { // console.log("its a type and not directly in a tuple: " + param.type) types.push(param.type); } }); return types; }; /** * Returns a random hex string by the given bytes size * * @param {Number} size * @returns {string} */ var randomHex = function (size) { return '0x' + randombytes(size).toString('hex'); }; /** * Should be called to get ascii from it's hex representation * * @method hexToAscii * @param {String} hex * @returns {String} ascii string representation of hex value */ var hexToAscii = function (hex) { if (!utils.isHexStrict(hex)) throw new Error('The parameter must be a valid HEX string.'); var str = ""; var i = 0, l = hex.length; if (hex.substring(0, 2) === '0x') { i = 2; } for (; i < l; i += 2) { var code = parseInt(hex.substr(i, 2), 16); str += String.fromCharCode(code); } return str; }; /** * Should be called to get hex representation (prefixed by 0x) of ascii string * * @method asciiToHex * @param {String} str * @returns {String} hex representation of input string */ var asciiToHex = function (str) { if (!str) return "0x00"; var hex = ""; for (var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); var n = code.toString(16); hex += n.length < 2 ? '0' + n : n; } return "0x" + hex; }; /** * Returns value of unit in Wei * * @method getUnitValue * @param {String} unit the unit to convert to, default ether * @returns {BN} value of the unit (in Wei) * @throws error if the unit is not correct:w */ var getUnitValue = function (unit) { unit = unit ? unit.toLowerCase() : 'ether'; if (!ethjsUnit.unitMap[unit]) { throw new Error('This unit "' + unit + '" doesn\'t exist, please use the one of the following units' + JSON.stringify(ethjsUnit.unitMap, null, 2)); } return unit; }; /** * Takes a number of wei and converts it to any other ether unit. * * Possible units are: * SI Short SI Full Effigy Other * - kwei femtoether babbage * - mwei picoether lovelace * - gwei nanoether shannon nano * - -- microether szabo micro * - -- milliether finney milli * - ether -- -- * - kether -- grand * - mether * - gether * - tether * * @method fromWei * @param {Number|String} number can be a number, number string or a HEX of a decimal * @param {String} unit the unit to convert to, default ether * @return {String|Object} When given a BN object it returns one as well, otherwise a number */ var fromWei = function (number, unit) { unit = getUnitValue(unit); if (!utils.isBN(number) && !(typeof number === 'string')) { throw new Error('Please pass numbers as strings or BN objects to avoid precision errors.'); } return utils.isBN(number) ? ethjsUnit.fromWei(number, unit) : ethjsUnit.fromWei(number, unit).toString(10); }; /** * Takes a number of a unit and converts it to wei. * * Possible units are: * SI Short SI Full Effigy Other * - kwei femtoether babbage * - mwei picoether lovelace * - gwei nanoether shannon nano * - -- microether szabo micro * - -- microether szabo micro * - -- milliether finney milli * - ether -- -- * - kether -- grand * - mether * - gether * - tether * * @method toWei * @param {Number|String|BN} number can be a number, number string or a HEX of a decimal * @param {String} unit the unit to convert from, default ether * @return {String|Object} When given a BN object it returns one as well, otherwise a number */ var toWei = function (number, unit) { unit = getUnitValue(unit); if (!utils.isBN(number) && !(typeof number === 'string')) { throw new Error('Please pass numbers as strings or BN objects to avoid precision errors.'); } return utils.isBN(number) ? ethjsUnit.toWei(number, unit) : ethjsUnit.toWei(number, unit).toString(10); }; /** * Converts to a checksum address * * @method toChecksumAddress * @param {String} address the given HEX address * @return {String} */ var toChecksumAddress = function (address) { if (typeof address === 'undefined') return ''; if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error('Given address "' + address + '" is not a valid Ethereum address.'); address = address.toLowerCase().replace(/^0x/i, ''); var addressHash = utils.sha3(address).replace(/^0x/i, ''); var checksumAddress = '0x'; for (var i = 0; i < address.length; i++) { // If ith character is 8 to f then make it uppercase if (parseInt(addressHash[i], 16) > 7) { checksumAddress += address[i].toUpperCase(); } else { checksumAddress += address[i]; } } return checksumAddress; }; /** * Returns -1 if ab; 0 if a == b. * For more details on this type of function, see * developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort * * @method compareBlockNumbers * * @param {String|Number|BN} a * * @param {String|Number|BN} b * * @returns {Number} -1, 0, or 1 */ var compareBlockNumbers = function (a, b) { if (a == b) { return 0; } else if (("genesis" == a || "earliest" == a || 0 == a) && ("genesis" == b || "earliest" == b || 0 == b)) { return 0; } else if ("genesis" == a || "earliest" == a) { // b !== a, thus a < b return -1; } else if ("genesis" == b || "earliest" == b) { // b !== a, thus a > b return 1; } else if (a == "latest") { if (b == "pending") { return -1; } else { // b !== ("pending" OR "latest"), thus a > b return 1; } } else if (b === "latest") { if (a == "pending") { return 1; } else { // b !== ("pending" OR "latest"), thus a > b return -1; } } else if (a == "pending") { // b (== OR <) "latest", thus a > b return 1; } else if (b == "pending") { return -1; } else { let bnA = new BN(a); let bnB = new BN(b); if (bnA.lt(bnB)) { return -1; } else if (bnA.eq(bnB)) { return 0; } else { return 1; } } }; module.exports = { _fireError: _fireError, _jsonInterfaceMethodToString: _jsonInterfaceMethodToString, _flattenTypes: _flattenTypes, // extractDisplayName: extractDisplayName, // extractTypeName: extractTypeName, randomHex: randomHex, BN: utils.BN, isBN: utils.isBN, isBigNumber: utils.isBigNumber, isHex: utils.isHex, isHexStrict: utils.isHexStrict, sha3: utils.sha3, sha3Raw: utils.sha3Raw, keccak256: utils.sha3, soliditySha3: soliditySha3.soliditySha3, soliditySha3Raw: soliditySha3.soliditySha3Raw, encodePacked: soliditySha3.encodePacked, isAddress: utils.isAddress, checkAddressChecksum: utils.checkAddressChecksum, toChecksumAddress: toChecksumAddress, toHex: utils.toHex, toBN: utils.toBN, bytesToHex: utils.bytesToHex, hexToBytes: utils.hexToBytes, hexToNumberString: utils.hexToNumberString, hexToNumber: utils.hexToNumber, toDecimal: utils.hexToNumber, numberToHex: utils.numberToHex, fromDecimal: utils.numberToHex, hexToUtf8: utils.hexToUtf8, hexToString: utils.hexToUtf8, toUtf8: utils.hexToUtf8, stripHexPrefix: utils.stripHexPrefix, utf8ToHex: utils.utf8ToHex, stringToHex: utils.utf8ToHex, fromUtf8: utils.utf8ToHex, hexToAscii: hexToAscii, toAscii: hexToAscii, asciiToHex: asciiToHex, fromAscii: asciiToHex, unitMap: ethjsUnit.unitMap, toWei: toWei, fromWei: fromWei, padLeft: utils.leftPad, leftPad: utils.leftPad, padRight: utils.rightPad, rightPad: utils.rightPad, toTwosComplement: utils.toTwosComplement, isBloom: utils.isBloom, isUserEthereumAddressInBloom: utils.isUserEthereumAddressInBloom, isContractAddressInBloom: utils.isContractAddressInBloom, isTopic: utils.isTopic, isTopicInBloom: utils.isTopicInBloom, isInBloom: utils.isInBloom, compareBlockNumbers: compareBlockNumbers, toNumber: utils.toNumber }; /***/ }), /***/ 78529: /*!*************************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-utils/lib/soliditySha3.js ***! \*************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file soliditySha3.js * @author Fabian Vogelsteller * @date 2017 */ var BN = __webpack_require__(/*! bn.js */ 62630); var utils = __webpack_require__(/*! ./utils.js */ 24612); var _elementaryName = function (name) { /*jshint maxcomplexity:false */ if (name.startsWith('int[')) { return 'int256' + name.slice(3); } else if (name === 'int') { return 'int256'; } else if (name.startsWith('uint[')) { return 'uint256' + name.slice(4); } else if (name === 'uint') { return 'uint256'; } else if (name.startsWith('fixed[')) { return 'fixed128x128' + name.slice(5); } else if (name === 'fixed') { return 'fixed128x128'; } else if (name.startsWith('ufixed[')) { return 'ufixed128x128' + name.slice(6); } else if (name === 'ufixed') { return 'ufixed128x128'; } return name; }; // Parse N from type var _parseTypeN = function (type) { var typesize = /^\D+(\d+).*$/.exec(type); return typesize ? parseInt(typesize[1], 10) : null; }; // Parse N from type[] var _parseTypeNArray = function (type) { var arraySize = /^\D+\d*\[(\d+)\]$/.exec(type); return arraySize ? parseInt(arraySize[1], 10) : null; }; var _parseNumber = function (arg) { var type = typeof arg; if (type === 'string') { if (utils.isHexStrict(arg)) { return new BN(arg.replace(/0x/i, ''), 16); } else { return new BN(arg, 10); } } else if (type === 'number') { return new BN(arg); } else if (utils.isBigNumber(arg)) { return new BN(arg.toString(10)); } else if (utils.isBN(arg)) { return arg; } else { throw new Error(arg + ' is not a number'); } }; var _solidityPack = function (type, value, arraySize) { /*jshint maxcomplexity:false */ var size, num; type = _elementaryName(type); if (type === 'bytes') { if (value.replace(/^0x/i, '').length % 2 !== 0) { throw new Error('Invalid bytes characters ' + value.length); } return value; } else if (type === 'string') { return utils.utf8ToHex(value); } else if (type === 'bool') { return value ? '01' : '00'; } else if (type.startsWith('address')) { if (arraySize) { size = 64; } else { size = 40; } if (!utils.isAddress(value)) { throw new Error(value + ' is not a valid address, or the checksum is invalid.'); } return utils.leftPad(value.toLowerCase(), size); } size = _parseTypeN(type); if (type.startsWith('bytes')) { if (!size) { throw new Error('bytes[] not yet supported in solidity'); } // must be 32 byte slices when in an array if (arraySize) { size = 32; } if (size < 1 || size > 32 || size < value.replace(/^0x/i, '').length / 2) { throw new Error('Invalid bytes' + size + ' for ' + value); } return utils.rightPad(value, size * 2); } else if (type.startsWith('uint')) { if ((size % 8) || (size < 8) || (size > 256)) { throw new Error('Invalid uint' + size + ' size'); } num = _parseNumber(value); if (num.bitLength() > size) { throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength()); } if (num.lt(new BN(0))) { throw new Error('Supplied uint ' + num.toString() + ' is negative'); } return size ? utils.leftPad(num.toString('hex'), size / 8 * 2) : num; } else if (type.startsWith('int')) { if ((size % 8) || (size < 8) || (size > 256)) { throw new Error('Invalid int' + size + ' size'); } num = _parseNumber(value); if (num.bitLength() > size) { throw new Error('Supplied int exceeds width: ' + size + ' vs ' + num.bitLength()); } if (num.lt(new BN(0))) { return num.toTwos(size).toString('hex'); } else { return size ? utils.leftPad(num.toString('hex'), size / 8 * 2) : num; } } else { // FIXME: support all other types throw new Error('Unsupported or invalid type: ' + type); } }; var _processSolidityEncodePackedArgs = function (arg) { /*jshint maxcomplexity:false */ if (Array.isArray(arg)) { throw new Error('Autodetection of array types is not supported.'); } var type, value = ''; var hexArg, arraySize; // if type is given if (!!arg && typeof arg === 'object' && (arg.hasOwnProperty('v') || arg.hasOwnProperty('t') || arg.hasOwnProperty('value') || arg.hasOwnProperty('type'))) { type = arg.hasOwnProperty('t') ? arg.t : arg.type; value = arg.hasOwnProperty('v') ? arg.v : arg.value; // otherwise try to guess the type } else { type = utils.toHex(arg, true); value = utils.toHex(arg); if (!type.startsWith('int') && !type.startsWith('uint')) { type = 'bytes'; } } if ((type.startsWith('int') || type.startsWith('uint')) && typeof value === 'string' && !/^(-)?0x/i.test(value)) { value = new BN(value); } // get the array size if (Array.isArray(value)) { arraySize = _parseTypeNArray(type); if (arraySize && value.length !== arraySize) { throw new Error(type + ' is not matching the given array ' + JSON.stringify(value)); } else { arraySize = value.length; } } if (Array.isArray(value)) { hexArg = value.map(function (val) { return _solidityPack(type, val, arraySize).toString('hex').replace('0x', ''); }); return hexArg.join(''); } else { hexArg = _solidityPack(type, value, arraySize); return hexArg.toString('hex').replace('0x', ''); } }; /** * Hashes solidity values to a sha3 hash using keccak 256 * * @method soliditySha3 * @return {Object} the sha3 */ var soliditySha3 = function () { /*jshint maxcomplexity:false */ var args = Array.prototype.slice.call(arguments); var hexArgs = args.map(_processSolidityEncodePackedArgs); // console.log(args, hexArgs); // console.log('0x'+ hexArgs.join('')); return utils.sha3('0x' + hexArgs.join('')); }; /** * Hashes solidity values to a sha3 hash using keccak 256 but does return the hash of value `null` instead of `null` * * @method soliditySha3Raw * @return {Object} the sha3 */ var soliditySha3Raw = function () { return utils.sha3Raw('0x' + Array.prototype.slice.call(arguments).map(_processSolidityEncodePackedArgs).join('')); }; /** * Encode packed args to hex * * @method encodePacked * @return {String} the hex encoded arguments */ var encodePacked = function () { /*jshint maxcomplexity:false */ var args = Array.prototype.slice.call(arguments); var hexArgs = args.map(_processSolidityEncodePackedArgs); return '0x' + hexArgs.join('').toLowerCase(); }; module.exports = { soliditySha3: soliditySha3, soliditySha3Raw: soliditySha3Raw, encodePacked: encodePacked }; /***/ }), /***/ 24612: /*!******************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3-utils/lib/utils.js ***! \******************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ 3875)["Buffer"]; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file utils.js * @author Fabian Vogelsteller * @date 2017 */ var BN = __webpack_require__(/*! bn.js */ 62630); var numberToBN = __webpack_require__(/*! number-to-bn */ 7388); var utf8 = __webpack_require__(/*! utf8 */ 43790); var ethereumjsUtil = __webpack_require__(/*! ethereumjs-util */ 34692); var ethereumBloomFilters = __webpack_require__(/*! ethereum-bloom-filters */ 25613); /** * Returns true if object is BN, otherwise false * * @method isBN * @param {Object} object * @return {Boolean} */ var isBN = function (object) { return BN.isBN(object); }; /** * Returns true if object is BigNumber, otherwise false * * @method isBigNumber * @param {Object} object * @return {Boolean} */ var isBigNumber = function (object) { return object && object.constructor && object.constructor.name === 'BigNumber'; }; /** * Takes an input and transforms it into an BN * * @method toBN * @param {Number|String|BN} number, string, HEX string or BN * @return {BN} BN */ var toBN = function (number) { try { return numberToBN.apply(null, arguments); } catch (e) { throw new Error(e + ' Given value: "' + number + '"'); } }; /** * Takes and input transforms it into BN and if it is negative value, into two's complement * * @method toTwosComplement * @param {Number|String|BN} number * @return {String} */ var toTwosComplement = function (number) { return '0x' + toBN(number).toTwos(256).toString(16, 64); }; /** * Checks if the given string is an address * * @method isAddress * @param {String} address the given HEX address * @return {Boolean} */ var isAddress = function (address) { // check if it has the basic requirements of an address if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { return false; // If it's ALL lowercase or ALL upppercase } else if (/^(0x|0X)?[0-9a-f]{40}$/.test(address) || /^(0x|0X)?[0-9A-F]{40}$/.test(address)) { return true; // Otherwise check each case } else { return checkAddressChecksum(address); } }; /** * Checks if the given string is a checksummed address * * @method checkAddressChecksum * @param {String} address the given HEX address * @return {Boolean} */ var checkAddressChecksum = function (address) { // Check each case address = address.replace(/^0x/i, ''); var addressHash = sha3(address.toLowerCase()).replace(/^0x/i, ''); for (var i = 0; i < 40; i++) { // the nth letter should be uppercase if the nth digit of casemap is 1 if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { return false; } } return true; }; /** * Should be called to pad string to expected length * * @method leftPad * @param {String} string to be padded * @param {Number} chars that result string should have * @param {String} sign, by default 0 * @returns {String} right aligned string */ var leftPad = function (string, chars, sign) { var hasPrefix = /^0x/i.test(string) || typeof string === 'number'; string = string.toString(16).replace(/^0x/i, ''); var padding = (chars - string.length + 1 >= 0) ? chars - string.length + 1 : 0; return (hasPrefix ? '0x' : '') + new Array(padding).join(sign ? sign : "0") + string; }; /** * Should be called to pad string to expected length * * @method rightPad * @param {String} string to be padded * @param {Number} chars that result string should have * @param {String} sign, by default 0 * @returns {String} right aligned string */ var rightPad = function (string, chars, sign) { var hasPrefix = /^0x/i.test(string) || typeof string === 'number'; string = string.toString(16).replace(/^0x/i, ''); var padding = (chars - string.length + 1 >= 0) ? chars - string.length + 1 : 0; return (hasPrefix ? '0x' : '') + string + (new Array(padding).join(sign ? sign : "0")); }; /** * Should be called to get hex representation (prefixed by 0x) of utf8 string * * @method utf8ToHex * @param {String} str * @returns {String} hex representation of input string */ var utf8ToHex = function (str) { str = utf8.encode(str); var hex = ""; // remove \u0000 padding from either side str = str.replace(/^(?:\u0000)*/, ''); str = str.split("").reverse().join(""); str = str.replace(/^(?:\u0000)*/, ''); str = str.split("").reverse().join(""); for (var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); // if (code !== 0) { var n = code.toString(16); hex += n.length < 2 ? '0' + n : n; // } } return "0x" + hex; }; /** * Should be called to get utf8 from it's hex representation * * @method hexToUtf8 * @param {String} hex * @returns {String} ascii string representation of hex value */ var hexToUtf8 = function (hex) { if (!isHexStrict(hex)) throw new Error('The parameter "' + hex + '" must be a valid HEX string.'); var str = ""; var code = 0; hex = hex.replace(/^0x/i, ''); // remove 00 padding from either side hex = hex.replace(/^(?:00)*/, ''); hex = hex.split("").reverse().join(""); hex = hex.replace(/^(?:00)*/, ''); hex = hex.split("").reverse().join(""); var l = hex.length; for (var i = 0; i < l; i += 2) { code = parseInt(hex.substr(i, 2), 16); // if (code !== 0) { str += String.fromCharCode(code); // } } return utf8.decode(str); }; /** * Converts value to it's number representation * * @method hexToNumber * @param {String|Number|BN} value * @return {String} */ var hexToNumber = function (value) { if (!value) { return value; } if (typeof value === 'string' && !isHexStrict(value)) { throw new Error('Given value "' + value + '" is not a valid hex string.'); } return toBN(value).toNumber(); }; /** * Converts value to it's decimal representation in string * * @method hexToNumberString * @param {String|Number|BN} value * @return {String} */ var hexToNumberString = function (value) { if (!value) return value; if (typeof value === 'string' && !isHexStrict(value)) { throw new Error('Given value "' + value + '" is not a valid hex string.'); } return toBN(value).toString(10); }; /** * Converts value to it's hex representation * * @method numberToHex * @param {String|Number|BN} value * @return {String} */ var numberToHex = function (value) { if ((value === null || value === undefined)) { return value; } if (!isFinite(value) && !isHexStrict(value)) { throw new Error('Given input "' + value + '" is not a number.'); } var number = toBN(value); var result = number.toString(16); return number.lt(new BN(0)) ? '-0x' + result.substr(1) : '0x' + result; }; /** * Convert a byte array to a hex string * * Note: Implementation from crypto-js * * @method bytesToHex * @param {Array} bytes * @return {String} the hex string */ var bytesToHex = function (bytes) { for (var hex = [], i = 0; i < bytes.length; i++) { /* jshint ignore:start */ hex.push((bytes[i] >>> 4).toString(16)); hex.push((bytes[i] & 0xF).toString(16)); /* jshint ignore:end */ } return '0x' + hex.join(""); }; /** * Convert a hex string to a byte array * * Note: Implementation from crypto-js * * @method hexToBytes * @param {string} hex * @return {Array} the byte array */ var hexToBytes = function (hex) { hex = hex.toString(16); if (!isHexStrict(hex)) { throw new Error('Given value "' + hex + '" is not a valid hex string.'); } hex = hex.replace(/^0x/i, ''); for (var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16)); return bytes; }; /** * Auto converts any given value into it's hex representation. * * And even stringifys objects before. * * @method toHex * @param {String|Number|BN|Object|Buffer} value * @param {Boolean} returnType * @return {String} */ var toHex = function (value, returnType) { /*jshint maxcomplexity: false */ if (isAddress(value)) { return returnType ? 'address' : '0x' + value.toLowerCase().replace(/^0x/i, ''); } if (typeof value === 'boolean') { return returnType ? 'bool' : value ? '0x01' : '0x00'; } if (Buffer.isBuffer(value)) { return '0x' + value.toString('hex'); } if (typeof value === 'object' && !!value && !isBigNumber(value) && !isBN(value)) { return returnType ? 'string' : utf8ToHex(JSON.stringify(value)); } // if its a negative number, pass it through numberToHex if (typeof value === 'string') { if (value.indexOf('-0x') === 0 || value.indexOf('-0X') === 0) { return returnType ? 'int256' : numberToHex(value); } else if (value.indexOf('0x') === 0 || value.indexOf('0X') === 0) { return returnType ? 'bytes' : value; } else if (!isFinite(value)) { return returnType ? 'string' : utf8ToHex(value); } } return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value); }; /** * Check if string is HEX, requires a 0x in front * * @method isHexStrict * @param {String} hex to be checked * @returns {Boolean} */ var isHexStrict = function (hex) { return ((typeof hex === 'string' || typeof hex === 'number') && /^(-)?0x[0-9a-f]*$/i.test(hex)); }; /** * Check if string is HEX * * @method isHex * @param {String} hex to be checked * @returns {Boolean} */ var isHex = function (hex) { return ((typeof hex === 'string' || typeof hex === 'number') && /^(-0x|0x)?[0-9a-f]*$/i.test(hex)); }; /** * Remove 0x prefix from string * * @method stripHexPrefix * @param {String} str to be checked * @returns {String} */ var stripHexPrefix = function (str) { if (str !== 0 && isHex(str)) return str.replace(/^(-)?0x/i, '$1'); return str; }; /** * Returns true if given string is a valid Ethereum block header bloom. * * @method isBloom * @param {String} bloom encoded bloom filter * @return {Boolean} */ var isBloom = function (bloom) { return ethereumBloomFilters.isBloom(bloom); }; /** * Returns true if the ethereum users address is part of the given bloom * note: false positives are possible. * * @method isUserEthereumAddressInBloom * @param {String} ethereumAddress encoded bloom filter * @param {String} bloom ethereum addresss * @return {Boolean} */ var isUserEthereumAddressInBloom = function (bloom, ethereumAddress) { return ethereumBloomFilters.isUserEthereumAddressInBloom(bloom, ethereumAddress); }; /** * Returns true if the contract address is part of the given bloom * note: false positives are possible. * * @method isUserEthereumAddressInBloom * @param {String} bloom encoded bloom filter * @param {String} contractAddress contract addresss * @return {Boolean} */ var isContractAddressInBloom = function (bloom, contractAddress) { return ethereumBloomFilters.isContractAddressInBloom(bloom, contractAddress); }; /** * Returns true if given string is a valid log topic. * * @method isTopic * @param {String} topic encoded topic * @return {Boolean} */ var isTopic = function (topic) { return ethereumBloomFilters.isTopic(topic); }; /** * Returns true if the topic is part of the given bloom * note: false positives are possible. * * @method isTopicInBloom * @param {String} bloom encoded bloom filter * @param {String} topic encoded topic * @return {Boolean} */ var isTopicInBloom = function (bloom, topic) { return ethereumBloomFilters.isTopicInBloom(bloom, topic); }; /** * Returns true if the value is part of the given bloom * note: false positives are possible. * * @method isInBloom * @param {String} bloom encoded bloom filter * @param {String | Uint8Array} topic encoded value * @return {Boolean} */ var isInBloom = function (bloom, topic) { return ethereumBloomFilters.isInBloom(bloom, topic); }; /** * Hashes values to a sha3 hash using keccak 256 * * To hash a HEX string the hex must have 0x in front. * * @method sha3 * @return {String} the sha3 string */ var SHA3_NULL_S = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; var sha3 = function (value) { if (isBN(value)) { value = value.toString(); } if (isHexStrict(value) && /^0x/i.test((value).toString())) { value = ethereumjsUtil.toBuffer(value); } else if (typeof value === 'string') { // Assume value is an arbitrary string value = Buffer.from(value, 'utf-8'); } var returnValue = ethereumjsUtil.bufferToHex(ethereumjsUtil.keccak256(value)); if (returnValue === SHA3_NULL_S) { return null; } else { return returnValue; } }; // expose the under the hood keccak256 sha3._Hash = ethereumjsUtil.keccak256; /** * @method sha3Raw * * @param value * * @returns {string} */ var sha3Raw = function (value) { value = sha3(value); if (value === null) { return SHA3_NULL_S; } return value; }; /** * Auto converts any given value into it's hex representation, * then converts hex to number. * * @method toNumber * @param {String|Number|BN} value * @return {Number} */ var toNumber = function (value) { return typeof value === 'number' ? value : hexToNumber(toHex(value)); }; module.exports = { BN: BN, isBN: isBN, isBigNumber: isBigNumber, toBN: toBN, isAddress: isAddress, isBloom: isBloom, isUserEthereumAddressInBloom: isUserEthereumAddressInBloom, isContractAddressInBloom: isContractAddressInBloom, isTopic: isTopic, isTopicInBloom: isTopicInBloom, isInBloom: isInBloom, checkAddressChecksum: checkAddressChecksum, utf8ToHex: utf8ToHex, hexToUtf8: hexToUtf8, hexToNumber: hexToNumber, hexToNumberString: hexToNumberString, numberToHex: numberToHex, toHex: toHex, hexToBytes: hexToBytes, bytesToHex: bytesToHex, isHex: isHex, isHexStrict: isHexStrict, stripHexPrefix: stripHexPrefix, leftPad: leftPad, rightPad: rightPad, toTwosComplement: toTwosComplement, sha3: sha3, sha3Raw: sha3Raw, toNumber: toNumber }; /***/ }), /***/ 88912: /*!************************************************************************!*\ !*** ./node_modules/@alch/alchemy-web3/node_modules/web3/lib/index.js ***! \************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ /** * @file index.js * @authors: * Fabian Vogelsteller * Gav Wood * Jeffrey Wilcke * Marek Kotewicz * Marian Oancea * @date 2017 */ var version = __webpack_require__(/*! ../package.json */ 1934).version; var core = __webpack_require__(/*! web3-core */ 79517); var Eth = __webpack_require__(/*! web3-eth */ 38805); var Net = __webpack_require__(/*! web3-net */ 26293); var Personal = __webpack_require__(/*! web3-eth-personal */ 82330); var Shh = __webpack_require__(/*! web3-shh */ 69053); var Bzz = __webpack_require__(/*! web3-bzz */ 22165); var utils = __webpack_require__(/*! web3-utils */ 60819); var Web3 = function Web3() { var _this = this; // sets _requestmanager etc core.packageInit(this, arguments); this.version = version; this.utils = utils; this.eth = new Eth(this); this.shh = new Shh(this); this.bzz = new Bzz(this); // overwrite package setProvider var setProvider = this.setProvider; this.setProvider = function (provider, net) { /*jshint unused: false */ setProvider.apply(_this, arguments); _this.eth.setRequestManager(_this._requestManager); _this.shh.setRequestManager(_this._requestManager); _this.bzz.setProvider(provider); return true; }; }; Web3.version = version; Web3.utils = utils; Web3.modules = { Eth: Eth, Net: Net, Personal: Personal, Shh: Shh, Bzz: Bzz }; core.addProviders(Web3); module.exports = Web3; /***/ }), /***/ 38583: /*!**********************************************************************!*\ !*** ./node_modules/@angular/common/__ivy_ngcc__/fesm2015/common.js ***! \**********************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "APP_BASE_HREF": () => (/* binding */ APP_BASE_HREF), /* harmony export */ "AsyncPipe": () => (/* binding */ AsyncPipe), /* harmony export */ "CommonModule": () => (/* binding */ CommonModule), /* harmony export */ "CurrencyPipe": () => (/* binding */ CurrencyPipe), /* harmony export */ "DOCUMENT": () => (/* binding */ DOCUMENT), /* harmony export */ "DatePipe": () => (/* binding */ DatePipe), /* harmony export */ "DecimalPipe": () => (/* binding */ DecimalPipe), /* harmony export */ "FormStyle": () => (/* binding */ FormStyle), /* harmony export */ "FormatWidth": () => (/* binding */ FormatWidth), /* harmony export */ "HashLocationStrategy": () => (/* binding */ HashLocationStrategy), /* harmony export */ "I18nPluralPipe": () => (/* binding */ I18nPluralPipe), /* harmony export */ "I18nSelectPipe": () => (/* binding */ I18nSelectPipe), /* harmony export */ "JsonPipe": () => (/* binding */ JsonPipe), /* harmony export */ "KeyValuePipe": () => (/* binding */ KeyValuePipe), /* harmony export */ "LOCATION_INITIALIZED": () => (/* binding */ LOCATION_INITIALIZED), /* harmony export */ "Location": () => (/* binding */ Location), /* harmony export */ "LocationStrategy": () => (/* binding */ LocationStrategy), /* harmony export */ "LowerCasePipe": () => (/* binding */ LowerCasePipe), /* harmony export */ "NgClass": () => (/* binding */ NgClass), /* harmony export */ "NgComponentOutlet": () => (/* binding */ NgComponentOutlet), /* harmony export */ "NgForOf": () => (/* binding */ NgForOf), /* harmony export */ "NgForOfContext": () => (/* binding */ NgForOfContext), /* harmony export */ "NgIf": () => (/* binding */ NgIf), /* harmony export */ "NgIfContext": () => (/* binding */ NgIfContext), /* harmony export */ "NgLocaleLocalization": () => (/* binding */ NgLocaleLocalization), /* harmony export */ "NgLocalization": () => (/* binding */ NgLocalization), /* harmony export */ "NgPlural": () => (/* binding */ NgPlural), /* harmony export */ "NgPluralCase": () => (/* binding */ NgPluralCase), /* harmony export */ "NgStyle": () => (/* binding */ NgStyle), /* harmony export */ "NgSwitch": () => (/* binding */ NgSwitch), /* harmony export */ "NgSwitchCase": () => (/* binding */ NgSwitchCase), /* harmony export */ "NgSwitchDefault": () => (/* binding */ NgSwitchDefault), /* harmony export */ "NgTemplateOutlet": () => (/* binding */ NgTemplateOutlet), /* harmony export */ "NumberFormatStyle": () => (/* binding */ NumberFormatStyle), /* harmony export */ "NumberSymbol": () => (/* binding */ NumberSymbol), /* harmony export */ "PathLocationStrategy": () => (/* binding */ PathLocationStrategy), /* harmony export */ "PercentPipe": () => (/* binding */ PercentPipe), /* harmony export */ "PlatformLocation": () => (/* binding */ PlatformLocation), /* harmony export */ "Plural": () => (/* binding */ Plural), /* harmony export */ "SlicePipe": () => (/* binding */ SlicePipe), /* harmony export */ "TitleCasePipe": () => (/* binding */ TitleCasePipe), /* harmony export */ "TranslationWidth": () => (/* binding */ TranslationWidth), /* harmony export */ "UpperCasePipe": () => (/* binding */ UpperCasePipe), /* harmony export */ "VERSION": () => (/* binding */ VERSION), /* harmony export */ "ViewportScroller": () => (/* binding */ ViewportScroller), /* harmony export */ "WeekDay": () => (/* binding */ WeekDay), /* harmony export */ "XhrFactory": () => (/* binding */ XhrFactory), /* harmony export */ "formatCurrency": () => (/* binding */ formatCurrency), /* harmony export */ "formatDate": () => (/* binding */ formatDate), /* harmony export */ "formatNumber": () => (/* binding */ formatNumber), /* harmony export */ "formatPercent": () => (/* binding */ formatPercent), /* harmony export */ "getCurrencySymbol": () => (/* binding */ getCurrencySymbol), /* harmony export */ "getLocaleCurrencyCode": () => (/* binding */ getLocaleCurrencyCode), /* harmony export */ "getLocaleCurrencyName": () => (/* binding */ getLocaleCurrencyName), /* harmony export */ "getLocaleCurrencySymbol": () => (/* binding */ getLocaleCurrencySymbol), /* harmony export */ "getLocaleDateFormat": () => (/* binding */ getLocaleDateFormat), /* harmony export */ "getLocaleDateTimeFormat": () => (/* binding */ getLocaleDateTimeFormat), /* harmony export */ "getLocaleDayNames": () => (/* binding */ getLocaleDayNames), /* harmony export */ "getLocaleDayPeriods": () => (/* binding */ getLocaleDayPeriods), /* harmony export */ "getLocaleDirection": () => (/* binding */ getLocaleDirection), /* harmony export */ "getLocaleEraNames": () => (/* binding */ getLocaleEraNames), /* harmony export */ "getLocaleExtraDayPeriodRules": () => (/* binding */ getLocaleExtraDayPeriodRules), /* harmony export */ "getLocaleExtraDayPeriods": () => (/* binding */ getLocaleExtraDayPeriods), /* harmony export */ "getLocaleFirstDayOfWeek": () => (/* binding */ getLocaleFirstDayOfWeek), /* harmony export */ "getLocaleId": () => (/* binding */ getLocaleId), /* harmony export */ "getLocaleMonthNames": () => (/* binding */ getLocaleMonthNames), /* harmony export */ "getLocaleNumberFormat": () => (/* binding */ getLocaleNumberFormat), /* harmony export */ "getLocaleNumberSymbol": () => (/* binding */ getLocaleNumberSymbol), /* harmony export */ "getLocalePluralCase": () => (/* binding */ getLocalePluralCase), /* harmony export */ "getLocaleTimeFormat": () => (/* binding */ getLocaleTimeFormat), /* harmony export */ "getLocaleWeekEndRange": () => (/* binding */ getLocaleWeekEndRange), /* harmony export */ "getNumberOfCurrencyDigits": () => (/* binding */ getNumberOfCurrencyDigits), /* harmony export */ "isPlatformBrowser": () => (/* binding */ isPlatformBrowser), /* harmony export */ "isPlatformServer": () => (/* binding */ isPlatformServer), /* harmony export */ "isPlatformWorkerApp": () => (/* binding */ isPlatformWorkerApp), /* harmony export */ "isPlatformWorkerUi": () => (/* binding */ isPlatformWorkerUi), /* harmony export */ "registerLocaleData": () => (/* binding */ registerLocaleData), /* harmony export */ "ɵBrowserPlatformLocation": () => (/* binding */ BrowserPlatformLocation), /* harmony export */ "ɵDomAdapter": () => (/* binding */ DomAdapter), /* harmony export */ "ɵNullViewportScroller": () => (/* binding */ NullViewportScroller), /* harmony export */ "ɵPLATFORM_BROWSER_ID": () => (/* binding */ PLATFORM_BROWSER_ID), /* harmony export */ "ɵPLATFORM_SERVER_ID": () => (/* binding */ PLATFORM_SERVER_ID), /* harmony export */ "ɵPLATFORM_WORKER_APP_ID": () => (/* binding */ PLATFORM_WORKER_APP_ID), /* harmony export */ "ɵPLATFORM_WORKER_UI_ID": () => (/* binding */ PLATFORM_WORKER_UI_ID), /* harmony export */ "ɵangular_packages_common_common_a": () => (/* binding */ useBrowserPlatformLocation), /* harmony export */ "ɵangular_packages_common_common_b": () => (/* binding */ createBrowserPlatformLocation), /* harmony export */ "ɵangular_packages_common_common_c": () => (/* binding */ createLocation), /* harmony export */ "ɵangular_packages_common_common_d": () => (/* binding */ provideLocationStrategy), /* harmony export */ "ɵangular_packages_common_common_e": () => (/* binding */ COMMON_DIRECTIVES), /* harmony export */ "ɵangular_packages_common_common_f": () => (/* binding */ COMMON_PIPES), /* harmony export */ "ɵgetDOM": () => (/* binding */ getDOM), /* harmony export */ "ɵparseCookieValue": () => (/* binding */ parseCookieValue), /* harmony export */ "ɵsetRootDomAdapter": () => (/* binding */ setRootDomAdapter) /* harmony export */ }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ 37716); /* provided dependency */ var console = __webpack_require__(/*! console-browserify */ 88883); /** * @license Angular v12.0.5 * (c) 2010-2021 Google LLC. https://angular.io/ * License: MIT */ /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ let _DOM = null; function getDOM() { return _DOM; } function setDOM(adapter) { _DOM = adapter; } function setRootDomAdapter(adapter) { if (!_DOM) { _DOM = adapter; } } /* tslint:disable:requireParameterType */ /** * Provides DOM operations in an environment-agnostic way. * * @security Tread carefully! Interacting with the DOM directly is dangerous and * can introduce XSS risks. */ class DomAdapter { } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A DI Token representing the main rendering context. In a browser this is the DOM Document. * * Note: Document might not be available in the Application Context when Application and Rendering * Contexts are not the same (e.g. when running the application in a Web Worker). * * @publicApi */ const DOCUMENT = new _angular_core__WEBPACK_IMPORTED_MODULE_0__.InjectionToken('DocumentToken'); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * This class should not be used directly by an application developer. Instead, use * {@link Location}. * * `PlatformLocation` encapsulates all calls to DOM APIs, which allows the Router to be * platform-agnostic. * This means that we can have different implementation of `PlatformLocation` for the different * platforms that Angular supports. For example, `@angular/platform-browser` provides an * implementation specific to the browser environment, while `@angular/platform-server` provides * one suitable for use with server-side rendering. * * The `PlatformLocation` class is used directly by all implementations of {@link LocationStrategy} * when they need to interact with the DOM APIs like pushState, popState, etc. * * {@link LocationStrategy} in turn is used by the {@link Location} service which is used directly * by the {@link Router} in order to navigate between routes. Since all interactions between {@link * Router} / * {@link Location} / {@link LocationStrategy} and DOM APIs flow through the `PlatformLocation` * class, they are all platform-agnostic. * * @publicApi */ class PlatformLocation { historyGo(relativePosition) { throw new Error('Not implemented'); } } PlatformLocation.ɵfac = function PlatformLocation_Factory(t) { return new (t || PlatformLocation)(); }; PlatformLocation.ɵprov = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"])({ factory: useBrowserPlatformLocation, token: PlatformLocation, providedIn: "platform" }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](PlatformLocation, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Injectable, args: [{ providedIn: 'platform', // See #23917 useFactory: useBrowserPlatformLocation }] }], null, null); })(); function useBrowserPlatformLocation() { return (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(BrowserPlatformLocation); } /** * @description * Indicates when a location is initialized. * * @publicApi */ const LOCATION_INITIALIZED = new _angular_core__WEBPACK_IMPORTED_MODULE_0__.InjectionToken('Location Initialized'); /** * `PlatformLocation` encapsulates all of the direct calls to platform APIs. * This class should not be used directly by an application developer. Instead, use * {@link Location}. */ class BrowserPlatformLocation extends PlatformLocation { constructor(_doc) { super(); this._doc = _doc; this._init(); } // This is moved to its own method so that `MockPlatformLocationStrategy` can overwrite it /** @internal */ _init() { this.location = window.location; this._history = window.history; } getBaseHrefFromDOM() { return getDOM().getBaseHref(this._doc); } onPopState(fn) { const window = getDOM().getGlobalEventTarget(this._doc, 'window'); window.addEventListener('popstate', fn, false); return () => window.removeEventListener('popstate', fn); } onHashChange(fn) { const window = getDOM().getGlobalEventTarget(this._doc, 'window'); window.addEventListener('hashchange', fn, false); return () => window.removeEventListener('hashchange', fn); } get href() { return this.location.href; } get protocol() { return this.location.protocol; } get hostname() { return this.location.hostname; } get port() { return this.location.port; } get pathname() { return this.location.pathname; } get search() { return this.location.search; } get hash() { return this.location.hash; } set pathname(newPath) { this.location.pathname = newPath; } pushState(state, title, url) { if (supportsState()) { this._history.pushState(state, title, url); } else { this.location.hash = url; } } replaceState(state, title, url) { if (supportsState()) { this._history.replaceState(state, title, url); } else { this.location.hash = url; } } forward() { this._history.forward(); } back() { this._history.back(); } historyGo(relativePosition = 0) { this._history.go(relativePosition); } getState() { return this._history.state; } } BrowserPlatformLocation.ɵfac = function BrowserPlatformLocation_Factory(t) { return new (t || BrowserPlatformLocation)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](DOCUMENT)); }; BrowserPlatformLocation.ɵprov = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"])({ factory: createBrowserPlatformLocation, token: BrowserPlatformLocation, providedIn: "platform" }); BrowserPlatformLocation.ctorParameters = () => [ { type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [DOCUMENT,] }] } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](BrowserPlatformLocation, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Injectable, args: [{ providedIn: 'platform', // See #23917 useFactory: createBrowserPlatformLocation }] }], function () { return [{ type: undefined, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [DOCUMENT] }] }]; }, null); })(); function supportsState() { return !!window.history.pushState; } function createBrowserPlatformLocation() { return new BrowserPlatformLocation((0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(DOCUMENT)); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Joins two parts of a URL with a slash if needed. * * @param start URL string * @param end URL string * * * @returns The joined URL string. */ function joinWithSlash(start, end) { if (start.length == 0) { return end; } if (end.length == 0) { return start; } let slashes = 0; if (start.endsWith('/')) { slashes++; } if (end.startsWith('/')) { slashes++; } if (slashes == 2) { return start + end.substring(1); } if (slashes == 1) { return start + end; } return start + '/' + end; } /** * Removes a trailing slash from a URL string if needed. * Looks for the first occurrence of either `#`, `?`, or the end of the * line as `/` characters and removes the trailing slash if one exists. * * @param url URL string. * * @returns The URL string, modified if needed. */ function stripTrailingSlash(url) { const match = url.match(/#|\?|$/); const pathEndIdx = match && match.index || url.length; const droppedSlashIdx = pathEndIdx - (url[pathEndIdx - 1] === '/' ? 1 : 0); return url.slice(0, droppedSlashIdx) + url.slice(pathEndIdx); } /** * Normalizes URL parameters by prepending with `?` if needed. * * @param params String of URL parameters. * * @returns The normalized URL parameters string. */ function normalizeQueryParams(params) { return params && params[0] !== '?' ? '?' + params : params; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Enables the `Location` service to read route state from the browser's URL. * Angular provides two strategies: * `HashLocationStrategy` and `PathLocationStrategy`. * * Applications should use the `Router` or `Location` services to * interact with application route state. * * For instance, `HashLocationStrategy` produces URLs like * http://example.com#/foo, * and `PathLocationStrategy` produces * http://example.com/foo as an equivalent URL. * * See these two classes for more. * * @publicApi */ class LocationStrategy { historyGo(relativePosition) { throw new Error('Not implemented'); } } LocationStrategy.ɵfac = function LocationStrategy_Factory(t) { return new (t || LocationStrategy)(); }; LocationStrategy.ɵprov = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"])({ factory: provideLocationStrategy, token: LocationStrategy, providedIn: "root" }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](LocationStrategy, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Injectable, args: [{ providedIn: 'root', useFactory: provideLocationStrategy }] }], null, null); })(); function provideLocationStrategy(platformLocation) { // See #23917 const location = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(DOCUMENT).location; return new PathLocationStrategy((0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(PlatformLocation), location && location.origin || ''); } /** * A predefined [DI token](guide/glossary#di-token) for the base href * to be used with the `PathLocationStrategy`. * The base href is the URL prefix that should be preserved when generating * and recognizing URLs. * * @usageNotes * * The following example shows how to use this token to configure the root app injector * with a base href value, so that the DI framework can supply the dependency anywhere in the app. * * ```typescript * import {Component, NgModule} from '@angular/core'; * import {APP_BASE_HREF} from '@angular/common'; * * @NgModule({ * providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}] * }) * class AppModule {} * ``` * * @publicApi */ const APP_BASE_HREF = new _angular_core__WEBPACK_IMPORTED_MODULE_0__.InjectionToken('appBaseHref'); /** * @description * A {@link LocationStrategy} used to configure the {@link Location} service to * represent its state in the * [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the * browser's URL. * * If you're using `PathLocationStrategy`, you must provide a {@link APP_BASE_HREF} * or add a `` element to the document. * * For instance, if you provide an `APP_BASE_HREF` of `'/my/app/'` and call * `location.go('/foo')`, the browser's URL will become * `example.com/my/app/foo`. To ensure all relative URIs resolve correctly, * the `` and/or `APP_BASE_HREF` should end with a `/`. * * Similarly, if you add `` to the document and call * `location.go('/foo')`, the browser's URL will become * `example.com/my/app/foo`. * * Note that when using `PathLocationStrategy`, neither the query nor * the fragment in the `` will be preserved, as outlined * by the [RFC](https://tools.ietf.org/html/rfc3986#section-5.2.2). * * @usageNotes * * ### Example * * {@example common/location/ts/path_location_component.ts region='LocationComponent'} * * @publicApi */ class PathLocationStrategy extends LocationStrategy { constructor(_platformLocation, href) { super(); this._platformLocation = _platformLocation; this._removeListenerFns = []; if (href == null) { href = this._platformLocation.getBaseHrefFromDOM(); } if (href == null) { throw new Error(`No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.`); } this._baseHref = href; } ngOnDestroy() { while (this._removeListenerFns.length) { this._removeListenerFns.pop()(); } } onPopState(fn) { this._removeListenerFns.push(this._platformLocation.onPopState(fn), this._platformLocation.onHashChange(fn)); } getBaseHref() { return this._baseHref; } prepareExternalUrl(internal) { return joinWithSlash(this._baseHref, internal); } path(includeHash = false) { const pathname = this._platformLocation.pathname + normalizeQueryParams(this._platformLocation.search); const hash = this._platformLocation.hash; return hash && includeHash ? `${pathname}${hash}` : pathname; } pushState(state, title, url, queryParams) { const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams)); this._platformLocation.pushState(state, title, externalUrl); } replaceState(state, title, url, queryParams) { const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams)); this._platformLocation.replaceState(state, title, externalUrl); } forward() { this._platformLocation.forward(); } back() { this._platformLocation.back(); } historyGo(relativePosition = 0) { var _a, _b; (_b = (_a = this._platformLocation).historyGo) === null || _b === void 0 ? void 0 : _b.call(_a, relativePosition); } } PathLocationStrategy.ɵfac = function PathLocationStrategy_Factory(t) { return new (t || PathLocationStrategy)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](PlatformLocation), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](APP_BASE_HREF, 8)); }; PathLocationStrategy.ɵprov = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({ token: PathLocationStrategy, factory: PathLocationStrategy.ɵfac }); PathLocationStrategy.ctorParameters = () => [ { type: PlatformLocation }, { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Optional }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [APP_BASE_HREF,] }] } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](PathLocationStrategy, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Injectable }], function () { return [{ type: PlatformLocation }, { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Optional }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [APP_BASE_HREF] }] }]; }, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @description * A {@link LocationStrategy} used to configure the {@link Location} service to * represent its state in the * [hash fragment](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) * of the browser's URL. * * For instance, if you call `location.go('/foo')`, the browser's URL will become * `example.com#/foo`. * * @usageNotes * * ### Example * * {@example common/location/ts/hash_location_component.ts region='LocationComponent'} * * @publicApi */ class HashLocationStrategy extends LocationStrategy { constructor(_platformLocation, _baseHref) { super(); this._platformLocation = _platformLocation; this._baseHref = ''; this._removeListenerFns = []; if (_baseHref != null) { this._baseHref = _baseHref; } } ngOnDestroy() { while (this._removeListenerFns.length) { this._removeListenerFns.pop()(); } } onPopState(fn) { this._removeListenerFns.push(this._platformLocation.onPopState(fn), this._platformLocation.onHashChange(fn)); } getBaseHref() { return this._baseHref; } path(includeHash = false) { // the hash value is always prefixed with a `#` // and if it is empty then it will stay empty let path = this._platformLocation.hash; if (path == null) path = '#'; return path.length > 0 ? path.substring(1) : path; } prepareExternalUrl(internal) { const url = joinWithSlash(this._baseHref, internal); return url.length > 0 ? ('#' + url) : url; } pushState(state, title, path, queryParams) { let url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams)); if (url.length == 0) { url = this._platformLocation.pathname; } this._platformLocation.pushState(state, title, url); } replaceState(state, title, path, queryParams) { let url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams)); if (url.length == 0) { url = this._platformLocation.pathname; } this._platformLocation.replaceState(state, title, url); } forward() { this._platformLocation.forward(); } back() { this._platformLocation.back(); } historyGo(relativePosition = 0) { var _a, _b; (_b = (_a = this._platformLocation).historyGo) === null || _b === void 0 ? void 0 : _b.call(_a, relativePosition); } } HashLocationStrategy.ɵfac = function HashLocationStrategy_Factory(t) { return new (t || HashLocationStrategy)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](PlatformLocation), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](APP_BASE_HREF, 8)); }; HashLocationStrategy.ɵprov = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({ token: HashLocationStrategy, factory: HashLocationStrategy.ɵfac }); HashLocationStrategy.ctorParameters = () => [ { type: PlatformLocation }, { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Optional }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [APP_BASE_HREF,] }] } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](HashLocationStrategy, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Injectable }], function () { return [{ type: PlatformLocation }, { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Optional }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [APP_BASE_HREF] }] }]; }, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @description * * A service that applications can use to interact with a browser's URL. * * Depending on the `LocationStrategy` used, `Location` persists * to the URL's path or the URL's hash segment. * * @usageNotes * * It's better to use the `Router.navigate()` service to trigger route changes. Use * `Location` only if you need to interact with or create normalized URLs outside of * routing. * * `Location` is responsible for normalizing the URL against the application's base href. * A normalized URL is absolute from the URL host, includes the application's base href, and has no * trailing slash: * - `/my/app/user/123` is normalized * - `my/app/user/123` **is not** normalized * - `/my/app/user/123/` **is not** normalized * * ### Example * * * * @publicApi */ class Location { constructor(platformStrategy, platformLocation) { /** @internal */ this._subject = new _angular_core__WEBPACK_IMPORTED_MODULE_0__.EventEmitter(); /** @internal */ this._urlChangeListeners = []; this._platformStrategy = platformStrategy; const browserBaseHref = this._platformStrategy.getBaseHref(); this._platformLocation = platformLocation; this._baseHref = stripTrailingSlash(_stripIndexHtml(browserBaseHref)); this._platformStrategy.onPopState((ev) => { this._subject.emit({ 'url': this.path(true), 'pop': true, 'state': ev.state, 'type': ev.type, }); }); } /** * Normalizes the URL path for this location. * * @param includeHash True to include an anchor fragment in the path. * * @returns The normalized URL path. */ // TODO: vsavkin. Remove the boolean flag and always include hash once the deprecated router is // removed. path(includeHash = false) { return this.normalize(this._platformStrategy.path(includeHash)); } /** * Reports the current state of the location history. * @returns The current value of the `history.state` object. */ getState() { return this._platformLocation.getState(); } /** * Normalizes the given path and compares to the current normalized path. * * @param path The given URL path. * @param query Query parameters. * * @returns True if the given URL path is equal to the current normalized path, false * otherwise. */ isCurrentPathEqualTo(path, query = '') { return this.path() == this.normalize(path + normalizeQueryParams(query)); } /** * Normalizes a URL path by stripping any trailing slashes. * * @param url String representing a URL. * * @returns The normalized URL string. */ normalize(url) { return Location.stripTrailingSlash(_stripBaseHref(this._baseHref, _stripIndexHtml(url))); } /** * Normalizes an external URL path. * If the given URL doesn't begin with a leading slash (`'/'`), adds one * before normalizing. Adds a hash if `HashLocationStrategy` is * in use, or the `APP_BASE_HREF` if the `PathLocationStrategy` is in use. * * @param url String representing a URL. * * @returns A normalized platform-specific URL. */ prepareExternalUrl(url) { if (url && url[0] !== '/') { url = '/' + url; } return this._platformStrategy.prepareExternalUrl(url); } // TODO: rename this method to pushState /** * Changes the browser's URL to a normalized version of a given URL, and pushes a * new item onto the platform's history. * * @param path URL path to normalize. * @param query Query parameters. * @param state Location history state. * */ go(path, query = '', state = null) { this._platformStrategy.pushState(state, '', path, query); this._notifyUrlChangeListeners(this.prepareExternalUrl(path + normalizeQueryParams(query)), state); } /** * Changes the browser's URL to a normalized version of the given URL, and replaces * the top item on the platform's history stack. * * @param path URL path to normalize. * @param query Query parameters. * @param state Location history state. */ replaceState(path, query = '', state = null) { this._platformStrategy.replaceState(state, '', path, query); this._notifyUrlChangeListeners(this.prepareExternalUrl(path + normalizeQueryParams(query)), state); } /** * Navigates forward in the platform's history. */ forward() { this._platformStrategy.forward(); } /** * Navigates back in the platform's history. */ back() { this._platformStrategy.back(); } /** * Navigate to a specific page from session history, identified by its relative position to the * current page. * * @param relativePosition Position of the target page in the history relative to the current * page. * A negative value moves backwards, a positive value moves forwards, e.g. `location.historyGo(2)` * moves forward two pages and `location.historyGo(-2)` moves back two pages. When we try to go * beyond what's stored in the history session, we stay in the current page. Same behaviour occurs * when `relativePosition` equals 0. * @see https://developer.mozilla.org/en-US/docs/Web/API/History_API#Moving_to_a_specific_point_in_history */ historyGo(relativePosition = 0) { var _a, _b; (_b = (_a = this._platformStrategy).historyGo) === null || _b === void 0 ? void 0 : _b.call(_a, relativePosition); } /** * Registers a URL change listener. Use to catch updates performed by the Angular * framework that are not detectible through "popstate" or "hashchange" events. * * @param fn The change handler function, which take a URL and a location history state. */ onUrlChange(fn) { this._urlChangeListeners.push(fn); if (!this._urlChangeSubscription) { this._urlChangeSubscription = this.subscribe(v => { this._notifyUrlChangeListeners(v.url, v.state); }); } } /** @internal */ _notifyUrlChangeListeners(url = '', state) { this._urlChangeListeners.forEach(fn => fn(url, state)); } /** * Subscribes to the platform's `popState` events. * * Note: `Location.go()` does not trigger the `popState` event in the browser. Use * `Location.onUrlChange()` to subscribe to URL changes instead. * * @param value Event that is triggered when the state history changes. * @param exception The exception to throw. * * @see [onpopstate](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate) * * @returns Subscribed events. */ subscribe(onNext, onThrow, onReturn) { return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn }); } } Location.ɵfac = function Location_Factory(t) { return new (t || Location)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](LocationStrategy), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](PlatformLocation)); }; /** * Normalizes URL parameters by prepending with `?` if needed. * * @param params String of URL parameters. * * @returns The normalized URL parameters string. */ Location.normalizeQueryParams = normalizeQueryParams; /** * Joins two parts of a URL with a slash if needed. * * @param start URL string * @param end URL string * * * @returns The joined URL string. */ Location.joinWithSlash = joinWithSlash; /** * Removes a trailing slash from a URL string if needed. * Looks for the first occurrence of either `#`, `?`, or the end of the * line as `/` characters and removes the trailing slash if one exists. * * @param url URL string. * * @returns The URL string, modified if needed. */ Location.stripTrailingSlash = stripTrailingSlash; Location.ɵprov = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"])({ factory: createLocation, token: Location, providedIn: "root" }); Location.ctorParameters = () => [ { type: LocationStrategy }, { type: PlatformLocation } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](Location, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Injectable, args: [{ providedIn: 'root', // See #23917 useFactory: createLocation }] }], function () { return [{ type: LocationStrategy }, { type: PlatformLocation }]; }, null); })(); function createLocation() { return new Location((0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(LocationStrategy), (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(PlatformLocation)); } function _stripBaseHref(baseHref, url) { return baseHref && url.startsWith(baseHref) ? url.substring(baseHref.length) : url; } function _stripIndexHtml(url) { return url.replace(/\/index.html$/, ''); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** @internal */ const CURRENCIES_EN = { 'ADP': [undefined, undefined, 0], 'AFN': [undefined, undefined, 0], 'ALL': [undefined, undefined, 0], 'AMD': [undefined, undefined, 2], 'AOA': [undefined, 'Kz'], 'ARS': [undefined, '$'], 'AUD': ['A$', '$'], 'BAM': [undefined, 'KM'], 'BBD': [undefined, '$'], 'BDT': [undefined, 'ą§³'], 'BHD': [undefined, undefined, 3], 'BIF': [undefined, undefined, 0], 'BMD': [undefined, '$'], 'BND': [undefined, '$'], 'BOB': [undefined, 'Bs'], 'BRL': ['R$'], 'BSD': [undefined, '$'], 'BWP': [undefined, 'P'], 'BYN': [undefined, 'р.', 2], 'BYR': [undefined, undefined, 0], 'BZD': [undefined, '$'], 'CAD': ['CA$', '$', 2], 'CHF': [undefined, undefined, 2], 'CLF': [undefined, undefined, 4], 'CLP': [undefined, '$', 0], 'CNY': ['CNĀ„', 'Ā„'], 'COP': [undefined, '$', 2], 'CRC': [undefined, 'ā‚”', 2], 'CUC': [undefined, '$'], 'CUP': [undefined, '$'], 'CZK': [undefined, 'Kč', 2], 'DJF': [undefined, undefined, 0], 'DKK': [undefined, 'kr', 2], 'DOP': [undefined, '$'], 'EGP': [undefined, 'EĀ£'], 'ESP': [undefined, 'ā‚§', 0], 'EUR': ['€'], 'FJD': [undefined, '$'], 'FKP': [undefined, 'Ā£'], 'GBP': ['Ā£'], 'GEL': [undefined, '₾'], 'GIP': [undefined, 'Ā£'], 'GNF': [undefined, 'FG', 0], 'GTQ': [undefined, 'Q'], 'GYD': [undefined, '$', 2], 'HKD': ['HK$', '$'], 'HNL': [undefined, 'L'], 'HRK': [undefined, 'kn'], 'HUF': [undefined, 'Ft', 2], 'IDR': [undefined, 'Rp', 2], 'ILS': ['₪'], 'INR': ['₹'], 'IQD': [undefined, undefined, 0], 'IRR': [undefined, undefined, 0], 'ISK': [undefined, 'kr', 0], 'ITL': [undefined, undefined, 0], 'JMD': [undefined, '$'], 'JOD': [undefined, undefined, 3], 'JPY': ['Ā„', undefined, 0], 'KHR': [undefined, 'įŸ›'], 'KMF': [undefined, 'CF', 0], 'KPW': [undefined, 'ā‚©', 0], 'KRW': ['ā‚©', undefined, 0], 'KWD': [undefined, undefined, 3], 'KYD': [undefined, '$'], 'KZT': [undefined, '₸'], 'LAK': [undefined, 'ā‚­', 0], 'LBP': [undefined, 'LĀ£', 0], 'LKR': [undefined, 'Rs'], 'LRD': [undefined, '$'], 'LTL': [undefined, 'Lt'], 'LUF': [undefined, undefined, 0], 'LVL': [undefined, 'Ls'], 'LYD': [undefined, undefined, 3], 'MGA': [undefined, 'Ar', 0], 'MGF': [undefined, undefined, 0], 'MMK': [undefined, 'K', 0], 'MNT': [undefined, 'ā‚®', 2], 'MRO': [undefined, undefined, 0], 'MUR': [undefined, 'Rs', 2], 'MXN': ['MX$', '$'], 'MYR': [undefined, 'RM'], 'NAD': [undefined, '$'], 'NGN': [undefined, '₦'], 'NIO': [undefined, 'C$'], 'NOK': [undefined, 'kr', 2], 'NPR': [undefined, 'Rs'], 'NZD': ['NZ$', '$'], 'OMR': [undefined, undefined, 3], 'PHP': [undefined, '₱'], 'PKR': [undefined, 'Rs', 2], 'PLN': [undefined, 'zł'], 'PYG': [undefined, '₲', 0], 'RON': [undefined, 'lei'], 'RSD': [undefined, undefined, 0], 'RUB': [undefined, '₽'], 'RUR': [undefined, 'р.'], 'RWF': [undefined, 'RF', 0], 'SBD': [undefined, '$'], 'SEK': [undefined, 'kr', 2], 'SGD': [undefined, '$'], 'SHP': [undefined, 'Ā£'], 'SLL': [undefined, undefined, 0], 'SOS': [undefined, undefined, 0], 'SRD': [undefined, '$'], 'SSP': [undefined, 'Ā£'], 'STD': [undefined, undefined, 0], 'STN': [undefined, 'Db'], 'SYP': [undefined, 'Ā£', 0], 'THB': [undefined, 'ąøæ'], 'TMM': [undefined, undefined, 0], 'TND': [undefined, undefined, 3], 'TOP': [undefined, 'T$'], 'TRL': [undefined, undefined, 0], 'TRY': [undefined, '₺'], 'TTD': [undefined, '$'], 'TWD': ['NT$', '$', 2], 'TZS': [undefined, undefined, 2], 'UAH': [undefined, 'ā‚“'], 'UGX': [undefined, undefined, 0], 'USD': ['$'], 'UYI': [undefined, undefined, 0], 'UYU': [undefined, '$'], 'UYW': [undefined, undefined, 4], 'UZS': [undefined, undefined, 2], 'VEF': [undefined, 'Bs', 2], 'VND': ['ā‚«', undefined, 0], 'VUV': [undefined, undefined, 0], 'XAF': ['FCFA', undefined, 0], 'XCD': ['EC$', '$'], 'XOF': ['CFA', undefined, 0], 'XPF': ['CFPF', undefined, 0], 'XXX': ['¤'], 'YER': [undefined, undefined, 0], 'ZAR': [undefined, 'R'], 'ZMK': [undefined, undefined, 0], 'ZMW': [undefined, 'ZK'], 'ZWD': [undefined, undefined, 0] }; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Format styles that can be used to represent numbers. * @see `getLocaleNumberFormat()`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ var NumberFormatStyle; (function (NumberFormatStyle) { NumberFormatStyle[NumberFormatStyle["Decimal"] = 0] = "Decimal"; NumberFormatStyle[NumberFormatStyle["Percent"] = 1] = "Percent"; NumberFormatStyle[NumberFormatStyle["Currency"] = 2] = "Currency"; NumberFormatStyle[NumberFormatStyle["Scientific"] = 3] = "Scientific"; })(NumberFormatStyle || (NumberFormatStyle = {})); /** * Plurality cases used for translating plurals to different languages. * * @see `NgPlural` * @see `NgPluralCase` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ var Plural; (function (Plural) { Plural[Plural["Zero"] = 0] = "Zero"; Plural[Plural["One"] = 1] = "One"; Plural[Plural["Two"] = 2] = "Two"; Plural[Plural["Few"] = 3] = "Few"; Plural[Plural["Many"] = 4] = "Many"; Plural[Plural["Other"] = 5] = "Other"; })(Plural || (Plural = {})); /** * Context-dependant translation forms for strings. * Typically the standalone version is for the nominative form of the word, * and the format version is used for the genitive case. * @see [CLDR website](http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles) * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ var FormStyle; (function (FormStyle) { FormStyle[FormStyle["Format"] = 0] = "Format"; FormStyle[FormStyle["Standalone"] = 1] = "Standalone"; })(FormStyle || (FormStyle = {})); /** * String widths available for translations. * The specific character widths are locale-specific. * Examples are given for the word "Sunday" in English. * * @publicApi */ var TranslationWidth; (function (TranslationWidth) { /** 1 character for `en-US`. For example: 'S' */ TranslationWidth[TranslationWidth["Narrow"] = 0] = "Narrow"; /** 3 characters for `en-US`. For example: 'Sun' */ TranslationWidth[TranslationWidth["Abbreviated"] = 1] = "Abbreviated"; /** Full length for `en-US`. For example: "Sunday" */ TranslationWidth[TranslationWidth["Wide"] = 2] = "Wide"; /** 2 characters for `en-US`, For example: "Su" */ TranslationWidth[TranslationWidth["Short"] = 3] = "Short"; })(TranslationWidth || (TranslationWidth = {})); /** * String widths available for date-time formats. * The specific character widths are locale-specific. * Examples are given for `en-US`. * * @see `getLocaleDateFormat()` * @see `getLocaleTimeFormat()` * @see `getLocaleDateTimeFormat()` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * @publicApi */ var FormatWidth; (function (FormatWidth) { /** * For `en-US`, 'M/d/yy, h:mm a'` * (Example: `6/15/15, 9:03 AM`) */ FormatWidth[FormatWidth["Short"] = 0] = "Short"; /** * For `en-US`, `'MMM d, y, h:mm:ss a'` * (Example: `Jun 15, 2015, 9:03:01 AM`) */ FormatWidth[FormatWidth["Medium"] = 1] = "Medium"; /** * For `en-US`, `'MMMM d, y, h:mm:ss a z'` * (Example: `June 15, 2015 at 9:03:01 AM GMT+1`) */ FormatWidth[FormatWidth["Long"] = 2] = "Long"; /** * For `en-US`, `'EEEE, MMMM d, y, h:mm:ss a zzzz'` * (Example: `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00`) */ FormatWidth[FormatWidth["Full"] = 3] = "Full"; })(FormatWidth || (FormatWidth = {})); /** * Symbols that can be used to replace placeholders in number patterns. * Examples are based on `en-US` values. * * @see `getLocaleNumberSymbol()` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ var NumberSymbol; (function (NumberSymbol) { /** * Decimal separator. * For `en-US`, the dot character. * Example: 2,345`.`67 */ NumberSymbol[NumberSymbol["Decimal"] = 0] = "Decimal"; /** * Grouping separator, typically for thousands. * For `en-US`, the comma character. * Example: 2`,`345.67 */ NumberSymbol[NumberSymbol["Group"] = 1] = "Group"; /** * List-item separator. * Example: "one, two, and three" */ NumberSymbol[NumberSymbol["List"] = 2] = "List"; /** * Sign for percentage (out of 100). * Example: 23.4% */ NumberSymbol[NumberSymbol["PercentSign"] = 3] = "PercentSign"; /** * Sign for positive numbers. * Example: +23 */ NumberSymbol[NumberSymbol["PlusSign"] = 4] = "PlusSign"; /** * Sign for negative numbers. * Example: -23 */ NumberSymbol[NumberSymbol["MinusSign"] = 5] = "MinusSign"; /** * Computer notation for exponential value (n times a power of 10). * Example: 1.2E3 */ NumberSymbol[NumberSymbol["Exponential"] = 6] = "Exponential"; /** * Human-readable format of exponential. * Example: 1.2x103 */ NumberSymbol[NumberSymbol["SuperscriptingExponent"] = 7] = "SuperscriptingExponent"; /** * Sign for permille (out of 1000). * Example: 23.4‰ */ NumberSymbol[NumberSymbol["PerMille"] = 8] = "PerMille"; /** * Infinity, can be used with plus and minus. * Example: āˆž, +āˆž, -āˆž */ NumberSymbol[NumberSymbol["Infinity"] = 9] = "Infinity"; /** * Not a number. * Example: NaN */ NumberSymbol[NumberSymbol["NaN"] = 10] = "NaN"; /** * Symbol used between time units. * Example: 10:52 */ NumberSymbol[NumberSymbol["TimeSeparator"] = 11] = "TimeSeparator"; /** * Decimal separator for currency values (fallback to `Decimal`). * Example: $2,345.67 */ NumberSymbol[NumberSymbol["CurrencyDecimal"] = 12] = "CurrencyDecimal"; /** * Group separator for currency values (fallback to `Group`). * Example: $2,345.67 */ NumberSymbol[NumberSymbol["CurrencyGroup"] = 13] = "CurrencyGroup"; })(NumberSymbol || (NumberSymbol = {})); /** * The value for each day of the week, based on the `en-US` locale * * @publicApi */ var WeekDay; (function (WeekDay) { WeekDay[WeekDay["Sunday"] = 0] = "Sunday"; WeekDay[WeekDay["Monday"] = 1] = "Monday"; WeekDay[WeekDay["Tuesday"] = 2] = "Tuesday"; WeekDay[WeekDay["Wednesday"] = 3] = "Wednesday"; WeekDay[WeekDay["Thursday"] = 4] = "Thursday"; WeekDay[WeekDay["Friday"] = 5] = "Friday"; WeekDay[WeekDay["Saturday"] = 6] = "Saturday"; })(WeekDay || (WeekDay = {})); /** * Retrieves the locale ID from the currently loaded locale. * The loaded locale could be, for example, a global one rather than a regional one. * @param locale A locale code, such as `fr-FR`. * @returns The locale code. For example, `fr`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleId(locale) { return (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale)[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].LocaleId]; } /** * Retrieves day period strings for the given locale. * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns An array of localized period strings. For example, `[AM, PM]` for `en-US`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleDayPeriods(locale, formStyle, width) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); const amPmData = [ data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DayPeriodsFormat], data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DayPeriodsStandalone] ]; const amPm = getLastDefinedValue(amPmData, formStyle); return getLastDefinedValue(amPm, width); } /** * Retrieves days of the week for the given locale, using the Gregorian calendar. * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns An array of localized name strings. * For example,`[Sunday, Monday, ... Saturday]` for `en-US`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleDayNames(locale, formStyle, width) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); const daysData = [data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DaysFormat], data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DaysStandalone]]; const days = getLastDefinedValue(daysData, formStyle); return getLastDefinedValue(days, width); } /** * Retrieves months of the year for the given locale, using the Gregorian calendar. * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns An array of localized name strings. * For example, `[January, February, ...]` for `en-US`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleMonthNames(locale, formStyle, width) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); const monthsData = [data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].MonthsFormat], data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].MonthsStandalone]]; const months = getLastDefinedValue(monthsData, formStyle); return getLastDefinedValue(months, width); } /** * Retrieves Gregorian-calendar eras for the given locale. * @param locale A locale code for the locale format rules to use. * @param width The required character width. * @returns An array of localized era strings. * For example, `[AD, BC]` for `en-US`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleEraNames(locale, width) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); const erasData = data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].Eras]; return getLastDefinedValue(erasData, width); } /** * Retrieves the first day of the week for the given locale. * * @param locale A locale code for the locale format rules to use. * @returns A day index number, using the 0-based week-day index for `en-US` * (Sunday = 0, Monday = 1, ...). * For example, for `fr-FR`, returns 1 to indicate that the first day is Monday. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleFirstDayOfWeek(locale) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].FirstDayOfWeek]; } /** * Range of week days that are considered the week-end for the given locale. * * @param locale A locale code for the locale format rules to use. * @returns The range of day values, `[startDay, endDay]`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleWeekEndRange(locale) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].WeekendRange]; } /** * Retrieves a localized date-value formating string. * * @param locale A locale code for the locale format rules to use. * @param width The format type. * @returns The localized formating string. * @see `FormatWidth` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleDateFormat(locale, width) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); return getLastDefinedValue(data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DateFormat], width); } /** * Retrieves a localized time-value formatting string. * * @param locale A locale code for the locale format rules to use. * @param width The format type. * @returns The localized formatting string. * @see `FormatWidth` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * @publicApi */ function getLocaleTimeFormat(locale, width) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); return getLastDefinedValue(data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].TimeFormat], width); } /** * Retrieves a localized date-time formatting string. * * @param locale A locale code for the locale format rules to use. * @param width The format type. * @returns The localized formatting string. * @see `FormatWidth` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleDateTimeFormat(locale, width) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); const dateTimeFormatData = data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].DateTimeFormat]; return getLastDefinedValue(dateTimeFormatData, width); } /** * Retrieves a localized number symbol that can be used to replace placeholders in number formats. * @param locale The locale code. * @param symbol The symbol to localize. * @returns The character for the localized symbol. * @see `NumberSymbol` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleNumberSymbol(locale, symbol) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); const res = data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].NumberSymbols][symbol]; if (typeof res === 'undefined') { if (symbol === NumberSymbol.CurrencyDecimal) { return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].NumberSymbols][NumberSymbol.Decimal]; } else if (symbol === NumberSymbol.CurrencyGroup) { return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].NumberSymbols][NumberSymbol.Group]; } } return res; } /** * Retrieves a number format for a given locale. * * Numbers are formatted using patterns, like `#,###.00`. For example, the pattern `#,###.00` * when used to format the number 12345.678 could result in "12'345,678". That would happen if the * grouping separator for your language is an apostrophe, and the decimal separator is a comma. * * Important: The characters `.` `,` `0` `#` (and others below) are special placeholders * that stand for the decimal separator, and so on, and are NOT real characters. * You must NOT "translate" the placeholders. For example, don't change `.` to `,` even though in * your language the decimal point is written with a comma. The symbols should be replaced by the * local equivalents, using the appropriate `NumberSymbol` for your language. * * Here are the special characters used in number patterns: * * | Symbol | Meaning | * |--------|---------| * | . | Replaced automatically by the character used for the decimal point. | * | , | Replaced by the "grouping" (thousands) separator. | * | 0 | Replaced by a digit (or zero if there aren't enough digits). | * | # | Replaced by a digit (or nothing if there aren't enough). | * | ¤ | Replaced by a currency symbol, such as $ or USD. | * | % | Marks a percent format. The % symbol may change position, but must be retained. | * | E | Marks a scientific format. The E symbol may change position, but must be retained. | * | ' | Special characters used as literal characters are quoted with ASCII single quotes. | * * @param locale A locale code for the locale format rules to use. * @param type The type of numeric value to be formatted (such as `Decimal` or `Currency`.) * @returns The localized format string. * @see `NumberFormatStyle` * @see [CLDR website](http://cldr.unicode.org/translation/number-patterns) * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleNumberFormat(locale, type) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].NumberFormats][type]; } /** * Retrieves the symbol used to represent the currency for the main country * corresponding to a given locale. For example, '$' for `en-US`. * * @param locale A locale code for the locale format rules to use. * @returns The localized symbol character, * or `null` if the main country cannot be determined. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleCurrencySymbol(locale) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].CurrencySymbol] || null; } /** * Retrieves the name of the currency for the main country corresponding * to a given locale. For example, 'US Dollar' for `en-US`. * @param locale A locale code for the locale format rules to use. * @returns The currency name, * or `null` if the main country cannot be determined. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleCurrencyName(locale) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].CurrencyName] || null; } /** * Retrieves the default currency code for the given locale. * * The default is defined as the first currency which is still in use. * * @param locale The code of the locale whose currency code we want. * @returns The code of the default currency for the given locale. * * @publicApi */ function getLocaleCurrencyCode(locale) { return (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵgetLocaleCurrencyCode"])(locale); } /** * Retrieves the currency values for a given locale. * @param locale A locale code for the locale format rules to use. * @returns The currency values. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) */ function getLocaleCurrencies(locale) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].Currencies]; } /** * @alias core/ɵgetLocalePluralCase * @publicApi */ const getLocalePluralCase = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵgetLocalePluralCase"]; function checkFullData(data) { if (!data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].ExtraData]) { throw new Error(`Missing extra locale data for the locale "${data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].LocaleId]}". Use "registerLocaleData" to load new data. See the "I18n guide" on angular.io to know more.`); } } /** * Retrieves locale-specific rules used to determine which day period to use * when more than one period is defined for a locale. * * There is a rule for each defined day period. The * first rule is applied to the first day period and so on. * Fall back to AM/PM when no rules are available. * * A rule can specify a period as time range, or as a single time value. * * This functionality is only available when you have loaded the full locale data. * See the ["I18n guide"](guide/i18n#i18n-pipes). * * @param locale A locale code for the locale format rules to use. * @returns The rules for the locale, a single time value or array of *from-time, to-time*, * or null if no periods are available. * * @see `getLocaleExtraDayPeriods()` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleExtraDayPeriodRules(locale) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); checkFullData(data); const rules = data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].ExtraData][2 /* ExtraDayPeriodsRules */] || []; return rules.map((rule) => { if (typeof rule === 'string') { return extractTime(rule); } return [extractTime(rule[0]), extractTime(rule[1])]; }); } /** * Retrieves locale-specific day periods, which indicate roughly how a day is broken up * in different languages. * For example, for `en-US`, periods are morning, noon, afternoon, evening, and midnight. * * This functionality is only available when you have loaded the full locale data. * See the ["I18n guide"](guide/i18n#i18n-pipes). * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns The translated day-period strings. * @see `getLocaleExtraDayPeriodRules()` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleExtraDayPeriods(locale, formStyle, width) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); checkFullData(data); const dayPeriodsData = [ data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].ExtraData][0 /* ExtraDayPeriodFormats */], data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].ExtraData][1 /* ExtraDayPeriodStandalone */] ]; const dayPeriods = getLastDefinedValue(dayPeriodsData, formStyle) || []; return getLastDefinedValue(dayPeriods, width) || []; } /** * Retrieves the writing direction of a specified locale * @param locale A locale code for the locale format rules to use. * @publicApi * @returns 'rtl' or 'ltr' * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) */ function getLocaleDirection(locale) { const data = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵfindLocaleData"])(locale); return data[_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵLocaleDataIndex"].Directionality]; } /** * Retrieves the first value that is defined in an array, going backwards from an index position. * * To avoid repeating the same data (as when the "format" and "standalone" forms are the same) * add the first value to the locale data arrays, and add other values only if they are different. * * @param data The data array to retrieve from. * @param index A 0-based index into the array to start from. * @returns The value immediately before the given index position. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLastDefinedValue(data, index) { for (let i = index; i > -1; i--) { if (typeof data[i] !== 'undefined') { return data[i]; } } throw new Error('Locale data API: locale data undefined'); } /** * Extracts the hours and minutes from a string like "15:45" */ function extractTime(time) { const [h, m] = time.split(':'); return { hours: +h, minutes: +m }; } /** * Retrieves the currency symbol for a given currency code. * * For example, for the default `en-US` locale, the code `USD` can * be represented by the narrow symbol `$` or the wide symbol `US$`. * * @param code The currency code. * @param format The format, `wide` or `narrow`. * @param locale A locale code for the locale format rules to use. * * @returns The symbol, or the currency code if no symbol is available. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getCurrencySymbol(code, format, locale = 'en') { const currency = getLocaleCurrencies(locale)[code] || CURRENCIES_EN[code] || []; const symbolNarrow = currency[1 /* SymbolNarrow */]; if (format === 'narrow' && typeof symbolNarrow === 'string') { return symbolNarrow; } return currency[0 /* Symbol */] || code; } // Most currencies have cents, that's why the default is 2 const DEFAULT_NB_OF_CURRENCY_DIGITS = 2; /** * Reports the number of decimal digits for a given currency. * The value depends upon the presence of cents in that particular currency. * * @param code The currency code. * @returns The number of decimal digits, typically 0 or 2. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getNumberOfCurrencyDigits(code) { let digits; const currency = CURRENCIES_EN[code]; if (currency) { digits = currency[2 /* NbOfDigits */]; } return typeof digits === 'number' ? digits : DEFAULT_NB_OF_CURRENCY_DIGITS; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const ISO8601_DATE_REGEX = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; // 1 2 3 4 5 6 7 8 9 10 11 const NAMED_FORMATS = {}; const DATE_FORMATS_SPLIT = /((?:[^BEGHLMOSWYZabcdhmswyz']+)|(?:'(?:[^']|'')*')|(?:G{1,5}|y{1,4}|Y{1,4}|M{1,5}|L{1,5}|w{1,2}|W{1}|d{1,2}|E{1,6}|c{1,6}|a{1,5}|b{1,5}|B{1,5}|h{1,2}|H{1,2}|m{1,2}|s{1,2}|S{1,3}|z{1,4}|Z{1,5}|O{1,4}))([\s\S]*)/; var ZoneWidth; (function (ZoneWidth) { ZoneWidth[ZoneWidth["Short"] = 0] = "Short"; ZoneWidth[ZoneWidth["ShortGMT"] = 1] = "ShortGMT"; ZoneWidth[ZoneWidth["Long"] = 2] = "Long"; ZoneWidth[ZoneWidth["Extended"] = 3] = "Extended"; })(ZoneWidth || (ZoneWidth = {})); var DateType; (function (DateType) { DateType[DateType["FullYear"] = 0] = "FullYear"; DateType[DateType["Month"] = 1] = "Month"; DateType[DateType["Date"] = 2] = "Date"; DateType[DateType["Hours"] = 3] = "Hours"; DateType[DateType["Minutes"] = 4] = "Minutes"; DateType[DateType["Seconds"] = 5] = "Seconds"; DateType[DateType["FractionalSeconds"] = 6] = "FractionalSeconds"; DateType[DateType["Day"] = 7] = "Day"; })(DateType || (DateType = {})); var TranslationType; (function (TranslationType) { TranslationType[TranslationType["DayPeriods"] = 0] = "DayPeriods"; TranslationType[TranslationType["Days"] = 1] = "Days"; TranslationType[TranslationType["Months"] = 2] = "Months"; TranslationType[TranslationType["Eras"] = 3] = "Eras"; })(TranslationType || (TranslationType = {})); /** * @ngModule CommonModule * @description * * Formats a date according to locale rules. * * @param value The date to format, as a Date, or a number (milliseconds since UTC epoch) * or an [ISO date-time string](https://www.w3.org/TR/NOTE-datetime). * @param format The date-time components to include. See `DatePipe` for details. * @param locale A locale code for the locale format rules to use. * @param timezone The time zone. A time zone offset from GMT (such as `'+0430'`), * or a standard UTC/GMT or continental US time zone abbreviation. * If not specified, uses host system settings. * * @returns The formatted date string. * * @see `DatePipe` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function formatDate(value, format, locale, timezone) { let date = toDate(value); const namedFormat = getNamedFormat(locale, format); format = namedFormat || format; let parts = []; let match; while (format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = parts.concat(match.slice(1)); const part = parts.pop(); if (!part) { break; } format = part; } else { parts.push(format); break; } } let dateTimezoneOffset = date.getTimezoneOffset(); if (timezone) { dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); date = convertTimezoneToLocal(date, timezone, true); } let text = ''; parts.forEach(value => { const dateFormatter = getDateFormatter(value); text += dateFormatter ? dateFormatter(date, locale, dateTimezoneOffset) : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\''); }); return text; } /** * Create a new Date object with the given date value, and the time set to midnight. * * We cannot use `new Date(year, month, date)` because it maps years between 0 and 99 to 1900-1999. * See: https://github.com/angular/angular/issues/40377 * * Note that this function returns a Date object whose time is midnight in the current locale's * timezone. In the future we might want to change this to be midnight in UTC, but this would be a * considerable breaking change. */ function createDate(year, month, date) { // The `newDate` is set to midnight (UTC) on January 1st 1970. // - In PST this will be December 31st 1969 at 4pm. // - In GMT this will be January 1st 1970 at 1am. // Note that they even have different years, dates and months! const newDate = new Date(0); // `setFullYear()` allows years like 0001 to be set correctly. This function does not // change the internal time of the date. // Consider calling `setFullYear(2019, 8, 20)` (September 20, 2019). // - In PST this will now be September 20, 2019 at 4pm // - In GMT this will now be September 20, 2019 at 1am newDate.setFullYear(year, month, date); // We want the final date to be at local midnight, so we reset the time. // - In PST this will now be September 20, 2019 at 12am // - In GMT this will now be September 20, 2019 at 12am newDate.setHours(0, 0, 0); return newDate; } function getNamedFormat(locale, format) { const localeId = getLocaleId(locale); NAMED_FORMATS[localeId] = NAMED_FORMATS[localeId] || {}; if (NAMED_FORMATS[localeId][format]) { return NAMED_FORMATS[localeId][format]; } let formatValue = ''; switch (format) { case 'shortDate': formatValue = getLocaleDateFormat(locale, FormatWidth.Short); break; case 'mediumDate': formatValue = getLocaleDateFormat(locale, FormatWidth.Medium); break; case 'longDate': formatValue = getLocaleDateFormat(locale, FormatWidth.Long); break; case 'fullDate': formatValue = getLocaleDateFormat(locale, FormatWidth.Full); break; case 'shortTime': formatValue = getLocaleTimeFormat(locale, FormatWidth.Short); break; case 'mediumTime': formatValue = getLocaleTimeFormat(locale, FormatWidth.Medium); break; case 'longTime': formatValue = getLocaleTimeFormat(locale, FormatWidth.Long); break; case 'fullTime': formatValue = getLocaleTimeFormat(locale, FormatWidth.Full); break; case 'short': const shortTime = getNamedFormat(locale, 'shortTime'); const shortDate = getNamedFormat(locale, 'shortDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Short), [shortTime, shortDate]); break; case 'medium': const mediumTime = getNamedFormat(locale, 'mediumTime'); const mediumDate = getNamedFormat(locale, 'mediumDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Medium), [mediumTime, mediumDate]); break; case 'long': const longTime = getNamedFormat(locale, 'longTime'); const longDate = getNamedFormat(locale, 'longDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Long), [longTime, longDate]); break; case 'full': const fullTime = getNamedFormat(locale, 'fullTime'); const fullDate = getNamedFormat(locale, 'fullDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Full), [fullTime, fullDate]); break; } if (formatValue) { NAMED_FORMATS[localeId][format] = formatValue; } return formatValue; } function formatDateTime(str, opt_values) { if (opt_values) { str = str.replace(/\{([^}]+)}/g, function (match, key) { return (opt_values != null && key in opt_values) ? opt_values[key] : match; }); } return str; } function padNumber(num, digits, minusSign = '-', trim, negWrap) { let neg = ''; if (num < 0 || (negWrap && num <= 0)) { if (negWrap) { num = -num + 1; } else { num = -num; neg = minusSign; } } let strNum = String(num); while (strNum.length < digits) { strNum = '0' + strNum; } if (trim) { strNum = strNum.substr(strNum.length - digits); } return neg + strNum; } function formatFractionalSeconds(milliseconds, digits) { const strMs = padNumber(milliseconds, 3); return strMs.substr(0, digits); } /** * Returns a date formatter that transforms a date into its locale digit representation */ function dateGetter(name, size, offset = 0, trim = false, negWrap = false) { return function (date, locale) { let part = getDatePart(name, date); if (offset > 0 || part > -offset) { part += offset; } if (name === DateType.Hours) { if (part === 0 && offset === -12) { part = 12; } } else if (name === DateType.FractionalSeconds) { return formatFractionalSeconds(part, size); } const localeMinus = getLocaleNumberSymbol(locale, NumberSymbol.MinusSign); return padNumber(part, size, localeMinus, trim, negWrap); }; } function getDatePart(part, date) { switch (part) { case DateType.FullYear: return date.getFullYear(); case DateType.Month: return date.getMonth(); case DateType.Date: return date.getDate(); case DateType.Hours: return date.getHours(); case DateType.Minutes: return date.getMinutes(); case DateType.Seconds: return date.getSeconds(); case DateType.FractionalSeconds: return date.getMilliseconds(); case DateType.Day: return date.getDay(); default: throw new Error(`Unknown DateType value "${part}".`); } } /** * Returns a date formatter that transforms a date into its locale string representation */ function dateStrGetter(name, width, form = FormStyle.Format, extended = false) { return function (date, locale) { return getDateTranslation(date, locale, name, width, form, extended); }; } /** * Returns the locale translation of a date for a given form, type and width */ function getDateTranslation(date, locale, name, width, form, extended) { switch (name) { case TranslationType.Months: return getLocaleMonthNames(locale, form, width)[date.getMonth()]; case TranslationType.Days: return getLocaleDayNames(locale, form, width)[date.getDay()]; case TranslationType.DayPeriods: const currentHours = date.getHours(); const currentMinutes = date.getMinutes(); if (extended) { const rules = getLocaleExtraDayPeriodRules(locale); const dayPeriods = getLocaleExtraDayPeriods(locale, form, width); const index = rules.findIndex(rule => { if (Array.isArray(rule)) { // morning, afternoon, evening, night const [from, to] = rule; const afterFrom = currentHours >= from.hours && currentMinutes >= from.minutes; const beforeTo = (currentHours < to.hours || (currentHours === to.hours && currentMinutes < to.minutes)); // We must account for normal rules that span a period during the day (e.g. 6am-9am) // where `from` is less (earlier) than `to`. But also rules that span midnight (e.g. // 10pm - 5am) where `from` is greater (later!) than `to`. // // In the first case the current time must be BOTH after `from` AND before `to` // (e.g. 8am is after 6am AND before 10am). // // In the second case the current time must be EITHER after `from` OR before `to` // (e.g. 4am is before 5am but not after 10pm; and 11pm is not before 5am but it is // after 10pm). if (from.hours < to.hours) { if (afterFrom && beforeTo) { return true; } } else if (afterFrom || beforeTo) { return true; } } else { // noon or midnight if (rule.hours === currentHours && rule.minutes === currentMinutes) { return true; } } return false; }); if (index !== -1) { return dayPeriods[index]; } } // if no rules for the day periods, we use am/pm by default return getLocaleDayPeriods(locale, form, width)[currentHours < 12 ? 0 : 1]; case TranslationType.Eras: return getLocaleEraNames(locale, width)[date.getFullYear() <= 0 ? 0 : 1]; default: // This default case is not needed by TypeScript compiler, as the switch is exhaustive. // However Closure Compiler does not understand that and reports an error in typed mode. // The `throw new Error` below works around the problem, and the unexpected: never variable // makes sure tsc still checks this code is unreachable. const unexpected = name; throw new Error(`unexpected translation type ${unexpected}`); } } /** * Returns a date formatter that transforms a date and an offset into a timezone with ISO8601 or * GMT format depending on the width (eg: short = +0430, short:GMT = GMT+4, long = GMT+04:30, * extended = +04:30) */ function timeZoneGetter(width) { return function (date, locale, offset) { const zone = -1 * offset; const minusSign = getLocaleNumberSymbol(locale, NumberSymbol.MinusSign); const hours = zone > 0 ? Math.floor(zone / 60) : Math.ceil(zone / 60); switch (width) { case ZoneWidth.Short: return ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) + padNumber(Math.abs(zone % 60), 2, minusSign); case ZoneWidth.ShortGMT: return 'GMT' + ((zone >= 0) ? '+' : '') + padNumber(hours, 1, minusSign); case ZoneWidth.Long: return 'GMT' + ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) + ':' + padNumber(Math.abs(zone % 60), 2, minusSign); case ZoneWidth.Extended: if (offset === 0) { return 'Z'; } else { return ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) + ':' + padNumber(Math.abs(zone % 60), 2, minusSign); } default: throw new Error(`Unknown zone width "${width}"`); } }; } const JANUARY = 0; const THURSDAY = 4; function getFirstThursdayOfYear(year) { const firstDayOfYear = createDate(year, JANUARY, 1).getDay(); return createDate(year, 0, 1 + ((firstDayOfYear <= THURSDAY) ? THURSDAY : THURSDAY + 7) - firstDayOfYear); } function getThursdayThisWeek(datetime) { return createDate(datetime.getFullYear(), datetime.getMonth(), datetime.getDate() + (THURSDAY - datetime.getDay())); } function weekGetter(size, monthBased = false) { return function (date, locale) { let result; if (monthBased) { const nbDaysBefore1stDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1).getDay() - 1; const today = date.getDate(); result = 1 + Math.floor((today + nbDaysBefore1stDayOfMonth) / 7); } else { const thisThurs = getThursdayThisWeek(date); // Some days of a year are part of next year according to ISO 8601. // Compute the firstThurs from the year of this week's Thursday const firstThurs = getFirstThursdayOfYear(thisThurs.getFullYear()); const diff = thisThurs.getTime() - firstThurs.getTime(); result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week } return padNumber(result, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign)); }; } /** * Returns a date formatter that provides the week-numbering year for the input date. */ function weekNumberingYearGetter(size, trim = false) { return function (date, locale) { const thisThurs = getThursdayThisWeek(date); const weekNumberingYear = thisThurs.getFullYear(); return padNumber(weekNumberingYear, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign), trim); }; } const DATE_FORMATS = {}; // Based on CLDR formats: // See complete list: http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table // See also explanations: http://cldr.unicode.org/translation/date-time // TODO(ocombe): support all missing cldr formats: U, Q, D, F, e, j, J, C, A, v, V, X, x function getDateFormatter(format) { if (DATE_FORMATS[format]) { return DATE_FORMATS[format]; } let formatter; switch (format) { // Era name (AD/BC) case 'G': case 'GG': case 'GGG': formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Abbreviated); break; case 'GGGG': formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Wide); break; case 'GGGGG': formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Narrow); break; // 1 digit representation of the year, e.g. (AD 1 => 1, AD 199 => 199) case 'y': formatter = dateGetter(DateType.FullYear, 1, 0, false, true); break; // 2 digit representation of the year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) case 'yy': formatter = dateGetter(DateType.FullYear, 2, 0, true, true); break; // 3 digit representation of the year, padded (000-999). (e.g. AD 2001 => 01, AD 2010 => 10) case 'yyy': formatter = dateGetter(DateType.FullYear, 3, 0, false, true); break; // 4 digit representation of the year (e.g. AD 1 => 0001, AD 2010 => 2010) case 'yyyy': formatter = dateGetter(DateType.FullYear, 4, 0, false, true); break; // 1 digit representation of the week-numbering year, e.g. (AD 1 => 1, AD 199 => 199) case 'Y': formatter = weekNumberingYearGetter(1); break; // 2 digit representation of the week-numbering year, padded (00-99). (e.g. AD 2001 => 01, AD // 2010 => 10) case 'YY': formatter = weekNumberingYearGetter(2, true); break; // 3 digit representation of the week-numbering year, padded (000-999). (e.g. AD 1 => 001, AD // 2010 => 2010) case 'YYY': formatter = weekNumberingYearGetter(3); break; // 4 digit representation of the week-numbering year (e.g. AD 1 => 0001, AD 2010 => 2010) case 'YYYY': formatter = weekNumberingYearGetter(4); break; // Month of the year (1-12), numeric case 'M': case 'L': formatter = dateGetter(DateType.Month, 1, 1); break; case 'MM': case 'LL': formatter = dateGetter(DateType.Month, 2, 1); break; // Month of the year (January, ...), string, format case 'MMM': formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Abbreviated); break; case 'MMMM': formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Wide); break; case 'MMMMM': formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Narrow); break; // Month of the year (January, ...), string, standalone case 'LLL': formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Abbreviated, FormStyle.Standalone); break; case 'LLLL': formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Wide, FormStyle.Standalone); break; case 'LLLLL': formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Narrow, FormStyle.Standalone); break; // Week of the year (1, ... 52) case 'w': formatter = weekGetter(1); break; case 'ww': formatter = weekGetter(2); break; // Week of the month (1, ...) case 'W': formatter = weekGetter(1, true); break; // Day of the month (1-31) case 'd': formatter = dateGetter(DateType.Date, 1); break; case 'dd': formatter = dateGetter(DateType.Date, 2); break; // Day of the Week StandAlone (1, 1, Mon, Monday, M, Mo) case 'c': case 'cc': formatter = dateGetter(DateType.Day, 1); break; case 'ccc': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Abbreviated, FormStyle.Standalone); break; case 'cccc': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Wide, FormStyle.Standalone); break; case 'ccccc': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Narrow, FormStyle.Standalone); break; case 'cccccc': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Short, FormStyle.Standalone); break; // Day of the Week case 'E': case 'EE': case 'EEE': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Abbreviated); break; case 'EEEE': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Wide); break; case 'EEEEE': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Narrow); break; case 'EEEEEE': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Short); break; // Generic period of the day (am-pm) case 'a': case 'aa': case 'aaa': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated); break; case 'aaaa': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide); break; case 'aaaaa': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow); break; // Extended period of the day (midnight, at night, ...), standalone case 'b': case 'bb': case 'bbb': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated, FormStyle.Standalone, true); break; case 'bbbb': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide, FormStyle.Standalone, true); break; case 'bbbbb': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow, FormStyle.Standalone, true); break; // Extended period of the day (midnight, night, ...), standalone case 'B': case 'BB': case 'BBB': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated, FormStyle.Format, true); break; case 'BBBB': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide, FormStyle.Format, true); break; case 'BBBBB': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow, FormStyle.Format, true); break; // Hour in AM/PM, (1-12) case 'h': formatter = dateGetter(DateType.Hours, 1, -12); break; case 'hh': formatter = dateGetter(DateType.Hours, 2, -12); break; // Hour of the day (0-23) case 'H': formatter = dateGetter(DateType.Hours, 1); break; // Hour in day, padded (00-23) case 'HH': formatter = dateGetter(DateType.Hours, 2); break; // Minute of the hour (0-59) case 'm': formatter = dateGetter(DateType.Minutes, 1); break; case 'mm': formatter = dateGetter(DateType.Minutes, 2); break; // Second of the minute (0-59) case 's': formatter = dateGetter(DateType.Seconds, 1); break; case 'ss': formatter = dateGetter(DateType.Seconds, 2); break; // Fractional second case 'S': formatter = dateGetter(DateType.FractionalSeconds, 1); break; case 'SS': formatter = dateGetter(DateType.FractionalSeconds, 2); break; case 'SSS': formatter = dateGetter(DateType.FractionalSeconds, 3); break; // Timezone ISO8601 short format (-0430) case 'Z': case 'ZZ': case 'ZZZ': formatter = timeZoneGetter(ZoneWidth.Short); break; // Timezone ISO8601 extended format (-04:30) case 'ZZZZZ': formatter = timeZoneGetter(ZoneWidth.Extended); break; // Timezone GMT short format (GMT+4) case 'O': case 'OO': case 'OOO': // Should be location, but fallback to format O instead because we don't have the data yet case 'z': case 'zz': case 'zzz': formatter = timeZoneGetter(ZoneWidth.ShortGMT); break; // Timezone GMT long format (GMT+0430) case 'OOOO': case 'ZZZZ': // Should be location, but fallback to format O instead because we don't have the data yet case 'zzzz': formatter = timeZoneGetter(ZoneWidth.Long); break; default: return null; } DATE_FORMATS[format] = formatter; return formatter; } function timezoneToOffset(timezone, fallback) { // Support: IE 11 only, Edge 13-15+ // IE/Edge do not "understand" colon (`:`) in timezone timezone = timezone.replace(/:/g, ''); const requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000; return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset; } function addDateMinutes(date, minutes) { date = new Date(date.getTime()); date.setMinutes(date.getMinutes() + minutes); return date; } function convertTimezoneToLocal(date, timezone, reverse) { const reverseValue = reverse ? -1 : 1; const dateTimezoneOffset = date.getTimezoneOffset(); const timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); return addDateMinutes(date, reverseValue * (timezoneOffset - dateTimezoneOffset)); } /** * Converts a value to date. * * Supported input formats: * - `Date` * - number: timestamp * - string: numeric (e.g. "1234"), ISO and date strings in a format supported by * [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse). * Note: ISO strings without time return a date without timeoffset. * * Throws if unable to convert to a date. */ function toDate(value) { if (isDate(value)) { return value; } if (typeof value === 'number' && !isNaN(value)) { return new Date(value); } if (typeof value === 'string') { value = value.trim(); if (/^(\d{4}(-\d{1,2}(-\d{1,2})?)?)$/.test(value)) { /* For ISO Strings without time the day, month and year must be extracted from the ISO String before Date creation to avoid time offset and errors in the new Date. If we only replace '-' with ',' in the ISO String ("2015,01,01"), and try to create a new date, some browsers (e.g. IE 9) will throw an invalid Date error. If we leave the '-' ("2015-01-01") and try to create a new Date("2015-01-01") the timeoffset is applied. Note: ISO months are 0 for January, 1 for February, ... */ const [y, m = 1, d = 1] = value.split('-').map((val) => +val); return createDate(y, m - 1, d); } const parsedNb = parseFloat(value); // any string that only contains numbers, like "1234" but not like "1234hello" if (!isNaN(value - parsedNb)) { return new Date(parsedNb); } let match; if (match = value.match(ISO8601_DATE_REGEX)) { return isoStringToDate(match); } } const date = new Date(value); if (!isDate(date)) { throw new Error(`Unable to convert "${value}" into a date`); } return date; } /** * Converts a date in ISO8601 to a Date. * Used instead of `Date.parse` because of browser discrepancies. */ function isoStringToDate(match) { const date = new Date(0); let tzHour = 0; let tzMin = 0; // match[8] means that the string contains "Z" (UTC) or a timezone like "+01:00" or "+0100" const dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear; const timeSetter = match[8] ? date.setUTCHours : date.setHours; // if there is a timezone defined like "+01:00" or "+0100" if (match[9]) { tzHour = Number(match[9] + match[10]); tzMin = Number(match[9] + match[11]); } dateSetter.call(date, Number(match[1]), Number(match[2]) - 1, Number(match[3])); const h = Number(match[4] || 0) - tzHour; const m = Number(match[5] || 0) - tzMin; const s = Number(match[6] || 0); // The ECMAScript specification (https://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.11) // defines that `DateTime` milliseconds should always be rounded down, so that `999.9ms` // becomes `999ms`. const ms = Math.floor(parseFloat('0.' + (match[7] || 0)) * 1000); timeSetter.call(date, h, m, s, ms); return date; } function isDate(value) { return value instanceof Date && !isNaN(value.valueOf()); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/; const MAX_DIGITS = 22; const DECIMAL_SEP = '.'; const ZERO_CHAR = '0'; const PATTERN_SEP = ';'; const GROUP_SEP = ','; const DIGIT_CHAR = '#'; const CURRENCY_CHAR = '¤'; const PERCENT_CHAR = '%'; /** * Transforms a number to a locale string based on a style and a format. */ function formatNumberToLocaleString(value, pattern, locale, groupSymbol, decimalSymbol, digitsInfo, isPercent = false) { let formattedText = ''; let isZero = false; if (!isFinite(value)) { formattedText = getLocaleNumberSymbol(locale, NumberSymbol.Infinity); } else { let parsedNumber = parseNumber(value); if (isPercent) { parsedNumber = toPercent(parsedNumber); } let minInt = pattern.minInt; let minFraction = pattern.minFrac; let maxFraction = pattern.maxFrac; if (digitsInfo) { const parts = digitsInfo.match(NUMBER_FORMAT_REGEXP); if (parts === null) { throw new Error(`${digitsInfo} is not a valid digit info`); } const minIntPart = parts[1]; const minFractionPart = parts[3]; const maxFractionPart = parts[5]; if (minIntPart != null) { minInt = parseIntAutoRadix(minIntPart); } if (minFractionPart != null) { minFraction = parseIntAutoRadix(minFractionPart); } if (maxFractionPart != null) { maxFraction = parseIntAutoRadix(maxFractionPart); } else if (minFractionPart != null && minFraction > maxFraction) { maxFraction = minFraction; } } roundNumber(parsedNumber, minFraction, maxFraction); let digits = parsedNumber.digits; let integerLen = parsedNumber.integerLen; const exponent = parsedNumber.exponent; let decimals = []; isZero = digits.every(d => !d); // pad zeros for small numbers for (; integerLen < minInt; integerLen++) { digits.unshift(0); } // pad zeros for small numbers for (; integerLen < 0; integerLen++) { digits.unshift(0); } // extract decimals digits if (integerLen > 0) { decimals = digits.splice(integerLen, digits.length); } else { decimals = digits; digits = [0]; } // format the integer digits with grouping separators const groups = []; if (digits.length >= pattern.lgSize) { groups.unshift(digits.splice(-pattern.lgSize, digits.length).join('')); } while (digits.length > pattern.gSize) { groups.unshift(digits.splice(-pattern.gSize, digits.length).join('')); } if (digits.length) { groups.unshift(digits.join('')); } formattedText = groups.join(getLocaleNumberSymbol(locale, groupSymbol)); // append the decimal digits if (decimals.length) { formattedText += getLocaleNumberSymbol(locale, decimalSymbol) + decimals.join(''); } if (exponent) { formattedText += getLocaleNumberSymbol(locale, NumberSymbol.Exponential) + '+' + exponent; } } if (value < 0 && !isZero) { formattedText = pattern.negPre + formattedText + pattern.negSuf; } else { formattedText = pattern.posPre + formattedText + pattern.posSuf; } return formattedText; } /** * @ngModule CommonModule * @description * * Formats a number as currency using locale rules. * * @param value The number to format. * @param locale A locale code for the locale format rules to use. * @param currency A string containing the currency symbol or its name, * such as "$" or "Canadian Dollar". Used in output string, but does not affect the operation * of the function. * @param currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) * currency code, such as `USD` for the US dollar and `EUR` for the euro. * Used to determine the number of digits in the decimal part. * @param digitsInfo Decimal representation options, specified by a string in the following format: * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details. * * @returns The formatted currency value. * * @see `formatNumber()` * @see `DecimalPipe` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function formatCurrency(value, locale, currency, currencyCode, digitsInfo) { const format = getLocaleNumberFormat(locale, NumberFormatStyle.Currency); const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign)); pattern.minFrac = getNumberOfCurrencyDigits(currencyCode); pattern.maxFrac = pattern.minFrac; const res = formatNumberToLocaleString(value, pattern, locale, NumberSymbol.CurrencyGroup, NumberSymbol.CurrencyDecimal, digitsInfo); return res .replace(CURRENCY_CHAR, currency) // if we have 2 time the currency character, the second one is ignored .replace(CURRENCY_CHAR, '') // If there is a spacing between currency character and the value and // the currency character is supressed by passing an empty string, the // spacing character would remain as part of the string. Then we // should remove it. .trim(); } /** * @ngModule CommonModule * @description * * Formats a number as a percentage according to locale rules. * * @param value The number to format. * @param locale A locale code for the locale format rules to use. * @param digitsInfo Decimal representation options, specified by a string in the following format: * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details. * * @returns The formatted percentage value. * * @see `formatNumber()` * @see `DecimalPipe` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * @publicApi * */ function formatPercent(value, locale, digitsInfo) { const format = getLocaleNumberFormat(locale, NumberFormatStyle.Percent); const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign)); const res = formatNumberToLocaleString(value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo, true); return res.replace(new RegExp(PERCENT_CHAR, 'g'), getLocaleNumberSymbol(locale, NumberSymbol.PercentSign)); } /** * @ngModule CommonModule * @description * * Formats a number as text, with group sizing, separator, and other * parameters based on the locale. * * @param value The number to format. * @param locale A locale code for the locale format rules to use. * @param digitsInfo Decimal representation options, specified by a string in the following format: * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details. * * @returns The formatted text string. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function formatNumber(value, locale, digitsInfo) { const format = getLocaleNumberFormat(locale, NumberFormatStyle.Decimal); const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign)); return formatNumberToLocaleString(value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo); } function parseNumberFormat(format, minusSign = '-') { const p = { minInt: 1, minFrac: 0, maxFrac: 0, posPre: '', posSuf: '', negPre: '', negSuf: '', gSize: 0, lgSize: 0 }; const patternParts = format.split(PATTERN_SEP); const positive = patternParts[0]; const negative = patternParts[1]; const positiveParts = positive.indexOf(DECIMAL_SEP) !== -1 ? positive.split(DECIMAL_SEP) : [ positive.substring(0, positive.lastIndexOf(ZERO_CHAR) + 1), positive.substring(positive.lastIndexOf(ZERO_CHAR) + 1) ], integer = positiveParts[0], fraction = positiveParts[1] || ''; p.posPre = integer.substr(0, integer.indexOf(DIGIT_CHAR)); for (let i = 0; i < fraction.length; i++) { const ch = fraction.charAt(i); if (ch === ZERO_CHAR) { p.minFrac = p.maxFrac = i + 1; } else if (ch === DIGIT_CHAR) { p.maxFrac = i + 1; } else { p.posSuf += ch; } } const groups = integer.split(GROUP_SEP); p.gSize = groups[1] ? groups[1].length : 0; p.lgSize = (groups[2] || groups[1]) ? (groups[2] || groups[1]).length : 0; if (negative) { const trunkLen = positive.length - p.posPre.length - p.posSuf.length, pos = negative.indexOf(DIGIT_CHAR); p.negPre = negative.substr(0, pos).replace(/'/g, ''); p.negSuf = negative.substr(pos + trunkLen).replace(/'/g, ''); } else { p.negPre = minusSign + p.posPre; p.negSuf = p.posSuf; } return p; } // Transforms a parsed number into a percentage by multiplying it by 100 function toPercent(parsedNumber) { // if the number is 0, don't do anything if (parsedNumber.digits[0] === 0) { return parsedNumber; } // Getting the current number of decimals const fractionLen = parsedNumber.digits.length - parsedNumber.integerLen; if (parsedNumber.exponent) { parsedNumber.exponent += 2; } else { if (fractionLen === 0) { parsedNumber.digits.push(0, 0); } else if (fractionLen === 1) { parsedNumber.digits.push(0); } parsedNumber.integerLen += 2; } return parsedNumber; } /** * Parses a number. * Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/ */ function parseNumber(num) { let numStr = Math.abs(num) + ''; let exponent = 0, digits, integerLen; let i, j, zeros; // Decimal point? if ((integerLen = numStr.indexOf(DECIMAL_SEP)) > -1) { numStr = numStr.replace(DECIMAL_SEP, ''); } // Exponential form? if ((i = numStr.search(/e/i)) > 0) { // Work out the exponent. if (integerLen < 0) integerLen = i; integerLen += +numStr.slice(i + 1); numStr = numStr.substring(0, i); } else if (integerLen < 0) { // There was no decimal point or exponent so it is an integer. integerLen = numStr.length; } // Count the number of leading zeros. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ } if (i === (zeros = numStr.length)) { // The digits are all zero. digits = [0]; integerLen = 1; } else { // Count the number of trailing zeros zeros--; while (numStr.charAt(zeros) === ZERO_CHAR) zeros--; // Trailing zeros are insignificant so ignore them integerLen -= i; digits = []; // Convert string to array of digits without leading/trailing zeros. for (j = 0; i <= zeros; i++, j++) { digits[j] = Number(numStr.charAt(i)); } } // If the number overflows the maximum allowed digits then use an exponent. if (integerLen > MAX_DIGITS) { digits = digits.splice(0, MAX_DIGITS - 1); exponent = integerLen - 1; integerLen = 1; } return { digits, exponent, integerLen }; } /** * Round the parsed number to the specified number of decimal places * This function changes the parsedNumber in-place */ function roundNumber(parsedNumber, minFrac, maxFrac) { if (minFrac > maxFrac) { throw new Error(`The minimum number of digits after fraction (${minFrac}) is higher than the maximum (${maxFrac}).`); } let digits = parsedNumber.digits; let fractionLen = digits.length - parsedNumber.integerLen; const fractionSize = Math.min(Math.max(minFrac, fractionLen), maxFrac); // The index of the digit to where rounding is to occur let roundAt = fractionSize + parsedNumber.integerLen; let digit = digits[roundAt]; if (roundAt > 0) { // Drop fractional digits beyond `roundAt` digits.splice(Math.max(parsedNumber.integerLen, roundAt)); // Set non-fractional digits beyond `roundAt` to 0 for (let j = roundAt; j < digits.length; j++) { digits[j] = 0; } } else { // We rounded to zero so reset the parsedNumber fractionLen = Math.max(0, fractionLen); parsedNumber.integerLen = 1; digits.length = Math.max(1, roundAt = fractionSize + 1); digits[0] = 0; for (let i = 1; i < roundAt; i++) digits[i] = 0; } if (digit >= 5) { if (roundAt - 1 < 0) { for (let k = 0; k > roundAt; k--) { digits.unshift(0); parsedNumber.integerLen++; } digits.unshift(1); parsedNumber.integerLen++; } else { digits[roundAt - 1]++; } } // Pad out with zeros to get the required fraction length for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); let dropTrailingZeros = fractionSize !== 0; // Minimal length = nb of decimals required + current nb of integers // Any number besides that is optional and can be removed if it's a trailing 0 const minLen = minFrac + parsedNumber.integerLen; // Do any carrying, e.g. a digit was rounded up to 10 const carry = digits.reduceRight(function (carry, d, i, digits) { d = d + carry; digits[i] = d < 10 ? d : d - 10; // d % 10 if (dropTrailingZeros) { // Do not keep meaningless fractional trailing zeros (e.g. 15.52000 --> 15.52) if (digits[i] === 0 && i >= minLen) { digits.pop(); } else { dropTrailingZeros = false; } } return d >= 10 ? 1 : 0; // Math.floor(d / 10); }, 0); if (carry) { digits.unshift(carry); parsedNumber.integerLen++; } } function parseIntAutoRadix(text) { const result = parseInt(text); if (isNaN(result)) { throw new Error('Invalid integer literal when parsing ' + text); } return result; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @publicApi */ class NgLocalization { } /** * Returns the plural category for a given value. * - "=value" when the case exists, * - the plural category otherwise */ function getPluralCategory(value, cases, ngLocalization, locale) { let key = `=${value}`; if (cases.indexOf(key) > -1) { return key; } key = ngLocalization.getPluralCategory(value, locale); if (cases.indexOf(key) > -1) { return key; } if (cases.indexOf('other') > -1) { return 'other'; } throw new Error(`No plural message found for value "${value}"`); } /** * Returns the plural case based on the locale * * @publicApi */ class NgLocaleLocalization extends NgLocalization { constructor(locale) { super(); this.locale = locale; } getPluralCategory(value, locale) { const plural = getLocalePluralCase(locale || this.locale)(value); switch (plural) { case Plural.Zero: return 'zero'; case Plural.One: return 'one'; case Plural.Two: return 'two'; case Plural.Few: return 'few'; case Plural.Many: return 'many'; default: return 'other'; } } } NgLocaleLocalization.ɵfac = function NgLocaleLocalization_Factory(t) { return new (t || NgLocaleLocalization)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID)); }; NgLocaleLocalization.ɵprov = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({ token: NgLocaleLocalization, factory: NgLocaleLocalization.ɵfac }); NgLocaleLocalization.ctorParameters = () => [ { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID,] }] } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgLocaleLocalization, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Injectable }], function () { return [{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID] }] }]; }, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Register global data to be used internally by Angular. See the * ["I18n guide"](guide/i18n#i18n-pipes) to know how to import additional locale data. * * The signature registerLocaleData(data: any, extraData?: any) is deprecated since v5.1 * * @publicApi */ function registerLocaleData(data, localeId, extraData) { return (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵregisterLocaleData"])(data, localeId, extraData); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function parseCookieValue(cookieStr, name) { name = encodeURIComponent(name); for (const cookie of cookieStr.split(';')) { const eqIndex = cookie.indexOf('='); const [cookieName, cookieValue] = eqIndex == -1 ? [cookie, ''] : [cookie.slice(0, eqIndex), cookie.slice(eqIndex + 1)]; if (cookieName.trim() === name) { return decodeURIComponent(cookieValue); } } return null; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * * @usageNotes * ``` * ... * * ... * * ... * * ... * * ... * ``` * * @description * * Adds and removes CSS classes on an HTML element. * * The CSS classes are updated as follows, depending on the type of the expression evaluation: * - `string` - the CSS classes listed in the string (space delimited) are added, * - `Array` - the CSS classes declared as Array elements are added, * - `Object` - keys are CSS classes that get added when the expression given in the value * evaluates to a truthy value, otherwise they are removed. * * @publicApi */ class NgClass { constructor(_iterableDiffers, _keyValueDiffers, _ngEl, _renderer) { this._iterableDiffers = _iterableDiffers; this._keyValueDiffers = _keyValueDiffers; this._ngEl = _ngEl; this._renderer = _renderer; this._iterableDiffer = null; this._keyValueDiffer = null; this._initialClasses = []; this._rawClass = null; } set klass(value) { this._removeClasses(this._initialClasses); this._initialClasses = typeof value === 'string' ? value.split(/\s+/) : []; this._applyClasses(this._initialClasses); this._applyClasses(this._rawClass); } set ngClass(value) { this._removeClasses(this._rawClass); this._applyClasses(this._initialClasses); this._iterableDiffer = null; this._keyValueDiffer = null; this._rawClass = typeof value === 'string' ? value.split(/\s+/) : value; if (this._rawClass) { if ((0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵisListLikeIterable"])(this._rawClass)) { this._iterableDiffer = this._iterableDiffers.find(this._rawClass).create(); } else { this._keyValueDiffer = this._keyValueDiffers.find(this._rawClass).create(); } } } ngDoCheck() { if (this._iterableDiffer) { const iterableChanges = this._iterableDiffer.diff(this._rawClass); if (iterableChanges) { this._applyIterableChanges(iterableChanges); } } else if (this._keyValueDiffer) { const keyValueChanges = this._keyValueDiffer.diff(this._rawClass); if (keyValueChanges) { this._applyKeyValueChanges(keyValueChanges); } } } _applyKeyValueChanges(changes) { changes.forEachAddedItem((record) => this._toggleClass(record.key, record.currentValue)); changes.forEachChangedItem((record) => this._toggleClass(record.key, record.currentValue)); changes.forEachRemovedItem((record) => { if (record.previousValue) { this._toggleClass(record.key, false); } }); } _applyIterableChanges(changes) { changes.forEachAddedItem((record) => { if (typeof record.item === 'string') { this._toggleClass(record.item, true); } else { throw new Error(`NgClass can only toggle CSS classes expressed as strings, got ${(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵstringify"])(record.item)}`); } }); changes.forEachRemovedItem((record) => this._toggleClass(record.item, false)); } /** * Applies a collection of CSS classes to the DOM element. * * For argument of type Set and Array CSS class names contained in those collections are always * added. * For argument of type Map CSS class name in the map's key is toggled based on the value (added * for truthy and removed for falsy). */ _applyClasses(rawClassVal) { if (rawClassVal) { if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) { rawClassVal.forEach((klass) => this._toggleClass(klass, true)); } else { Object.keys(rawClassVal).forEach(klass => this._toggleClass(klass, !!rawClassVal[klass])); } } } /** * Removes a collection of CSS classes from the DOM element. This is mostly useful for cleanup * purposes. */ _removeClasses(rawClassVal) { if (rawClassVal) { if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) { rawClassVal.forEach((klass) => this._toggleClass(klass, false)); } else { Object.keys(rawClassVal).forEach(klass => this._toggleClass(klass, false)); } } } _toggleClass(klass, enabled) { klass = klass.trim(); if (klass) { klass.split(/\s+/g).forEach(klass => { if (enabled) { this._renderer.addClass(this._ngEl.nativeElement, klass); } else { this._renderer.removeClass(this._ngEl.nativeElement, klass); } }); } } } NgClass.ɵfac = function NgClass_Factory(t) { return new (t || NgClass)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.IterableDiffers), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.KeyValueDiffers), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ElementRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.Renderer2)); }; NgClass.ɵdir = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgClass, selectors: [["", "ngClass", ""]], inputs: { klass: ["class", "klass"], ngClass: "ngClass" } }); NgClass.ctorParameters = () => [ { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.IterableDiffers }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.KeyValueDiffers }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ElementRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Renderer2 } ]; NgClass.propDecorators = { klass: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input, args: ['class',] }], ngClass: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input, args: ['ngClass',] }] }; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgClass, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Directive, args: [{ selector: '[ngClass]' }] }], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.IterableDiffers }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.KeyValueDiffers }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ElementRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Renderer2 }]; }, { klass: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input, args: ['class'] }], ngClass: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input, args: ['ngClass'] }] }); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Instantiates a single {@link Component} type and inserts its Host View into current View. * `NgComponentOutlet` provides a declarative approach for dynamic component creation. * * `NgComponentOutlet` requires a component type, if a falsy value is set the view will clear and * any existing component will get destroyed. * * @usageNotes * * ### Fine tune control * * You can control the component creation process by using the following optional attributes: * * * `ngComponentOutletInjector`: Optional custom {@link Injector} that will be used as parent for * the Component. Defaults to the injector of the current view container. * * * `ngComponentOutletContent`: Optional list of projectable nodes to insert into the content * section of the component, if exists. * * * `ngComponentOutletNgModuleFactory`: Optional module factory to allow dynamically loading other * module, then load a component from that module. * * ### Syntax * * Simple * ``` * * ``` * * Customized injector/content * ``` * * * ``` * * Customized ngModuleFactory * ``` * * * ``` * * ### A simple example * * {@example common/ngComponentOutlet/ts/module.ts region='SimpleExample'} * * A more complete example with additional options: * * {@example common/ngComponentOutlet/ts/module.ts region='CompleteExample'} * * @publicApi * @ngModule CommonModule */ class NgComponentOutlet { constructor(_viewContainerRef) { this._viewContainerRef = _viewContainerRef; this._componentRef = null; this._moduleRef = null; } ngOnChanges(changes) { this._viewContainerRef.clear(); this._componentRef = null; if (this.ngComponentOutlet) { const elInjector = this.ngComponentOutletInjector || this._viewContainerRef.parentInjector; if (changes['ngComponentOutletNgModuleFactory']) { if (this._moduleRef) this._moduleRef.destroy(); if (this.ngComponentOutletNgModuleFactory) { const parentModule = elInjector.get(_angular_core__WEBPACK_IMPORTED_MODULE_0__.NgModuleRef); this._moduleRef = this.ngComponentOutletNgModuleFactory.create(parentModule.injector); } else { this._moduleRef = null; } } const componentFactoryResolver = this._moduleRef ? this._moduleRef.componentFactoryResolver : elInjector.get(_angular_core__WEBPACK_IMPORTED_MODULE_0__.ComponentFactoryResolver); const componentFactory = componentFactoryResolver.resolveComponentFactory(this.ngComponentOutlet); this._componentRef = this._viewContainerRef.createComponent(componentFactory, this._viewContainerRef.length, elInjector, this.ngComponentOutletContent); } } ngOnDestroy() { if (this._moduleRef) this._moduleRef.destroy(); } } NgComponentOutlet.ɵfac = function NgComponentOutlet_Factory(t) { return new (t || NgComponentOutlet)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef)); }; NgComponentOutlet.ɵdir = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgComponentOutlet, selectors: [["", "ngComponentOutlet", ""]], inputs: { ngComponentOutlet: "ngComponentOutlet", ngComponentOutletInjector: "ngComponentOutletInjector", ngComponentOutletContent: "ngComponentOutletContent", ngComponentOutletNgModuleFactory: "ngComponentOutletNgModuleFactory" }, features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵNgOnChangesFeature"]] }); NgComponentOutlet.ctorParameters = () => [ { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef } ]; NgComponentOutlet.propDecorators = { ngComponentOutlet: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngComponentOutletInjector: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngComponentOutletContent: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngComponentOutletNgModuleFactory: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgComponentOutlet, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Directive, args: [{ selector: '[ngComponentOutlet]' }] }], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }]; }, { ngComponentOutlet: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngComponentOutletInjector: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngComponentOutletContent: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngComponentOutletNgModuleFactory: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @publicApi */ class NgForOfContext { constructor($implicit, ngForOf, index, count) { this.$implicit = $implicit; this.ngForOf = ngForOf; this.index = index; this.count = count; } get first() { return this.index === 0; } get last() { return this.index === this.count - 1; } get even() { return this.index % 2 === 0; } get odd() { return !this.even; } } /** * A [structural directive](guide/structural-directives) that renders * a template for each item in a collection. * The directive is placed on an element, which becomes the parent * of the cloned templates. * * The `ngForOf` directive is generally used in the * [shorthand form](guide/structural-directives#asterisk) `*ngFor`. * In this form, the template to be rendered for each iteration is the content * of an anchor element containing the directive. * * The following example shows the shorthand syntax with some options, * contained in an `
  • ` element. * * ``` *
  • ...
  • * ``` * * The shorthand form expands into a long form that uses the `ngForOf` selector * on an `` element. * The content of the `` element is the `
  • ` element that held the * short-form directive. * * Here is the expanded version of the short-form example. * * ``` * *
  • ...
  • *
    * ``` * * Angular automatically expands the shorthand syntax as it compiles the template. * The context for each embedded view is logically merged to the current component * context according to its lexical position. * * When using the shorthand syntax, Angular allows only [one structural directive * on an element](guide/built-in-directives#one-per-element). * If you want to iterate conditionally, for example, * put the `*ngIf` on a container element that wraps the `*ngFor` element. * For futher discussion, see * [Structural Directives](guide/built-in-directives#one-per-element). * * @usageNotes * * ### Local variables * * `NgForOf` provides exported values that can be aliased to local variables. * For example: * * ``` *
  • * {{i}}/{{users.length}}. {{user}} default *
  • * ``` * * The following exported values can be aliased to local variables: * * - `$implicit: T`: The value of the individual items in the iterable (`ngForOf`). * - `ngForOf: NgIterable`: The value of the iterable expression. Useful when the expression is * more complex then a property access, for example when using the async pipe (`userStreams | * async`). * - `index: number`: The index of the current item in the iterable. * - `count: number`: The length of the iterable. * - `first: boolean`: True when the item is the first item in the iterable. * - `last: boolean`: True when the item is the last item in the iterable. * - `even: boolean`: True when the item has an even index in the iterable. * - `odd: boolean`: True when the item has an odd index in the iterable. * * ### Change propagation * * When the contents of the iterator changes, `NgForOf` makes the corresponding changes to the DOM: * * * When an item is added, a new instance of the template is added to the DOM. * * When an item is removed, its template instance is removed from the DOM. * * When items are reordered, their respective templates are reordered in the DOM. * * Angular uses object identity to track insertions and deletions within the iterator and reproduce * those changes in the DOM. This has important implications for animations and any stateful * controls that are present, such as `` elements that accept user input. Inserted rows can * be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state * such as user input. * For more on animations, see [Transitions and Triggers](guide/transition-and-triggers). * * The identities of elements in the iterator can change while the data does not. * This can happen, for example, if the iterator is produced from an RPC to the server, and that * RPC is re-run. Even if the data hasn't changed, the second response produces objects with * different identities, and Angular must tear down the entire DOM and rebuild it (as if all old * elements were deleted and all new elements inserted). * * To avoid this expensive operation, you can customize the default tracking algorithm. * by supplying the `trackBy` option to `NgForOf`. * `trackBy` takes a function that has two arguments: `index` and `item`. * If `trackBy` is given, Angular tracks changes by the return value of the function. * * @see [Structural Directives](guide/structural-directives) * @ngModule CommonModule * @publicApi */ class NgForOf { constructor(_viewContainer, _template, _differs) { this._viewContainer = _viewContainer; this._template = _template; this._differs = _differs; this._ngForOf = null; this._ngForOfDirty = true; this._differ = null; } /** * The value of the iterable expression, which can be used as a * [template input variable](guide/structural-directives#shorthand). */ set ngForOf(ngForOf) { this._ngForOf = ngForOf; this._ngForOfDirty = true; } /** * Specifies a custom `TrackByFunction` to compute the identity of items in an iterable. * * If a custom `TrackByFunction` is not provided, `NgForOf` will use the item's [object * identity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) * as the key. * * `NgForOf` uses the computed key to associate items in an iterable with DOM elements * it produces for these items. * * A custom `TrackByFunction` is useful to provide good user experience in cases when items in an * iterable rendered using `NgForOf` have a natural identifier (for example, custom ID or a * primary key), and this iterable could be updated with new object instances that still * represent the same underlying entity (for example, when data is re-fetched from the server, * and the iterable is recreated and re-rendered, but most of the data is still the same). * * @see `TrackByFunction` */ set ngForTrackBy(fn) { if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') { // TODO(vicb): use a log service once there is a public one available if (console && console.warn) { console.warn(`trackBy must be a function, but received ${JSON.stringify(fn)}. ` + `See https://angular.io/api/common/NgForOf#change-propagation for more information.`); } } this._trackByFn = fn; } get ngForTrackBy() { return this._trackByFn; } /** * A reference to the template that is stamped out for each item in the iterable. * @see [template reference variable](guide/template-reference-variables) */ set ngForTemplate(value) { // TODO(TS2.1): make TemplateRef>> once we move to TS v2.1 // The current type is too restrictive; a template that just uses index, for example, // should be acceptable. if (value) { this._template = value; } } /** * Applies the changes when needed. */ ngDoCheck() { if (this._ngForOfDirty) { this._ngForOfDirty = false; // React on ngForOf changes only once all inputs have been initialized const value = this._ngForOf; if (!this._differ && value) { try { this._differ = this._differs.find(value).create(this.ngForTrackBy); } catch (_a) { throw new Error(`Cannot find a differ supporting object '${value}' of type '${getTypeName(value)}'. NgFor only supports binding to Iterables such as Arrays.`); } } } if (this._differ) { const changes = this._differ.diff(this._ngForOf); if (changes) this._applyChanges(changes); } } _applyChanges(changes) { const insertTuples = []; changes.forEachOperation((item, adjustedPreviousIndex, currentIndex) => { if (item.previousIndex == null) { // NgForOf is never "null" or "undefined" here because the differ detected // that a new item needs to be inserted from the iterable. This implies that // there is an iterable value for "_ngForOf". const view = this._viewContainer.createEmbeddedView(this._template, new NgForOfContext(null, this._ngForOf, -1, -1), currentIndex === null ? undefined : currentIndex); const tuple = new RecordViewTuple(item, view); insertTuples.push(tuple); } else if (currentIndex == null) { this._viewContainer.remove(adjustedPreviousIndex === null ? undefined : adjustedPreviousIndex); } else if (adjustedPreviousIndex !== null) { const view = this._viewContainer.get(adjustedPreviousIndex); this._viewContainer.move(view, currentIndex); const tuple = new RecordViewTuple(item, view); insertTuples.push(tuple); } }); for (let i = 0; i < insertTuples.length; i++) { this._perViewChange(insertTuples[i].view, insertTuples[i].record); } for (let i = 0, ilen = this._viewContainer.length; i < ilen; i++) { const viewRef = this._viewContainer.get(i); viewRef.context.index = i; viewRef.context.count = ilen; viewRef.context.ngForOf = this._ngForOf; } changes.forEachIdentityChange((record) => { const viewRef = this._viewContainer.get(record.currentIndex); viewRef.context.$implicit = record.item; }); } _perViewChange(view, record) { view.context.$implicit = record.item; } /** * Asserts the correct type of the context for the template that `NgForOf` will render. * * The presence of this method is a signal to the Ivy template type-check compiler that the * `NgForOf` structural directive renders its template with a specific context type. */ static ngTemplateContextGuard(dir, ctx) { return true; } } NgForOf.ɵfac = function NgForOf_Factory(t) { return new (t || NgForOf)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.IterableDiffers)); }; NgForOf.ɵdir = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgForOf, selectors: [["", "ngFor", "", "ngForOf", ""]], inputs: { ngForOf: "ngForOf", ngForTrackBy: "ngForTrackBy", ngForTemplate: "ngForTemplate" } }); NgForOf.ctorParameters = () => [ { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.IterableDiffers } ]; NgForOf.propDecorators = { ngForOf: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngForTrackBy: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngForTemplate: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgForOf, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Directive, args: [{ selector: '[ngFor][ngForOf]' }] }], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.IterableDiffers }]; }, { ngForOf: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngForTrackBy: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngForTemplate: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }); })(); class RecordViewTuple { constructor(record, view) { this.record = record; this.view = view; } } function getTypeName(type) { return type['name'] || typeof type; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A structural directive that conditionally includes a template based on the value of * an expression coerced to Boolean. * When the expression evaluates to true, Angular renders the template * provided in a `then` clause, and when false or null, * Angular renders the template provided in an optional `else` clause. The default * template for the `else` clause is blank. * * A [shorthand form](guide/structural-directives#asterisk) of the directive, * `*ngIf="condition"`, is generally used, provided * as an attribute of the anchor element for the inserted template. * Angular expands this into a more explicit version, in which the anchor element * is contained in an `` element. * * Simple form with shorthand syntax: * * ``` *
    Content to render when condition is true.
    * ``` * * Simple form with expanded syntax: * * ``` *
    Content to render when condition is * true.
    * ``` * * Form with an "else" block: * * ``` *
    Content to render when condition is true.
    * Content to render when condition is false. * ``` * * Shorthand form with "then" and "else" blocks: * * ``` *
    * Content to render when condition is true. * Content to render when condition is false. * ``` * * Form with storing the value locally: * * ``` *
    {{value}}
    * Content to render when value is null. * ``` * * @usageNotes * * The `*ngIf` directive is most commonly used to conditionally show an inline template, * as seen in the following example. * The default `else` template is blank. * * {@example common/ngIf/ts/module.ts region='NgIfSimple'} * * ### Showing an alternative template using `else` * * To display a template when `expression` evaluates to false, use an `else` template * binding as shown in the following example. * The `else` binding points to an `` element labeled `#elseBlock`. * The template can be defined anywhere in the component view, but is typically placed right after * `ngIf` for readability. * * {@example common/ngIf/ts/module.ts region='NgIfElse'} * * ### Using an external `then` template * * In the previous example, the then-clause template is specified inline, as the content of the * tag that contains the `ngIf` directive. You can also specify a template that is defined * externally, by referencing a labeled `` element. When you do this, you can * change which template to use at runtime, as shown in the following example. * * {@example common/ngIf/ts/module.ts region='NgIfThenElse'} * * ### Storing a conditional result in a variable * * You might want to show a set of properties from the same object. If you are waiting * for asynchronous data, the object can be undefined. * In this case, you can use `ngIf` and store the result of the condition in a local * variable as shown in the following example. * * {@example common/ngIf/ts/module.ts region='NgIfAs'} * * This code uses only one `AsyncPipe`, so only one subscription is created. * The conditional statement stores the result of `userStream|async` in the local variable `user`. * You can then bind the local `user` repeatedly. * * The conditional displays the data only if `userStream` returns a value, * so you don't need to use the * safe-navigation-operator (`?.`) * to guard against null values when accessing properties. * You can display an alternative template while waiting for the data. * * ### Shorthand syntax * * The shorthand syntax `*ngIf` expands into two separate template specifications * for the "then" and "else" clauses. For example, consider the following shorthand statement, * that is meant to show a loading page while waiting for data to be loaded. * * ``` *
    * ... *
    * * *
    Loading...
    *
    * ``` * * You can see that the "else" clause references the `` * with the `#loading` label, and the template for the "then" clause * is provided as the content of the anchor element. * * However, when Angular expands the shorthand syntax, it creates * another `` tag, with `ngIf` and `ngIfElse` directives. * The anchor element containing the template for the "then" clause becomes * the content of this unlabeled `` tag. * * ``` * *
    * ... *
    *
    * * *
    Loading...
    *
    * ``` * * The presence of the implicit template object has implications for the nesting of * structural directives. For more on this subject, see * [Structural Directives](https://angular.io/guide/built-in-directives#one-per-element). * * @ngModule CommonModule * @publicApi */ class NgIf { constructor(_viewContainer, templateRef) { this._viewContainer = _viewContainer; this._context = new NgIfContext(); this._thenTemplateRef = null; this._elseTemplateRef = null; this._thenViewRef = null; this._elseViewRef = null; this._thenTemplateRef = templateRef; } /** * The Boolean expression to evaluate as the condition for showing a template. */ set ngIf(condition) { this._context.$implicit = this._context.ngIf = condition; this._updateView(); } /** * A template to show if the condition expression evaluates to true. */ set ngIfThen(templateRef) { assertTemplate('ngIfThen', templateRef); this._thenTemplateRef = templateRef; this._thenViewRef = null; // clear previous view if any. this._updateView(); } /** * A template to show if the condition expression evaluates to false. */ set ngIfElse(templateRef) { assertTemplate('ngIfElse', templateRef); this._elseTemplateRef = templateRef; this._elseViewRef = null; // clear previous view if any. this._updateView(); } _updateView() { if (this._context.$implicit) { if (!this._thenViewRef) { this._viewContainer.clear(); this._elseViewRef = null; if (this._thenTemplateRef) { this._thenViewRef = this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context); } } } else { if (!this._elseViewRef) { this._viewContainer.clear(); this._thenViewRef = null; if (this._elseTemplateRef) { this._elseViewRef = this._viewContainer.createEmbeddedView(this._elseTemplateRef, this._context); } } } } /** * Asserts the correct type of the context for the template that `NgIf` will render. * * The presence of this method is a signal to the Ivy template type-check compiler that the * `NgIf` structural directive renders its template with a specific context type. */ static ngTemplateContextGuard(dir, ctx) { return true; } } NgIf.ɵfac = function NgIf_Factory(t) { return new (t || NgIf)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef)); }; NgIf.ɵdir = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgIf, selectors: [["", "ngIf", ""]], inputs: { ngIf: "ngIf", ngIfThen: "ngIfThen", ngIfElse: "ngIfElse" } }); NgIf.ctorParameters = () => [ { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef } ]; NgIf.propDecorators = { ngIf: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngIfThen: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngIfElse: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgIf, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Directive, args: [{ selector: '[ngIf]' }] }], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef }]; }, { ngIf: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngIfThen: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngIfElse: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }); })(); /** * @publicApi */ class NgIfContext { constructor() { this.$implicit = null; this.ngIf = null; } } function assertTemplate(property, templateRef) { const isTemplateRefOrNull = !!(!templateRef || templateRef.createEmbeddedView); if (!isTemplateRefOrNull) { throw new Error(`${property} must be a TemplateRef, but received '${(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵstringify"])(templateRef)}'.`); } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ class SwitchView { constructor(_viewContainerRef, _templateRef) { this._viewContainerRef = _viewContainerRef; this._templateRef = _templateRef; this._created = false; } create() { this._created = true; this._viewContainerRef.createEmbeddedView(this._templateRef); } destroy() { this._created = false; this._viewContainerRef.clear(); } enforceState(created) { if (created && !this._created) { this.create(); } else if (!created && this._created) { this.destroy(); } } } /** * @ngModule CommonModule * * @description * The `[ngSwitch]` directive on a container specifies an expression to match against. * The expressions to match are provided by `ngSwitchCase` directives on views within the container. * - Every view that matches is rendered. * - If there are no matches, a view with the `ngSwitchDefault` directive is rendered. * - Elements within the `[NgSwitch]` statement but outside of any `NgSwitchCase` * or `ngSwitchDefault` directive are preserved at the location. * * @usageNotes * Define a container element for the directive, and specify the switch expression * to match against as an attribute: * * ``` * * ``` * * Within the container, `*ngSwitchCase` statements specify the match expressions * as attributes. Include `*ngSwitchDefault` as the final case. * * ``` * * ... * ... * ... * * ``` * * ### Usage Examples * * The following example shows how to use more than one case to display the same view: * * ``` * * * ... * ... * ... * * ... * * ``` * * The following example shows how cases can be nested: * ``` * * ... * ... * ... * * * * * * ... * * ``` * * @publicApi * @see `NgSwitchCase` * @see `NgSwitchDefault` * @see [Structural Directives](guide/structural-directives) * */ class NgSwitch { constructor() { this._defaultUsed = false; this._caseCount = 0; this._lastCaseCheckIndex = 0; this._lastCasesMatched = false; } set ngSwitch(newValue) { this._ngSwitch = newValue; if (this._caseCount === 0) { this._updateDefaultCases(true); } } /** @internal */ _addCase() { return this._caseCount++; } /** @internal */ _addDefault(view) { if (!this._defaultViews) { this._defaultViews = []; } this._defaultViews.push(view); } /** @internal */ _matchCase(value) { const matched = value == this._ngSwitch; this._lastCasesMatched = this._lastCasesMatched || matched; this._lastCaseCheckIndex++; if (this._lastCaseCheckIndex === this._caseCount) { this._updateDefaultCases(!this._lastCasesMatched); this._lastCaseCheckIndex = 0; this._lastCasesMatched = false; } return matched; } _updateDefaultCases(useDefault) { if (this._defaultViews && useDefault !== this._defaultUsed) { this._defaultUsed = useDefault; for (let i = 0; i < this._defaultViews.length; i++) { const defaultView = this._defaultViews[i]; defaultView.enforceState(useDefault); } } } } NgSwitch.ɵfac = function NgSwitch_Factory(t) { return new (t || NgSwitch)(); }; NgSwitch.ɵdir = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgSwitch, selectors: [["", "ngSwitch", ""]], inputs: { ngSwitch: "ngSwitch" } }); NgSwitch.propDecorators = { ngSwitch: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgSwitch, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Directive, args: [{ selector: '[ngSwitch]' }] }], function () { return []; }, { ngSwitch: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }); })(); /** * @ngModule CommonModule * * @description * Provides a switch case expression to match against an enclosing `ngSwitch` expression. * When the expressions match, the given `NgSwitchCase` template is rendered. * If multiple match expressions match the switch expression value, all of them are displayed. * * @usageNotes * * Within a switch container, `*ngSwitchCase` statements specify the match expressions * as attributes. Include `*ngSwitchDefault` as the final case. * * ``` * * ... * ... * ... * * ``` * * Each switch-case statement contains an in-line HTML template or template reference * that defines the subtree to be selected if the value of the match expression * matches the value of the switch expression. * * Unlike JavaScript, which uses strict equality, Angular uses loose equality. * This means that the empty string, `""` matches 0. * * @publicApi * @see `NgSwitch` * @see `NgSwitchDefault` * */ class NgSwitchCase { constructor(viewContainer, templateRef, ngSwitch) { this.ngSwitch = ngSwitch; if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) { throwNgSwitchProviderNotFoundError('ngSwitchCase', 'NgSwitchCase'); } ngSwitch._addCase(); this._view = new SwitchView(viewContainer, templateRef); } /** * Performs case matching. For internal use only. */ ngDoCheck() { this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase)); } } NgSwitchCase.ɵfac = function NgSwitchCase_Factory(t) { return new (t || NgSwitchCase)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NgSwitch, 9)); }; NgSwitchCase.ɵdir = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgSwitchCase, selectors: [["", "ngSwitchCase", ""]], inputs: { ngSwitchCase: "ngSwitchCase" } }); NgSwitchCase.ctorParameters = () => [ { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef }, { type: NgSwitch, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Optional }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Host }] } ]; NgSwitchCase.propDecorators = { ngSwitchCase: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgSwitchCase, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Directive, args: [{ selector: '[ngSwitchCase]' }] }], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef }, { type: NgSwitch, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Optional }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Host }] }]; }, { ngSwitchCase: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }); })(); /** * @ngModule CommonModule * * @description * * Creates a view that is rendered when no `NgSwitchCase` expressions * match the `NgSwitch` expression. * This statement should be the final case in an `NgSwitch`. * * @publicApi * @see `NgSwitch` * @see `NgSwitchCase` * */ class NgSwitchDefault { constructor(viewContainer, templateRef, ngSwitch) { if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) { throwNgSwitchProviderNotFoundError('ngSwitchDefault', 'NgSwitchDefault'); } ngSwitch._addDefault(new SwitchView(viewContainer, templateRef)); } } NgSwitchDefault.ɵfac = function NgSwitchDefault_Factory(t) { return new (t || NgSwitchDefault)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NgSwitch, 9)); }; NgSwitchDefault.ɵdir = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgSwitchDefault, selectors: [["", "ngSwitchDefault", ""]] }); NgSwitchDefault.ctorParameters = () => [ { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef }, { type: NgSwitch, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Optional }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Host }] } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgSwitchDefault, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Directive, args: [{ selector: '[ngSwitchDefault]' }] }], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef }, { type: NgSwitch, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Optional }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Host }] }]; }, null); })(); function throwNgSwitchProviderNotFoundError(attrName, directiveName) { throw new _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵRuntimeError"]("305" /* TEMPLATE_STRUCTURE_ERROR */, `An element with the "${attrName}" attribute ` + `(matching the "${directiveName}" directive) must be located inside an element with the "ngSwitch" attribute ` + `(matching "NgSwitch" directive)`); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * * @usageNotes * ``` * * there is nothing * there is one * there are a few * * ``` * * @description * * Adds / removes DOM sub-trees based on a numeric value. Tailored for pluralization. * * Displays DOM sub-trees that match the switch expression value, or failing that, DOM sub-trees * that match the switch expression's pluralization category. * * To use this directive you must provide a container element that sets the `[ngPlural]` attribute * to a switch expression. Inner elements with a `[ngPluralCase]` will display based on their * expression: * - if `[ngPluralCase]` is set to a value starting with `=`, it will only display if the value * matches the switch expression exactly, * - otherwise, the view will be treated as a "category match", and will only display if exact * value matches aren't found and the value maps to its category for the defined locale. * * See http://cldr.unicode.org/index/cldr-spec/plural-rules * * @publicApi */ class NgPlural { constructor(_localization) { this._localization = _localization; this._caseViews = {}; } set ngPlural(value) { this._switchValue = value; this._updateView(); } addCase(value, switchView) { this._caseViews[value] = switchView; } _updateView() { this._clearViews(); const cases = Object.keys(this._caseViews); const key = getPluralCategory(this._switchValue, cases, this._localization); this._activateView(this._caseViews[key]); } _clearViews() { if (this._activeView) this._activeView.destroy(); } _activateView(view) { if (view) { this._activeView = view; this._activeView.create(); } } } NgPlural.ɵfac = function NgPlural_Factory(t) { return new (t || NgPlural)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NgLocalization)); }; NgPlural.ɵdir = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgPlural, selectors: [["", "ngPlural", ""]], inputs: { ngPlural: "ngPlural" } }); NgPlural.ctorParameters = () => [ { type: NgLocalization } ]; NgPlural.propDecorators = { ngPlural: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgPlural, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Directive, args: [{ selector: '[ngPlural]' }] }], function () { return [{ type: NgLocalization }]; }, { ngPlural: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }); })(); /** * @ngModule CommonModule * * @description * * Creates a view that will be added/removed from the parent {@link NgPlural} when the * given expression matches the plural expression according to CLDR rules. * * @usageNotes * ``` * * ... * ... * *``` * * See {@link NgPlural} for more details and example. * * @publicApi */ class NgPluralCase { constructor(value, template, viewContainer, ngPlural) { this.value = value; const isANumber = !isNaN(Number(value)); ngPlural.addCase(isANumber ? `=${value}` : value, new SwitchView(viewContainer, template)); } } NgPluralCase.ɵfac = function NgPluralCase_Factory(t) { return new (t || NgPluralCase)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinjectAttribute"]('ngPluralCase'), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NgPlural, 1)); }; NgPluralCase.ɵdir = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgPluralCase, selectors: [["", "ngPluralCase", ""]] }); NgPluralCase.ctorParameters = () => [ { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Attribute, args: ['ngPluralCase',] }] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }, { type: NgPlural, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Host }] } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgPluralCase, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Directive, args: [{ selector: '[ngPluralCase]' }] }], function () { return [{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Attribute, args: ['ngPluralCase'] }] }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.TemplateRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }, { type: NgPlural, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Host }] }]; }, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * * @usageNotes * * Set the font of the containing element to the result of an expression. * * ``` * ... * ``` * * Set the width of the containing element to a pixel value returned by an expression. * * ``` * ... * ``` * * Set a collection of style values using an expression that returns key-value pairs. * * ``` * ... * ``` * * @description * * An attribute directive that updates styles for the containing HTML element. * Sets one or more style properties, specified as colon-separated key-value pairs. * The key is a style name, with an optional `.` suffix * (such as 'top.px', 'font-style.em'). * The value is an expression to be evaluated. * The resulting non-null value, expressed in the given unit, * is assigned to the given style property. * If the result of evaluation is null, the corresponding style is removed. * * @publicApi */ class NgStyle { constructor(_ngEl, _differs, _renderer) { this._ngEl = _ngEl; this._differs = _differs; this._renderer = _renderer; this._ngStyle = null; this._differ = null; } set ngStyle(values) { this._ngStyle = values; if (!this._differ && values) { this._differ = this._differs.find(values).create(); } } ngDoCheck() { if (this._differ) { const changes = this._differ.diff(this._ngStyle); if (changes) { this._applyChanges(changes); } } } _setStyle(nameAndUnit, value) { const [name, unit] = nameAndUnit.split('.'); value = value != null && unit ? `${value}${unit}` : value; if (value != null) { this._renderer.setStyle(this._ngEl.nativeElement, name, value); } else { this._renderer.removeStyle(this._ngEl.nativeElement, name); } } _applyChanges(changes) { changes.forEachRemovedItem((record) => this._setStyle(record.key, null)); changes.forEachAddedItem((record) => this._setStyle(record.key, record.currentValue)); changes.forEachChangedItem((record) => this._setStyle(record.key, record.currentValue)); } } NgStyle.ɵfac = function NgStyle_Factory(t) { return new (t || NgStyle)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ElementRef), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.KeyValueDiffers), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.Renderer2)); }; NgStyle.ɵdir = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgStyle, selectors: [["", "ngStyle", ""]], inputs: { ngStyle: "ngStyle" } }); NgStyle.ctorParameters = () => [ { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ElementRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.KeyValueDiffers }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Renderer2 } ]; NgStyle.propDecorators = { ngStyle: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input, args: ['ngStyle',] }] }; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgStyle, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Directive, args: [{ selector: '[ngStyle]' }] }], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ElementRef }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.KeyValueDiffers }, { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Renderer2 }]; }, { ngStyle: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input, args: ['ngStyle'] }] }); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * * @description * * Inserts an embedded view from a prepared `TemplateRef`. * * You can attach a context object to the `EmbeddedViewRef` by setting `[ngTemplateOutletContext]`. * `[ngTemplateOutletContext]` should be an object, the object's keys will be available for binding * by the local template `let` declarations. * * @usageNotes * ``` * * ``` * * Using the key `$implicit` in the context object will set its value as default. * * ### Example * * {@example common/ngTemplateOutlet/ts/module.ts region='NgTemplateOutlet'} * * @publicApi */ class NgTemplateOutlet { constructor(_viewContainerRef) { this._viewContainerRef = _viewContainerRef; this._viewRef = null; /** * A context object to attach to the {@link EmbeddedViewRef}. This should be an * object, the object's keys will be available for binding by the local template `let` * declarations. * Using the key `$implicit` in the context object will set its value as default. */ this.ngTemplateOutletContext = null; /** * A string defining the template reference and optionally the context object for the template. */ this.ngTemplateOutlet = null; } ngOnChanges(changes) { if (changes['ngTemplateOutlet']) { const viewContainerRef = this._viewContainerRef; if (this._viewRef) { viewContainerRef.remove(viewContainerRef.indexOf(this._viewRef)); } this._viewRef = this.ngTemplateOutlet ? viewContainerRef.createEmbeddedView(this.ngTemplateOutlet, this.ngTemplateOutletContext) : null; } else if (this._viewRef && changes['ngTemplateOutletContext'] && this.ngTemplateOutletContext) { this._viewRef.context = this.ngTemplateOutletContext; } } } NgTemplateOutlet.ɵfac = function NgTemplateOutlet_Factory(t) { return new (t || NgTemplateOutlet)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef)); }; NgTemplateOutlet.ɵdir = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineDirective"]({ type: NgTemplateOutlet, selectors: [["", "ngTemplateOutlet", ""]], inputs: { ngTemplateOutletContext: "ngTemplateOutletContext", ngTemplateOutlet: "ngTemplateOutlet" }, features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵNgOnChangesFeature"]] }); NgTemplateOutlet.ctorParameters = () => [ { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef } ]; NgTemplateOutlet.propDecorators = { ngTemplateOutletContext: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngTemplateOutlet: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NgTemplateOutlet, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Directive, args: [{ selector: '[ngTemplateOutlet]' }] }], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ViewContainerRef }]; }, { ngTemplateOutletContext: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }], ngTemplateOutlet: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Input }] }); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A collection of Angular directives that are likely to be used in each and every Angular * application. */ const COMMON_DIRECTIVES = [ NgClass, NgComponentOutlet, NgForOf, NgIf, NgTemplateOutlet, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgPlural, NgPluralCase, ]; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function invalidPipeArgumentError(type, value) { return Error(`InvalidPipeArgument: '${value}' for pipe '${(0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵstringify"])(type)}'`); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ class SubscribableStrategy { createSubscription(async, updateLatestValue) { return async.subscribe({ next: updateLatestValue, error: (e) => { throw e; } }); } dispose(subscription) { subscription.unsubscribe(); } onDestroy(subscription) { subscription.unsubscribe(); } } class PromiseStrategy { createSubscription(async, updateLatestValue) { return async.then(updateLatestValue, e => { throw e; }); } dispose(subscription) { } onDestroy(subscription) { } } const _promiseStrategy = new PromiseStrategy(); const _subscribableStrategy = new SubscribableStrategy(); /** * @ngModule CommonModule * @description * * Unwraps a value from an asynchronous primitive. * * The `async` pipe subscribes to an `Observable` or `Promise` and returns the latest value it has * emitted. When a new value is emitted, the `async` pipe marks the component to be checked for * changes. When the component gets destroyed, the `async` pipe unsubscribes automatically to avoid * potential memory leaks. * * @usageNotes * * ### Examples * * This example binds a `Promise` to the view. Clicking the `Resolve` button resolves the * promise. * * {@example common/pipes/ts/async_pipe.ts region='AsyncPipePromise'} * * It's also possible to use `async` with Observables. The example below binds the `time` Observable * to the view. The Observable continuously updates the view with the current time. * * {@example common/pipes/ts/async_pipe.ts region='AsyncPipeObservable'} * * @publicApi */ class AsyncPipe { constructor(_ref) { this._ref = _ref; this._latestValue = null; this._subscription = null; this._obj = null; this._strategy = null; } ngOnDestroy() { if (this._subscription) { this._dispose(); } } transform(obj) { if (!this._obj) { if (obj) { this._subscribe(obj); } return this._latestValue; } if (obj !== this._obj) { this._dispose(); return this.transform(obj); } return this._latestValue; } _subscribe(obj) { this._obj = obj; this._strategy = this._selectStrategy(obj); this._subscription = this._strategy.createSubscription(obj, (value) => this._updateLatestValue(obj, value)); } _selectStrategy(obj) { if ((0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵisPromise"])(obj)) { return _promiseStrategy; } if ((0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵisSubscribable"])(obj)) { return _subscribableStrategy; } throw invalidPipeArgumentError(AsyncPipe, obj); } _dispose() { this._strategy.dispose(this._subscription); this._latestValue = null; this._subscription = null; this._obj = null; } _updateLatestValue(async, value) { if (async === this._obj) { this._latestValue = value; this._ref.markForCheck(); } } } AsyncPipe.ɵfac = function AsyncPipe_Factory(t) { return new (t || AsyncPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.ChangeDetectorRef, 16)); }; AsyncPipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "async", type: AsyncPipe, pure: false }); AsyncPipe.ctorParameters = () => [ { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ChangeDetectorRef } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](AsyncPipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'async', pure: false }] }], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.ChangeDetectorRef }]; }, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Transforms text to all lower case. * * @see `UpperCasePipe` * @see `TitleCasePipe` * @usageNotes * * The following example defines a view that allows the user to enter * text, and then uses the pipe to convert the input text to all lower case. * * * * @ngModule CommonModule * @publicApi */ class LowerCasePipe { transform(value) { if (value == null) return null; if (typeof value !== 'string') { throw invalidPipeArgumentError(LowerCasePipe, value); } return value.toLowerCase(); } } LowerCasePipe.ɵfac = function LowerCasePipe_Factory(t) { return new (t || LowerCasePipe)(); }; LowerCasePipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "lowercase", type: LowerCasePipe, pure: true }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](LowerCasePipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'lowercase' }] }], null, null); })(); // // Regex below matches any Unicode word and compatible with ES5. In ES2018 the same result // can be achieved by using /\p{L}\S*/gu and also known as Unicode Property Escapes // (https://2ality.com/2017/07/regexp-unicode-property-escapes.html). Since there is no // transpilation of this functionality down to ES5 without external tool, the only solution is // to use already transpiled form. Example can be found here - // https://mothereff.in/regexpu#input=var+regex+%3D+/%5Cp%7BL%7D/u%3B&unicodePropertyEscape=1 // const unicodeWordMatch = /(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])\S*/g; /** * Transforms text to title case. * Capitalizes the first letter of each word and transforms the * rest of the word to lower case. * Words are delimited by any whitespace character, such as a space, tab, or line-feed character. * * @see `LowerCasePipe` * @see `UpperCasePipe` * * @usageNotes * The following example shows the result of transforming various strings into title case. * * * * @ngModule CommonModule * @publicApi */ class TitleCasePipe { transform(value) { if (value == null) return null; if (typeof value !== 'string') { throw invalidPipeArgumentError(TitleCasePipe, value); } return value.replace(unicodeWordMatch, (txt => txt[0].toUpperCase() + txt.substr(1).toLowerCase())); } } TitleCasePipe.ɵfac = function TitleCasePipe_Factory(t) { return new (t || TitleCasePipe)(); }; TitleCasePipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "titlecase", type: TitleCasePipe, pure: true }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](TitleCasePipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'titlecase' }] }], null, null); })(); /** * Transforms text to all upper case. * @see `LowerCasePipe` * @see `TitleCasePipe` * * @ngModule CommonModule * @publicApi */ class UpperCasePipe { transform(value) { if (value == null) return null; if (typeof value !== 'string') { throw invalidPipeArgumentError(UpperCasePipe, value); } return value.toUpperCase(); } } UpperCasePipe.ɵfac = function UpperCasePipe_Factory(t) { return new (t || UpperCasePipe)(); }; UpperCasePipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "uppercase", type: UpperCasePipe, pure: true }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](UpperCasePipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'uppercase' }] }], null, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // clang-format off /** * @ngModule CommonModule * @description * * Formats a date value according to locale rules. * * `DatePipe` is executed only when it detects a pure change to the input value. * A pure change is either a change to a primitive input value * (such as `String`, `Number`, `Boolean`, or `Symbol`), * or a changed object reference (such as `Date`, `Array`, `Function`, or `Object`). * * Note that mutating a `Date` object does not cause the pipe to be rendered again. * To ensure that the pipe is executed, you must create a new `Date` object. * * Only the `en-US` locale data comes with Angular. To localize dates * in another language, you must import the corresponding locale data. * See the [I18n guide](guide/i18n#i18n-pipes) for more information. * * @see `formatDate()` * * * @usageNotes * * The result of this pipe is not reevaluated when the input is mutated. To avoid the need to * reformat the date on every change-detection cycle, treat the date as an immutable object * and change the reference when the pipe needs to run again. * * ### Pre-defined format options * * | Option | Equivalent to | Examples (given in `en-US` locale) | * |---------------|-------------------------------------|-------------------------------------------------| * | `'short'` | `'M/d/yy, h:mm a'` | `6/15/15, 9:03 AM` | * | `'medium'` | `'MMM d, y, h:mm:ss a'` | `Jun 15, 2015, 9:03:01 AM` | * | `'long'` | `'MMMM d, y, h:mm:ss a z'` | `June 15, 2015 at 9:03:01 AM GMT+1` | * | `'full'` | `'EEEE, MMMM d, y, h:mm:ss a zzzz'` | `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00` | * | `'shortDate'` | `'M/d/yy'` | `6/15/15` | * | `'mediumDate'`| `'MMM d, y'` | `Jun 15, 2015` | * | `'longDate'` | `'MMMM d, y'` | `June 15, 2015` | * | `'fullDate'` | `'EEEE, MMMM d, y'` | `Monday, June 15, 2015` | * | `'shortTime'` | `'h:mm a'` | `9:03 AM` | * | `'mediumTime'`| `'h:mm:ss a'` | `9:03:01 AM` | * | `'longTime'` | `'h:mm:ss a z'` | `9:03:01 AM GMT+1` | * | `'fullTime'` | `'h:mm:ss a zzzz'` | `9:03:01 AM GMT+01:00` | * * ### Custom format options * * You can construct a format string using symbols to specify the components * of a date-time value, as described in the following table. * Format details depend on the locale. * Fields marked with (*) are only available in the extra data set for the given locale. * * | Field type | Format | Description | Example Value | * |-------------------- |-------------|---------------------------------------------------------------|------------------------------------------------------------| * | Era | G, GG & GGG | Abbreviated | AD | * | | GGGG | Wide | Anno Domini | * | | GGGGG | Narrow | A | * | Year | y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 | * | | yy | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 | * | | yyy | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 | * | | yyyy | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 | * | Week-numbering year | Y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 | * | | YY | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 | * | | YYY | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 | * | | YYYY | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 | * | Month | M | Numeric: 1 digit | 9, 12 | * | | MM | Numeric: 2 digits + zero padded | 09, 12 | * | | MMM | Abbreviated | Sep | * | | MMMM | Wide | September | * | | MMMMM | Narrow | S | * | Month standalone | L | Numeric: 1 digit | 9, 12 | * | | LL | Numeric: 2 digits + zero padded | 09, 12 | * | | LLL | Abbreviated | Sep | * | | LLLL | Wide | September | * | | LLLLL | Narrow | S | * | Week of year | w | Numeric: minimum digits | 1... 53 | * | | ww | Numeric: 2 digits + zero padded | 01... 53 | * | Week of month | W | Numeric: 1 digit | 1... 5 | * | Day of month | d | Numeric: minimum digits | 1 | * | | dd | Numeric: 2 digits + zero padded | 01 | * | Week day | E, EE & EEE | Abbreviated | Tue | * | | EEEE | Wide | Tuesday | * | | EEEEE | Narrow | T | * | | EEEEEE | Short | Tu | * | Week day standalone | c, cc | Numeric: 1 digit | 2 | * | | ccc | Abbreviated | Tue | * | | cccc | Wide | Tuesday | * | | ccccc | Narrow | T | * | | cccccc | Short | Tu | * | Period | a, aa & aaa | Abbreviated | am/pm or AM/PM | * | | aaaa | Wide (fallback to `a` when missing) | ante meridiem/post meridiem | * | | aaaaa | Narrow | a/p | * | Period* | B, BB & BBB | Abbreviated | mid. | * | | BBBB | Wide | am, pm, midnight, noon, morning, afternoon, evening, night | * | | BBBBB | Narrow | md | * | Period standalone* | b, bb & bbb | Abbreviated | mid. | * | | bbbb | Wide | am, pm, midnight, noon, morning, afternoon, evening, night | * | | bbbbb | Narrow | md | * | Hour 1-12 | h | Numeric: minimum digits | 1, 12 | * | | hh | Numeric: 2 digits + zero padded | 01, 12 | * | Hour 0-23 | H | Numeric: minimum digits | 0, 23 | * | | HH | Numeric: 2 digits + zero padded | 00, 23 | * | Minute | m | Numeric: minimum digits | 8, 59 | * | | mm | Numeric: 2 digits + zero padded | 08, 59 | * | Second | s | Numeric: minimum digits | 0... 59 | * | | ss | Numeric: 2 digits + zero padded | 00... 59 | * | Fractional seconds | S | Numeric: 1 digit | 0... 9 | * | | SS | Numeric: 2 digits + zero padded | 00... 99 | * | | SSS | Numeric: 3 digits + zero padded (= milliseconds) | 000... 999 | * | Zone | z, zz & zzz | Short specific non location format (fallback to O) | GMT-8 | * | | zzzz | Long specific non location format (fallback to OOOO) | GMT-08:00 | * | | Z, ZZ & ZZZ | ISO8601 basic format | -0800 | * | | ZZZZ | Long localized GMT format | GMT-8:00 | * | | ZZZZZ | ISO8601 extended format + Z indicator for offset 0 (= XXXXX) | -08:00 | * | | O, OO & OOO | Short localized GMT format | GMT-8 | * | | OOOO | Long localized GMT format | GMT-08:00 | * * * ### Format examples * * These examples transform a date into various formats, * assuming that `dateObj` is a JavaScript `Date` object for * year: 2015, month: 6, day: 15, hour: 21, minute: 43, second: 11, * given in the local time for the `en-US` locale. * * ``` * {{ dateObj | date }} // output is 'Jun 15, 2015' * {{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM' * {{ dateObj | date:'shortTime' }} // output is '9:43 PM' * {{ dateObj | date:'mm:ss' }} // output is '43:11' * ``` * * ### Usage example * * The following component uses a date pipe to display the current date in different formats. * * ``` * @Component({ * selector: 'date-pipe', * template: `
    *

    Today is {{today | date}}

    *

    Or if you prefer, {{today | date:'fullDate'}}

    *

    The time is {{today | date:'h:mm a z'}}

    *
    ` * }) * // Get the current date and time as a date-time value. * export class DatePipeComponent { * today: number = Date.now(); * } * ``` * * @publicApi */ // clang-format on class DatePipe { constructor(locale) { this.locale = locale; } transform(value, format = 'mediumDate', timezone, locale) { if (value == null || value === '' || value !== value) return null; try { return formatDate(value, format, locale || this.locale, timezone); } catch (error) { throw invalidPipeArgumentError(DatePipe, error.message); } } } DatePipe.ɵfac = function DatePipe_Factory(t) { return new (t || DatePipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID, 16)); }; DatePipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "date", type: DatePipe, pure: true }); DatePipe.ctorParameters = () => [ { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID,] }] } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](DatePipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'date', pure: true }] }], function () { return [{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID] }] }]; }, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const _INTERPOLATION_REGEXP = /#/g; /** * @ngModule CommonModule * @description * * Maps a value to a string that pluralizes the value according to locale rules. * * @usageNotes * * ### Example * * {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'} * * @publicApi */ class I18nPluralPipe { constructor(_localization) { this._localization = _localization; } /** * @param value the number to be formatted * @param pluralMap an object that mimics the ICU format, see * http://userguide.icu-project.org/formatparse/messages. * @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by * default). */ transform(value, pluralMap, locale) { if (value == null) return ''; if (typeof pluralMap !== 'object' || pluralMap === null) { throw invalidPipeArgumentError(I18nPluralPipe, pluralMap); } const key = getPluralCategory(value, Object.keys(pluralMap), this._localization, locale); return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString()); } } I18nPluralPipe.ɵfac = function I18nPluralPipe_Factory(t) { return new (t || I18nPluralPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](NgLocalization, 16)); }; I18nPluralPipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "i18nPlural", type: I18nPluralPipe, pure: true }); I18nPluralPipe.ctorParameters = () => [ { type: NgLocalization } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](I18nPluralPipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'i18nPlural', pure: true }] }], function () { return [{ type: NgLocalization }]; }, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * @description * * Generic selector that displays the string that matches the current value. * * If none of the keys of the `mapping` match the `value`, then the content * of the `other` key is returned when present, otherwise an empty string is returned. * * @usageNotes * * ### Example * * {@example common/pipes/ts/i18n_pipe.ts region='I18nSelectPipeComponent'} * * @publicApi */ class I18nSelectPipe { /** * @param value a string to be internationalized. * @param mapping an object that indicates the text that should be displayed * for different values of the provided `value`. */ transform(value, mapping) { if (value == null) return ''; if (typeof mapping !== 'object' || typeof value !== 'string') { throw invalidPipeArgumentError(I18nSelectPipe, mapping); } if (mapping.hasOwnProperty(value)) { return mapping[value]; } if (mapping.hasOwnProperty('other')) { return mapping['other']; } return ''; } } I18nSelectPipe.ɵfac = function I18nSelectPipe_Factory(t) { return new (t || I18nSelectPipe)(); }; I18nSelectPipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "i18nSelect", type: I18nSelectPipe, pure: true }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](I18nSelectPipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'i18nSelect', pure: true }] }], null, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * @description * * Converts a value into its JSON-format representation. Useful for debugging. * * @usageNotes * * The following component uses a JSON pipe to convert an object * to JSON format, and displays the string in both formats for comparison. * * {@example common/pipes/ts/json_pipe.ts region='JsonPipe'} * * @publicApi */ class JsonPipe { /** * @param value A value of any type to convert into a JSON-format string. */ transform(value) { return JSON.stringify(value, null, 2); } } JsonPipe.ɵfac = function JsonPipe_Factory(t) { return new (t || JsonPipe)(); }; JsonPipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "json", type: JsonPipe, pure: false }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](JsonPipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'json', pure: false }] }], null, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function makeKeyValuePair(key, value) { return { key: key, value: value }; } /** * @ngModule CommonModule * @description * * Transforms Object or Map into an array of key value pairs. * * The output array will be ordered by keys. * By default the comparator will be by Unicode point value. * You can optionally pass a compareFn if your keys are complex types. * * @usageNotes * ### Examples * * This examples show how an Object or a Map can be iterated by ngFor with the use of this * keyvalue pipe. * * {@example common/pipes/ts/keyvalue_pipe.ts region='KeyValuePipe'} * * @publicApi */ class KeyValuePipe { constructor(differs) { this.differs = differs; this.keyValues = []; } transform(input, compareFn = defaultComparator) { if (!input || (!(input instanceof Map) && typeof input !== 'object')) { return null; } if (!this.differ) { // make a differ for whatever type we've been passed in this.differ = this.differs.find(input).create(); } const differChanges = this.differ.diff(input); if (differChanges) { this.keyValues = []; differChanges.forEachItem((r) => { this.keyValues.push(makeKeyValuePair(r.key, r.currentValue)); }); this.keyValues.sort(compareFn); } return this.keyValues; } } KeyValuePipe.ɵfac = function KeyValuePipe_Factory(t) { return new (t || KeyValuePipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.KeyValueDiffers, 16)); }; KeyValuePipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "keyvalue", type: KeyValuePipe, pure: false }); KeyValuePipe.ctorParameters = () => [ { type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.KeyValueDiffers } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](KeyValuePipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'keyvalue', pure: false }] }], function () { return [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.KeyValueDiffers }]; }, null); })(); function defaultComparator(keyValueA, keyValueB) { const a = keyValueA.key; const b = keyValueB.key; // if same exit with 0; if (a === b) return 0; // make sure that undefined are at the end of the sort. if (a === undefined) return 1; if (b === undefined) return -1; // make sure that nulls are at the end of the sort. if (a === null) return 1; if (b === null) return -1; if (typeof a == 'string' && typeof b == 'string') { return a < b ? -1 : 1; } if (typeof a == 'number' && typeof b == 'number') { return a - b; } if (typeof a == 'boolean' && typeof b == 'boolean') { return a < b ? -1 : 1; } // `a` and `b` are of different types. Compare their string values. const aString = String(a); const bString = String(b); return aString == bString ? 0 : aString < bString ? -1 : 1; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * @description * * Formats a value according to digit options and locale rules. * Locale determines group sizing and separator, * decimal point character, and other locale-specific configurations. * * @see `formatNumber()` * * @usageNotes * * ### digitsInfo * * The value's decimal representation is specified by the `digitsInfo` * parameter, written in the following format:
    * * ``` * {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits} * ``` * * - `minIntegerDigits`: * The minimum number of integer digits before the decimal point. * Default is 1. * * - `minFractionDigits`: * The minimum number of digits after the decimal point. * Default is 0. * * - `maxFractionDigits`: * The maximum number of digits after the decimal point. * Default is 3. * * If the formatted value is truncated it will be rounded using the "to-nearest" method: * * ``` * {{3.6 | number: '1.0-0'}} * * * {{-3.6 | number:'1.0-0'}} * * ``` * * ### locale * * `locale` will format a value according to locale rules. * Locale determines group sizing and separator, * decimal point character, and other locale-specific configurations. * * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default. * * See [Setting your app locale](guide/i18n#setting-up-the-locale-of-your-app). * * ### Example * * The following code shows how the pipe transforms values * according to various format specifications, * where the caller's default locale is `en-US`. * * * * @publicApi */ class DecimalPipe { constructor(_locale) { this._locale = _locale; } /** * @param value The value to be formatted. * @param digitsInfo Sets digit and decimal representation. * [See more](#digitsinfo). * @param locale Specifies what locale format rules to use. * [See more](#locale). */ transform(value, digitsInfo, locale) { if (!isValue(value)) return null; locale = locale || this._locale; try { const num = strToNumber(value); return formatNumber(num, locale, digitsInfo); } catch (error) { throw invalidPipeArgumentError(DecimalPipe, error.message); } } } DecimalPipe.ɵfac = function DecimalPipe_Factory(t) { return new (t || DecimalPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID, 16)); }; DecimalPipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "number", type: DecimalPipe, pure: true }); DecimalPipe.ctorParameters = () => [ { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID,] }] } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](DecimalPipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'number' }] }], function () { return [{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID] }] }]; }, null); })(); /** * @ngModule CommonModule * @description * * Transforms a number to a percentage * string, formatted according to locale rules that determine group sizing and * separator, decimal-point character, and other locale-specific * configurations. * * @see `formatPercent()` * * @usageNotes * The following code shows how the pipe transforms numbers * into text strings, according to various format specifications, * where the caller's default locale is `en-US`. * * * * @publicApi */ class PercentPipe { constructor(_locale) { this._locale = _locale; } transform(value, digitsInfo, locale) { if (!isValue(value)) return null; locale = locale || this._locale; try { const num = strToNumber(value); return formatPercent(num, locale, digitsInfo); } catch (error) { throw invalidPipeArgumentError(PercentPipe, error.message); } } } PercentPipe.ɵfac = function PercentPipe_Factory(t) { return new (t || PercentPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID, 16)); }; PercentPipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "percent", type: PercentPipe, pure: true }); PercentPipe.ctorParameters = () => [ { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID,] }] } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](PercentPipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'percent' }] }], function () { return [{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID] }] }]; }, null); })(); /** * @ngModule CommonModule * @description * * Transforms a number to a currency string, formatted according to locale rules * that determine group sizing and separator, decimal-point character, * and other locale-specific configurations. * * {@a currency-code-deprecation} *
    * * **Deprecation notice:** * * The default currency code is currently always `USD` but this is deprecated from v9. * * **In v11 the default currency code will be taken from the current locale identified by * the `LOCALE_ID` token. See the [i18n guide](guide/i18n#setting-up-the-locale-of-your-app) for * more information.** * * If you need the previous behavior then set it by creating a `DEFAULT_CURRENCY_CODE` provider in * your application `NgModule`: * * ```ts * {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'} * ``` * *
    * * @see `getCurrencySymbol()` * @see `formatCurrency()` * * @usageNotes * The following code shows how the pipe transforms numbers * into text strings, according to various format specifications, * where the caller's default locale is `en-US`. * * * * @publicApi */ class CurrencyPipe { constructor(_locale, _defaultCurrencyCode = 'USD') { this._locale = _locale; this._defaultCurrencyCode = _defaultCurrencyCode; } transform(value, currencyCode = this._defaultCurrencyCode, display = 'symbol', digitsInfo, locale) { if (!isValue(value)) return null; locale = locale || this._locale; if (typeof display === 'boolean') { if ((typeof ngDevMode === 'undefined' || ngDevMode) && console && console.warn) { console.warn(`Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are "code", "symbol" or "symbol-narrow".`); } display = display ? 'symbol' : 'code'; } let currency = currencyCode || this._defaultCurrencyCode; if (display !== 'code') { if (display === 'symbol' || display === 'symbol-narrow') { currency = getCurrencySymbol(currency, display === 'symbol' ? 'wide' : 'narrow', locale); } else { currency = display; } } try { const num = strToNumber(value); return formatCurrency(num, locale, currency, currencyCode, digitsInfo); } catch (error) { throw invalidPipeArgumentError(CurrencyPipe, error.message); } } } CurrencyPipe.ɵfac = function CurrencyPipe_Factory(t) { return new (t || CurrencyPipe)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID, 16), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_core__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_CURRENCY_CODE, 16)); }; CurrencyPipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "currency", type: CurrencyPipe, pure: true }); CurrencyPipe.ctorParameters = () => [ { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID,] }] }, { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_CURRENCY_CODE,] }] } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](CurrencyPipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'currency' }] }], function () { return [{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.LOCALE_ID] }] }, { type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Inject, args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_CURRENCY_CODE] }] }]; }, null); })(); function isValue(value) { return !(value == null || value === '' || value !== value); } /** * Transforms a string into a number (if needed). */ function strToNumber(value) { // Convert strings to numbers if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) { return Number(value); } if (typeof value !== 'number') { throw new Error(`${value} is not a number`); } return value; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * @description * * Creates a new `Array` or `String` containing a subset (slice) of the elements. * * @usageNotes * * All behavior is based on the expected behavior of the JavaScript API `Array.prototype.slice()` * and `String.prototype.slice()`. * * When operating on an `Array`, the returned `Array` is always a copy even when all * the elements are being returned. * * When operating on a blank value, the pipe returns the blank value. * * ### List Example * * This `ngFor` example: * * {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_list'} * * produces the following: * * ```html *
  • b
  • *
  • c
  • * ``` * * ### String Examples * * {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_string'} * * @publicApi */ class SlicePipe { transform(value, start, end) { if (value == null) return null; if (!this.supports(value)) { throw invalidPipeArgumentError(SlicePipe, value); } return value.slice(start, end); } supports(obj) { return typeof obj === 'string' || Array.isArray(obj); } } SlicePipe.ɵfac = function SlicePipe_Factory(t) { return new (t || SlicePipe)(); }; SlicePipe.ɵpipe = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "slice", type: SlicePipe, pure: false }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](SlicePipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.Pipe, args: [{ name: 'slice', pure: false }] }], null, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A collection of Angular pipes that are likely to be used in each and every application. */ const COMMON_PIPES = [ AsyncPipe, UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, TitleCasePipe, CurrencyPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, KeyValuePipe, ]; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // Note: This does not contain the location providers, // as they need some platform specific implementations to work. /** * Exports all the basic Angular directives and pipes, * such as `NgIf`, `NgForOf`, `DecimalPipe`, and so on. * Re-exported by `BrowserModule`, which is included automatically in the root * `AppModule` when you create a new app with the CLI `new` command. * * * The `providers` options configure the NgModule's injector to provide * localization dependencies to members. * * The `exports` options make the declared directives and pipes available for import * by other NgModules. * * @publicApi */ class CommonModule { } CommonModule.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; CommonModule.ɵmod = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineNgModule"]({ type: CommonModule }); CommonModule.ɵinj = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjector"]({ providers: [ { provide: NgLocalization, useClass: NgLocaleLocalization }, ] }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](CommonModule, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__.NgModule, args: [{ declarations: [COMMON_DIRECTIVES, COMMON_PIPES], exports: [COMMON_DIRECTIVES, COMMON_PIPES], providers: [ { provide: NgLocalization, useClass: NgLocaleLocalization }, ] }] }], null, null); })(); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵsetNgModuleScope"](CommonModule, { declarations: [NgClass, NgComponentOutlet, NgForOf, NgIf, NgTemplateOutlet, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgPlural, NgPluralCase, AsyncPipe, UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, TitleCasePipe, CurrencyPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, KeyValuePipe], exports: [NgClass, NgComponentOutlet, NgForOf, NgIf, NgTemplateOutlet, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgPlural, NgPluralCase, AsyncPipe, UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, TitleCasePipe, CurrencyPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, KeyValuePipe] }); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const PLATFORM_BROWSER_ID = 'browser'; const PLATFORM_SERVER_ID = 'server'; const PLATFORM_WORKER_APP_ID = 'browserWorkerApp'; const PLATFORM_WORKER_UI_ID = 'browserWorkerUi'; /** * Returns whether a platform id represents a browser platform. * @publicApi */ function isPlatformBrowser(platformId) { return platformId === PLATFORM_BROWSER_ID; } /** * Returns whether a platform id represents a server platform. * @publicApi */ function isPlatformServer(platformId) { return platformId === PLATFORM_SERVER_ID; } /** * Returns whether a platform id represents a web worker app platform. * @publicApi */ function isPlatformWorkerApp(platformId) { return platformId === PLATFORM_WORKER_APP_ID; } /** * Returns whether a platform id represents a web worker UI platform. * @publicApi */ function isPlatformWorkerUi(platformId) { return platformId === PLATFORM_WORKER_UI_ID; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @publicApi */ const VERSION = new _angular_core__WEBPACK_IMPORTED_MODULE_0__.Version('12.0.5'); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Defines a scroll position manager. Implemented by `BrowserViewportScroller`. * * @publicApi */ class ViewportScroller { } // De-sugared tree-shakable injection // See #23917 /** @nocollapse */ ViewportScroller.ɵprov = (0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"])({ token: ViewportScroller, providedIn: 'root', factory: () => new BrowserViewportScroller((0,_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"])(DOCUMENT), window) }); /** * Manages the scroll position for a browser window. */ class BrowserViewportScroller { constructor(document, window) { this.document = document; this.window = window; this.offset = () => [0, 0]; } /** * Configures the top offset used when scrolling to an anchor. * @param offset A position in screen coordinates (a tuple with x and y values) * or a function that returns the top offset position. * */ setOffset(offset) { if (Array.isArray(offset)) { this.offset = () => offset; } else { this.offset = offset; } } /** * Retrieves the current scroll position. * @returns The position in screen coordinates. */ getScrollPosition() { if (this.supportsScrolling()) { return [this.window.pageXOffset, this.window.pageYOffset]; } else { return [0, 0]; } } /** * Sets the scroll position. * @param position The new position in screen coordinates. */ scrollToPosition(position) { if (this.supportsScrolling()) { this.window.scrollTo(position[0], position[1]); } } /** * Scrolls to an element and attempts to focus the element. * * Note that the function name here is misleading in that the target string may be an ID for a * non-anchor element. * * @param target The ID of an element or name of the anchor. * * @see https://html.spec.whatwg.org/#the-indicated-part-of-the-document * @see https://html.spec.whatwg.org/#scroll-to-fragid */ scrollToAnchor(target) { if (!this.supportsScrolling()) { return; } // TODO(atscott): The correct behavior for `getElementsByName` would be to also verify that the // element is an anchor. However, this could be considered a breaking change and should be // done in a major version. const elSelected = findAnchorFromDocument(this.document, target); if (elSelected) { this.scrollToElement(elSelected); // After scrolling to the element, the spec dictates that we follow the focus steps for the // target. Rather than following the robust steps, simply attempt focus. this.attemptFocus(elSelected); } } /** * Disables automatic scroll restoration provided by the browser. */ setHistoryScrollRestoration(scrollRestoration) { if (this.supportScrollRestoration()) { const history = this.window.history; if (history && history.scrollRestoration) { history.scrollRestoration = scrollRestoration; } } } /** * Scrolls to an element using the native offset and the specified offset set on this scroller. * * The offset can be used when we know that there is a floating header and scrolling naively to an * element (ex: `scrollIntoView`) leaves the element hidden behind the floating header. */ scrollToElement(el) { const rect = el.getBoundingClientRect(); const left = rect.left + this.window.pageXOffset; const top = rect.top + this.window.pageYOffset; const offset = this.offset(); this.window.scrollTo(left - offset[0], top - offset[1]); } /** * Calls `focus` on the `focusTarget` and returns `true` if the element was focused successfully. * * If `false`, further steps may be necessary to determine a valid substitute to be focused * instead. * * @see https://html.spec.whatwg.org/#get-the-focusable-area * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus * @see https://html.spec.whatwg.org/#focusable-area */ attemptFocus(focusTarget) { focusTarget.focus(); return this.document.activeElement === focusTarget; } /** * We only support scroll restoration when we can get a hold of window. * This means that we do not support this behavior when running in a web worker. * * Lifting this restriction right now would require more changes in the dom adapter. * Since webworkers aren't widely used, we will lift it once RouterScroller is * battle-tested. */ supportScrollRestoration() { try { if (!this.supportsScrolling()) { return false; } // The `scrollRestoration` property could be on the `history` instance or its prototype. const scrollRestorationDescriptor = getScrollRestorationProperty(this.window.history) || getScrollRestorationProperty(Object.getPrototypeOf(this.window.history)); // We can write to the `scrollRestoration` property if it is a writable data field or it has a // setter function. return !!scrollRestorationDescriptor && !!(scrollRestorationDescriptor.writable || scrollRestorationDescriptor.set); } catch (_a) { return false; } } supportsScrolling() { try { return !!this.window && !!this.window.scrollTo && 'pageXOffset' in this.window; } catch (_a) { return false; } } } function getScrollRestorationProperty(obj) { return Object.getOwnPropertyDescriptor(obj, 'scrollRestoration'); } function findAnchorFromDocument(document, target) { const documentResult = document.getElementById(target) || document.getElementsByName(target)[0]; if (documentResult) { return documentResult; } // `getElementById` and `getElementsByName` won't pierce through the shadow DOM so we // have to traverse the DOM manually and do the lookup through the shadow roots. if (typeof document.createTreeWalker === 'function' && document.body && (document.body.createShadowRoot || document.body.attachShadow)) { const treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT); let currentNode = treeWalker.currentNode; while (currentNode) { const shadowRoot = currentNode.shadowRoot; if (shadowRoot) { // Note that `ShadowRoot` doesn't support `getElementsByName` // so we have to fall back to `querySelector`. const result = shadowRoot.getElementById(target) || shadowRoot.querySelector(`[name="${target}"]`); if (result) { return result; } } currentNode = treeWalker.nextNode(); } } return null; } /** * Provides an empty implementation of the viewport scroller. */ class NullViewportScroller { /** * Empty implementation */ setOffset(offset) { } /** * Empty implementation */ getScrollPosition() { return [0, 0]; } /** * Empty implementation */ scrollToPosition(position) { } /** * Empty implementation */ scrollToAnchor(anchor) { } /** * Empty implementation */ setHistoryScrollRestoration(scrollRestoration) { } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A wrapper around the `XMLHttpRequest` constructor. * * @publicApi */ class XhrFactory { } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // This file only reexports content of the `src` folder. Keep it that way. /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Generated bundle index. Do not edit. */ //# sourceMappingURL=common.js.map /***/ }), /***/ 91841: /*!********************************************************************!*\ !*** ./node_modules/@angular/common/__ivy_ngcc__/fesm2015/http.js ***! \********************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "HTTP_INTERCEPTORS": () => (/* binding */ HTTP_INTERCEPTORS), /* harmony export */ "HttpBackend": () => (/* binding */ HttpBackend), /* harmony export */ "HttpClient": () => (/* binding */ HttpClient), /* harmony export */ "HttpClientJsonpModule": () => (/* binding */ HttpClientJsonpModule), /* harmony export */ "HttpClientModule": () => (/* binding */ HttpClientModule), /* harmony export */ "HttpClientXsrfModule": () => (/* binding */ HttpClientXsrfModule), /* harmony export */ "HttpContext": () => (/* binding */ HttpContext), /* harmony export */ "HttpContextToken": () => (/* binding */ HttpContextToken), /* harmony export */ "HttpErrorResponse": () => (/* binding */ HttpErrorResponse), /* harmony export */ "HttpEventType": () => (/* binding */ HttpEventType), /* harmony export */ "HttpHandler": () => (/* binding */ HttpHandler), /* harmony export */ "HttpHeaderResponse": () => (/* binding */ HttpHeaderResponse), /* harmony export */ "HttpHeaders": () => (/* binding */ HttpHeaders), /* harmony export */ "HttpParams": () => (/* binding */ HttpParams), /* harmony export */ "HttpRequest": () => (/* binding */ HttpRequest), /* harmony export */ "HttpResponse": () => (/* binding */ HttpResponse), /* harmony export */ "HttpResponseBase": () => (/* binding */ HttpResponseBase), /* harmony export */ "HttpUrlEncodingCodec": () => (/* binding */ HttpUrlEncodingCodec), /* harmony export */ "HttpXhrBackend": () => (/* binding */ HttpXhrBackend), /* harmony export */ "HttpXsrfTokenExtractor": () => (/* binding */ HttpXsrfTokenExtractor), /* harmony export */ "JsonpClientBackend": () => (/* binding */ JsonpClientBackend), /* harmony export */ "JsonpInterceptor": () => (/* binding */ JsonpInterceptor), /* harmony export */ "XhrFactory": () => (/* binding */ XhrFactory), /* harmony export */ "ɵHttpInterceptingHandler": () => (/* binding */ HttpInterceptingHandler), /* harmony export */ "ɵangular_packages_common_http_http_a": () => (/* binding */ NoopInterceptor), /* harmony export */ "ɵangular_packages_common_http_http_b": () => (/* binding */ JsonpCallbackContext), /* harmony export */ "ɵangular_packages_common_http_http_c": () => (/* binding */ jsonpCallbackContext), /* harmony export */ "ɵangular_packages_common_http_http_d": () => (/* binding */ XSRF_COOKIE_NAME), /* harmony export */ "ɵangular_packages_common_http_http_e": () => (/* binding */ XSRF_HEADER_NAME), /* harmony export */ "ɵangular_packages_common_http_http_f": () => (/* binding */ HttpXsrfCookieExtractor), /* harmony export */ "ɵangular_packages_common_http_http_g": () => (/* binding */ HttpXsrfInterceptor) /* harmony export */ }); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @angular/common */ 38583); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @angular/core */ 37716); /* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rxjs */ 25917); /* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! rxjs */ 69165); /* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs/operators */ 94612); /* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs/operators */ 45435); /* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs/operators */ 88002); /** * @license Angular v12.0.5 * (c) 2010-2021 Google LLC. https://angular.io/ * License: MIT */ /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Transforms an `HttpRequest` into a stream of `HttpEvent`s, one of which will likely be a * `HttpResponse`. * * `HttpHandler` is injectable. When injected, the handler instance dispatches requests to the * first interceptor in the chain, which dispatches to the second, etc, eventually reaching the * `HttpBackend`. * * In an `HttpInterceptor`, the `HttpHandler` parameter is the next interceptor in the chain. * * @publicApi */ class HttpHandler { } /** * A final `HttpHandler` which will dispatch the request via browser HTTP APIs to a backend. * * Interceptors sit between the `HttpClient` interface and the `HttpBackend`. * * When injected, `HttpBackend` dispatches requests directly to the backend, without going * through the interceptor chain. * * @publicApi */ class HttpBackend { } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Represents the header configuration options for an HTTP request. * Instances are immutable. Modifying methods return a cloned * instance with the change. The original object is never changed. * * @publicApi */ class HttpHeaders { /** Constructs a new HTTP header object with the given values.*/ constructor(headers) { /** * Internal map of lowercased header names to the normalized * form of the name (the form seen first). */ this.normalizedNames = new Map(); /** * Queued updates to be materialized the next initialization. */ this.lazyUpdate = null; if (!headers) { this.headers = new Map(); } else if (typeof headers === 'string') { this.lazyInit = () => { this.headers = new Map(); headers.split('\n').forEach(line => { const index = line.indexOf(':'); if (index > 0) { const name = line.slice(0, index); const key = name.toLowerCase(); const value = line.slice(index + 1).trim(); this.maybeSetNormalizedName(name, key); if (this.headers.has(key)) { this.headers.get(key).push(value); } else { this.headers.set(key, [value]); } } }); }; } else { this.lazyInit = () => { this.headers = new Map(); Object.keys(headers).forEach(name => { let values = headers[name]; const key = name.toLowerCase(); if (typeof values === 'string') { values = [values]; } if (values.length > 0) { this.headers.set(key, values); this.maybeSetNormalizedName(name, key); } }); }; } } /** * Checks for existence of a given header. * * @param name The header name to check for existence. * * @returns True if the header exists, false otherwise. */ has(name) { this.init(); return this.headers.has(name.toLowerCase()); } /** * Retrieves the first value of a given header. * * @param name The header name. * * @returns The value string if the header exists, null otherwise */ get(name) { this.init(); const values = this.headers.get(name.toLowerCase()); return values && values.length > 0 ? values[0] : null; } /** * Retrieves the names of the headers. * * @returns A list of header names. */ keys() { this.init(); return Array.from(this.normalizedNames.values()); } /** * Retrieves a list of values for a given header. * * @param name The header name from which to retrieve values. * * @returns A string of values if the header exists, null otherwise. */ getAll(name) { this.init(); return this.headers.get(name.toLowerCase()) || null; } /** * Appends a new value to the existing set of values for a header * and returns them in a clone of the original instance. * * @param name The header name for which to append the values. * @param value The value to append. * * @returns A clone of the HTTP headers object with the value appended to the given header. */ append(name, value) { return this.clone({ name, value, op: 'a' }); } /** * Sets or modifies a value for a given header in a clone of the original instance. * If the header already exists, its value is replaced with the given value * in the returned object. * * @param name The header name. * @param value The value or values to set or overide for the given header. * * @returns A clone of the HTTP headers object with the newly set header value. */ set(name, value) { return this.clone({ name, value, op: 's' }); } /** * Deletes values for a given header in a clone of the original instance. * * @param name The header name. * @param value The value or values to delete for the given header. * * @returns A clone of the HTTP headers object with the given value deleted. */ delete(name, value) { return this.clone({ name, value, op: 'd' }); } maybeSetNormalizedName(name, lcName) { if (!this.normalizedNames.has(lcName)) { this.normalizedNames.set(lcName, name); } } init() { if (!!this.lazyInit) { if (this.lazyInit instanceof HttpHeaders) { this.copyFrom(this.lazyInit); } else { this.lazyInit(); } this.lazyInit = null; if (!!this.lazyUpdate) { this.lazyUpdate.forEach(update => this.applyUpdate(update)); this.lazyUpdate = null; } } } copyFrom(other) { other.init(); Array.from(other.headers.keys()).forEach(key => { this.headers.set(key, other.headers.get(key)); this.normalizedNames.set(key, other.normalizedNames.get(key)); }); } clone(update) { const clone = new HttpHeaders(); clone.lazyInit = (!!this.lazyInit && this.lazyInit instanceof HttpHeaders) ? this.lazyInit : this; clone.lazyUpdate = (this.lazyUpdate || []).concat([update]); return clone; } applyUpdate(update) { const key = update.name.toLowerCase(); switch (update.op) { case 'a': case 's': let value = update.value; if (typeof value === 'string') { value = [value]; } if (value.length === 0) { return; } this.maybeSetNormalizedName(update.name, key); const base = (update.op === 'a' ? this.headers.get(key) : undefined) || []; base.push(...value); this.headers.set(key, base); break; case 'd': const toDelete = update.value; if (!toDelete) { this.headers.delete(key); this.normalizedNames.delete(key); } else { let existing = this.headers.get(key); if (!existing) { return; } existing = existing.filter(value => toDelete.indexOf(value) === -1); if (existing.length === 0) { this.headers.delete(key); this.normalizedNames.delete(key); } else { this.headers.set(key, existing); } } break; } } /** * @internal */ forEach(fn) { this.init(); Array.from(this.normalizedNames.keys()) .forEach(key => fn(this.normalizedNames.get(key), this.headers.get(key))); } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Provides encoding and decoding of URL parameter and query-string values. * * Serializes and parses URL parameter keys and values to encode and decode them. * If you pass URL query parameters without encoding, * the query parameters can be misinterpreted at the receiving end. * * * @publicApi */ class HttpUrlEncodingCodec { /** * Encodes a key name for a URL parameter or query-string. * @param key The key name. * @returns The encoded key name. */ encodeKey(key) { return standardEncoding(key); } /** * Encodes the value of a URL parameter or query-string. * @param value The value. * @returns The encoded value. */ encodeValue(value) { return standardEncoding(value); } /** * Decodes an encoded URL parameter or query-string key. * @param key The encoded key name. * @returns The decoded key name. */ decodeKey(key) { return decodeURIComponent(key); } /** * Decodes an encoded URL parameter or query-string value. * @param value The encoded value. * @returns The decoded value. */ decodeValue(value) { return decodeURIComponent(value); } } function paramParser(rawParams, codec) { const map = new Map(); if (rawParams.length > 0) { // The `window.location.search` can be used while creating an instance of the `HttpParams` class // (e.g. `new HttpParams({ fromString: window.location.search })`). The `window.location.search` // may start with the `?` char, so we strip it if it's present. const params = rawParams.replace(/^\?/, '').split('&'); params.forEach((param) => { const eqIdx = param.indexOf('='); const [key, val] = eqIdx == -1 ? [codec.decodeKey(param), ''] : [codec.decodeKey(param.slice(0, eqIdx)), codec.decodeValue(param.slice(eqIdx + 1))]; const list = map.get(key) || []; list.push(val); map.set(key, list); }); } return map; } function standardEncoding(v) { return encodeURIComponent(v) .replace(/%40/gi, '@') .replace(/%3A/gi, ':') .replace(/%24/gi, '$') .replace(/%2C/gi, ',') .replace(/%3B/gi, ';') .replace(/%2B/gi, '+') .replace(/%3D/gi, '=') .replace(/%3F/gi, '?') .replace(/%2F/gi, '/'); } function valueToString(value) { return `${value}`; } /** * An HTTP request/response body that represents serialized parameters, * per the MIME type `application/x-www-form-urlencoded`. * * This class is immutable; all mutation operations return a new instance. * * @publicApi */ class HttpParams { constructor(options = {}) { this.updates = null; this.cloneFrom = null; this.encoder = options.encoder || new HttpUrlEncodingCodec(); if (!!options.fromString) { if (!!options.fromObject) { throw new Error(`Cannot specify both fromString and fromObject.`); } this.map = paramParser(options.fromString, this.encoder); } else if (!!options.fromObject) { this.map = new Map(); Object.keys(options.fromObject).forEach(key => { const value = options.fromObject[key]; this.map.set(key, Array.isArray(value) ? value : [value]); }); } else { this.map = null; } } /** * Reports whether the body includes one or more values for a given parameter. * @param param The parameter name. * @returns True if the parameter has one or more values, * false if it has no value or is not present. */ has(param) { this.init(); return this.map.has(param); } /** * Retrieves the first value for a parameter. * @param param The parameter name. * @returns The first value of the given parameter, * or `null` if the parameter is not present. */ get(param) { this.init(); const res = this.map.get(param); return !!res ? res[0] : null; } /** * Retrieves all values for a parameter. * @param param The parameter name. * @returns All values in a string array, * or `null` if the parameter not present. */ getAll(param) { this.init(); return this.map.get(param) || null; } /** * Retrieves all the parameters for this body. * @returns The parameter names in a string array. */ keys() { this.init(); return Array.from(this.map.keys()); } /** * Appends a new value to existing values for a parameter. * @param param The parameter name. * @param value The new value to add. * @return A new body with the appended value. */ append(param, value) { return this.clone({ param, value, op: 'a' }); } /** * Constructs a new body with appended values for the given parameter name. * @param params parameters and values * @return A new body with the new value. */ appendAll(params) { const updates = []; Object.keys(params).forEach(param => { const value = params[param]; if (Array.isArray(value)) { value.forEach(_value => { updates.push({ param, value: _value, op: 'a' }); }); } else { updates.push({ param, value: value, op: 'a' }); } }); return this.clone(updates); } /** * Replaces the value for a parameter. * @param param The parameter name. * @param value The new value. * @return A new body with the new value. */ set(param, value) { return this.clone({ param, value, op: 's' }); } /** * Removes a given value or all values from a parameter. * @param param The parameter name. * @param value The value to remove, if provided. * @return A new body with the given value removed, or with all values * removed if no value is specified. */ delete(param, value) { return this.clone({ param, value, op: 'd' }); } /** * Serializes the body to an encoded string, where key-value pairs (separated by `=`) are * separated by `&`s. */ toString() { this.init(); return this.keys() .map(key => { const eKey = this.encoder.encodeKey(key); // `a: ['1']` produces `'a=1'` // `b: []` produces `''` // `c: ['1', '2']` produces `'c=1&c=2'` return this.map.get(key).map(value => eKey + '=' + this.encoder.encodeValue(value)) .join('&'); }) // filter out empty values because `b: []` produces `''` // which results in `a=1&&c=1&c=2` instead of `a=1&c=1&c=2` if we don't .filter(param => param !== '') .join('&'); } clone(update) { const clone = new HttpParams({ encoder: this.encoder }); clone.cloneFrom = this.cloneFrom || this; clone.updates = (this.updates || []).concat(update); return clone; } init() { if (this.map === null) { this.map = new Map(); } if (this.cloneFrom !== null) { this.cloneFrom.init(); this.cloneFrom.keys().forEach(key => this.map.set(key, this.cloneFrom.map.get(key))); this.updates.forEach(update => { switch (update.op) { case 'a': case 's': const base = (update.op === 'a' ? this.map.get(update.param) : undefined) || []; base.push(valueToString(update.value)); this.map.set(update.param, base); break; case 'd': if (update.value !== undefined) { let base = this.map.get(update.param) || []; const idx = base.indexOf(valueToString(update.value)); if (idx !== -1) { base.splice(idx, 1); } if (base.length > 0) { this.map.set(update.param, base); } else { this.map.delete(update.param); } } else { this.map.delete(update.param); break; } } }); this.cloneFrom = this.updates = null; } } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A token used to manipulate and access values stored in `HttpContext`. * * @publicApi */ class HttpContextToken { constructor(defaultValue) { this.defaultValue = defaultValue; } } /** * Http context stores arbitrary user defined values and ensures type safety without * actually knowing the types. It is backed by a `Map` and guarantees that keys do not clash. * * This context is mutable and is shared between cloned requests unless explicitly specified. * * @usageNotes * * ### Usage Example * * ```typescript * // inside cache.interceptors.ts * export const IS_CACHE_ENABLED = new HttpContextToken(() => false); * * export class CacheInterceptor implements HttpInterceptor { * * intercept(req: HttpRequest, delegate: HttpHandler): Observable> { * if (req.context.get(IS_CACHE_ENABLED) === true) { * return ...; * } * return delegate.handle(req); * } * } * * // inside a service * * this.httpClient.get('/api/weather', { * context: new HttpContext().set(IS_CACHE_ENABLED, true) * }).subscribe(...); * ``` * * @publicApi */ class HttpContext { constructor() { this.map = new Map(); } /** * Store a value in the context. If a value is already present it will be overwritten. * * @param token The reference to an instance of `HttpContextToken`. * @param value The value to store. * * @returns A reference to itself for easy chaining. */ set(token, value) { this.map.set(token, value); return this; } /** * Retrieve the value associated with the given token. * * @param token The reference to an instance of `HttpContextToken`. * * @returns The stored value or default if one is defined. */ get(token) { if (!this.map.has(token)) { this.map.set(token, token.defaultValue()); } return this.map.get(token); } /** * Delete the value associated with the given token. * * @param token The reference to an instance of `HttpContextToken`. * * @returns A reference to itself for easy chaining. */ delete(token) { this.map.delete(token); return this; } /** * @returns a list of tokens currently stored in the context. */ keys() { return this.map.keys(); } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Determine whether the given HTTP method may include a body. */ function mightHaveBody(method) { switch (method) { case 'DELETE': case 'GET': case 'HEAD': case 'OPTIONS': case 'JSONP': return false; default: return true; } } /** * Safely assert whether the given value is an ArrayBuffer. * * In some execution environments ArrayBuffer is not defined. */ function isArrayBuffer(value) { return typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer; } /** * Safely assert whether the given value is a Blob. * * In some execution environments Blob is not defined. */ function isBlob(value) { return typeof Blob !== 'undefined' && value instanceof Blob; } /** * Safely assert whether the given value is a FormData instance. * * In some execution environments FormData is not defined. */ function isFormData(value) { return typeof FormData !== 'undefined' && value instanceof FormData; } /** * An outgoing HTTP request with an optional typed body. * * `HttpRequest` represents an outgoing request, including URL, method, * headers, body, and other request configuration options. Instances should be * assumed to be immutable. To modify a `HttpRequest`, the `clone` * method should be used. * * @publicApi */ class HttpRequest { constructor(method, url, third, fourth) { this.url = url; /** * The request body, or `null` if one isn't set. * * Bodies are not enforced to be immutable, as they can include a reference to any * user-defined data type. However, interceptors should take care to preserve * idempotence by treating them as such. */ this.body = null; /** * Whether this request should be made in a way that exposes progress events. * * Progress events are expensive (change detection runs on each event) and so * they should only be requested if the consumer intends to monitor them. */ this.reportProgress = false; /** * Whether this request should be sent with outgoing credentials (cookies). */ this.withCredentials = false; /** * The expected response type of the server. * * This is used to parse the response appropriately before returning it to * the requestee. */ this.responseType = 'json'; this.method = method.toUpperCase(); // Next, need to figure out which argument holds the HttpRequestInit // options, if any. let options; // Check whether a body argument is expected. The only valid way to omit // the body argument is to use a known no-body method like GET. if (mightHaveBody(this.method) || !!fourth) { // Body is the third argument, options are the fourth. this.body = (third !== undefined) ? third : null; options = fourth; } else { // No body required, options are the third argument. The body stays null. options = third; } // If options have been passed, interpret them. if (options) { // Normalize reportProgress and withCredentials. this.reportProgress = !!options.reportProgress; this.withCredentials = !!options.withCredentials; // Override default response type of 'json' if one is provided. if (!!options.responseType) { this.responseType = options.responseType; } // Override headers if they're provided. if (!!options.headers) { this.headers = options.headers; } if (!!options.context) { this.context = options.context; } if (!!options.params) { this.params = options.params; } } // If no headers have been passed in, construct a new HttpHeaders instance. if (!this.headers) { this.headers = new HttpHeaders(); } // If no context have been passed in, construct a new HttpContext instance. if (!this.context) { this.context = new HttpContext(); } // If no parameters have been passed in, construct a new HttpUrlEncodedParams instance. if (!this.params) { this.params = new HttpParams(); this.urlWithParams = url; } else { // Encode the parameters to a string in preparation for inclusion in the URL. const params = this.params.toString(); if (params.length === 0) { // No parameters, the visible URL is just the URL given at creation time. this.urlWithParams = url; } else { // Does the URL already have query parameters? Look for '?'. const qIdx = url.indexOf('?'); // There are 3 cases to handle: // 1) No existing parameters -> append '?' followed by params. // 2) '?' exists and is followed by existing query string -> // append '&' followed by params. // 3) '?' exists at the end of the url -> append params directly. // This basically amounts to determining the character, if any, with // which to join the URL and parameters. const sep = qIdx === -1 ? '?' : (qIdx < url.length - 1 ? '&' : ''); this.urlWithParams = url + sep + params; } } } /** * Transform the free-form body into a serialized format suitable for * transmission to the server. */ serializeBody() { // If no body is present, no need to serialize it. if (this.body === null) { return null; } // Check whether the body is already in a serialized form. If so, // it can just be returned directly. if (isArrayBuffer(this.body) || isBlob(this.body) || isFormData(this.body) || typeof this.body === 'string') { return this.body; } // Check whether the body is an instance of HttpUrlEncodedParams. if (this.body instanceof HttpParams) { return this.body.toString(); } // Check whether the body is an object or array, and serialize with JSON if so. if (typeof this.body === 'object' || typeof this.body === 'boolean' || Array.isArray(this.body)) { return JSON.stringify(this.body); } // Fall back on toString() for everything else. return this.body.toString(); } /** * Examine the body and attempt to infer an appropriate MIME type * for it. * * If no such type can be inferred, this method will return `null`. */ detectContentTypeHeader() { // An empty body has no content type. if (this.body === null) { return null; } // FormData bodies rely on the browser's content type assignment. if (isFormData(this.body)) { return null; } // Blobs usually have their own content type. If it doesn't, then // no type can be inferred. if (isBlob(this.body)) { return this.body.type || null; } // Array buffers have unknown contents and thus no type can be inferred. if (isArrayBuffer(this.body)) { return null; } // Technically, strings could be a form of JSON data, but it's safe enough // to assume they're plain strings. if (typeof this.body === 'string') { return 'text/plain'; } // `HttpUrlEncodedParams` has its own content-type. if (this.body instanceof HttpParams) { return 'application/x-www-form-urlencoded;charset=UTF-8'; } // Arrays, objects, boolean and numbers will be encoded as JSON. if (typeof this.body === 'object' || typeof this.body === 'number' || typeof this.body === 'boolean') { return 'application/json'; } // No type could be inferred. return null; } clone(update = {}) { var _a; // For method, url, and responseType, take the current value unless // it is overridden in the update hash. const method = update.method || this.method; const url = update.url || this.url; const responseType = update.responseType || this.responseType; // The body is somewhat special - a `null` value in update.body means // whatever current body is present is being overridden with an empty // body, whereas an `undefined` value in update.body implies no // override. const body = (update.body !== undefined) ? update.body : this.body; // Carefully handle the boolean options to differentiate between // `false` and `undefined` in the update args. const withCredentials = (update.withCredentials !== undefined) ? update.withCredentials : this.withCredentials; const reportProgress = (update.reportProgress !== undefined) ? update.reportProgress : this.reportProgress; // Headers and params may be appended to if `setHeaders` or // `setParams` are used. let headers = update.headers || this.headers; let params = update.params || this.params; // Pass on context if needed const context = (_a = update.context) !== null && _a !== void 0 ? _a : this.context; // Check whether the caller has asked to add headers. if (update.setHeaders !== undefined) { // Set every requested header. headers = Object.keys(update.setHeaders) .reduce((headers, name) => headers.set(name, update.setHeaders[name]), headers); } // Check whether the caller has asked to set params. if (update.setParams) { // Set every requested param. params = Object.keys(update.setParams) .reduce((params, param) => params.set(param, update.setParams[param]), params); } // Finally, construct the new HttpRequest using the pieces from above. return new HttpRequest(method, url, body, { params, headers, context, reportProgress, responseType, withCredentials, }); } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Type enumeration for the different kinds of `HttpEvent`. * * @publicApi */ var HttpEventType; (function (HttpEventType) { /** * The request was sent out over the wire. */ HttpEventType[HttpEventType["Sent"] = 0] = "Sent"; /** * An upload progress event was received. */ HttpEventType[HttpEventType["UploadProgress"] = 1] = "UploadProgress"; /** * The response status code and headers were received. */ HttpEventType[HttpEventType["ResponseHeader"] = 2] = "ResponseHeader"; /** * A download progress event was received. */ HttpEventType[HttpEventType["DownloadProgress"] = 3] = "DownloadProgress"; /** * The full response including the body was received. */ HttpEventType[HttpEventType["Response"] = 4] = "Response"; /** * A custom event from an interceptor or a backend. */ HttpEventType[HttpEventType["User"] = 5] = "User"; })(HttpEventType || (HttpEventType = {})); /** * Base class for both `HttpResponse` and `HttpHeaderResponse`. * * @publicApi */ class HttpResponseBase { /** * Super-constructor for all responses. * * The single parameter accepted is an initialization hash. Any properties * of the response passed there will override the default values. */ constructor(init, defaultStatus = 200 /* Ok */, defaultStatusText = 'OK') { // If the hash has values passed, use them to initialize the response. // Otherwise use the default values. this.headers = init.headers || new HttpHeaders(); this.status = init.status !== undefined ? init.status : defaultStatus; this.statusText = init.statusText || defaultStatusText; this.url = init.url || null; // Cache the ok value to avoid defining a getter. this.ok = this.status >= 200 && this.status < 300; } } /** * A partial HTTP response which only includes the status and header data, * but no response body. * * `HttpHeaderResponse` is a `HttpEvent` available on the response * event stream, only when progress events are requested. * * @publicApi */ class HttpHeaderResponse extends HttpResponseBase { /** * Create a new `HttpHeaderResponse` with the given parameters. */ constructor(init = {}) { super(init); this.type = HttpEventType.ResponseHeader; } /** * Copy this `HttpHeaderResponse`, overriding its contents with the * given parameter hash. */ clone(update = {}) { // Perform a straightforward initialization of the new HttpHeaderResponse, // overriding the current parameters with new ones if given. return new HttpHeaderResponse({ headers: update.headers || this.headers, status: update.status !== undefined ? update.status : this.status, statusText: update.statusText || this.statusText, url: update.url || this.url || undefined, }); } } /** * A full HTTP response, including a typed response body (which may be `null` * if one was not returned). * * `HttpResponse` is a `HttpEvent` available on the response event * stream. * * @publicApi */ class HttpResponse extends HttpResponseBase { /** * Construct a new `HttpResponse`. */ constructor(init = {}) { super(init); this.type = HttpEventType.Response; this.body = init.body !== undefined ? init.body : null; } clone(update = {}) { return new HttpResponse({ body: (update.body !== undefined) ? update.body : this.body, headers: update.headers || this.headers, status: (update.status !== undefined) ? update.status : this.status, statusText: update.statusText || this.statusText, url: update.url || this.url || undefined, }); } } /** * A response that represents an error or failure, either from a * non-successful HTTP status, an error while executing the request, * or some other failure which occurred during the parsing of the response. * * Any error returned on the `Observable` response stream will be * wrapped in an `HttpErrorResponse` to provide additional context about * the state of the HTTP layer when the error occurred. The error property * will contain either a wrapped Error object or the error response returned * from the server. * * @publicApi */ class HttpErrorResponse extends HttpResponseBase { constructor(init) { // Initialize with a default status of 0 / Unknown Error. super(init, 0, 'Unknown Error'); this.name = 'HttpErrorResponse'; /** * Errors are never okay, even when the status code is in the 2xx success range. */ this.ok = false; // If the response was successful, then this was a parse error. Otherwise, it was // a protocol-level failure of some sort. Either the request failed in transit // or the server returned an unsuccessful status code. if (this.status >= 200 && this.status < 300) { this.message = `Http failure during parsing for ${init.url || '(unknown url)'}`; } else { this.message = `Http failure response for ${init.url || '(unknown url)'}: ${init.status} ${init.statusText}`; } this.error = init.error || null; } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Constructs an instance of `HttpRequestOptions` from a source `HttpMethodOptions` and * the given `body`. This function clones the object and adds the body. * * Note that the `responseType` *options* value is a String that identifies the * single data type of the response. * A single overload version of the method handles each response type. * The value of `responseType` cannot be a union, as the combined signature could imply. * */ function addBody(options, body) { return { body, headers: options.headers, context: options.context, observe: options.observe, params: options.params, reportProgress: options.reportProgress, responseType: options.responseType, withCredentials: options.withCredentials, }; } /** * Performs HTTP requests. * This service is available as an injectable class, with methods to perform HTTP requests. * Each request method has multiple signatures, and the return type varies based on * the signature that is called (mainly the values of `observe` and `responseType`). * * Note that the `responseType` *options* value is a String that identifies the * single data type of the response. * A single overload version of the method handles each response type. * The value of `responseType` cannot be a union, as the combined signature could imply. * * @usageNotes * Sample HTTP requests for the [Tour of Heroes](/tutorial/toh-pt0) application. * * ### HTTP Request Example * * ``` * // GET heroes whose name contains search term * searchHeroes(term: string): observable{ * * const params = new HttpParams({fromString: 'name=term'}); * return this.httpClient.request('GET', this.heroesUrl, {responseType:'json', params}); * } * ``` * * Alternatively, the parameter string can be used without invoking HttpParams * by directly joining to the URL. * ``` * this.httpClient.request('GET', this.heroesUrl + '?' + 'name=term', {responseType:'json'}); * ``` * * * ### JSONP Example * ``` * requestJsonp(url, callback = 'callback') { * return this.httpClient.jsonp(this.heroesURL, callback); * } * ``` * * ### PATCH Example * ``` * // PATCH one of the heroes' name * patchHero (id: number, heroName: string): Observable<{}> { * const url = `${this.heroesUrl}/${id}`; // PATCH api/heroes/42 * return this.httpClient.patch(url, {name: heroName}, httpOptions) * .pipe(catchError(this.handleError('patchHero'))); * } * ``` * * @see [HTTP Guide](guide/http) * @see [HTTP Request](api/common/http/HttpRequest) * * @publicApi */ class HttpClient { constructor(handler) { this.handler = handler; } /** * Constructs an observable for a generic HTTP request that, when subscribed, * fires the request through the chain of registered interceptors and on to the * server. * * You can pass an `HttpRequest` directly as the only parameter. In this case, * the call returns an observable of the raw `HttpEvent` stream. * * Alternatively you can pass an HTTP method as the first parameter, * a URL string as the second, and an options hash containing the request body as the third. * See `addBody()`. In this case, the specified `responseType` and `observe` options determine the * type of returned observable. * * The `responseType` value determines how a successful response body is parsed. * * If `responseType` is the default `json`, you can pass a type interface for the resulting * object as a type parameter to the call. * * The `observe` value determines the return type, according to what you are interested in * observing. * * An `observe` value of events returns an observable of the raw `HttpEvent` stream, including * progress events by default. * * An `observe` value of response returns an observable of `HttpResponse`, * where the `T` parameter depends on the `responseType` and any optionally provided type * parameter. * * An `observe` value of body returns an observable of `` with the same `T` body type. * */ request(first, url, options = {}) { let req; // First, check whether the primary argument is an instance of `HttpRequest`. if (first instanceof HttpRequest) { // It is. The other arguments must be undefined (per the signatures) and can be // ignored. req = first; } else { // It's a string, so it represents a URL. Construct a request based on it, // and incorporate the remaining arguments (assuming `GET` unless a method is // provided. // Figure out the headers. let headers = undefined; if (options.headers instanceof HttpHeaders) { headers = options.headers; } else { headers = new HttpHeaders(options.headers); } // Sort out parameters. let params = undefined; if (!!options.params) { if (options.params instanceof HttpParams) { params = options.params; } else { params = new HttpParams({ fromObject: options.params }); } } // Construct the request. req = new HttpRequest(first, url, (options.body !== undefined ? options.body : null), { headers, context: options.context, params, reportProgress: options.reportProgress, // By default, JSON is assumed to be returned for all calls. responseType: options.responseType || 'json', withCredentials: options.withCredentials, }); } // Start with an Observable.of() the initial request, and run the handler (which // includes all interceptors) inside a concatMap(). This way, the handler runs // inside an Observable chain, which causes interceptors to be re-run on every // subscription (this also makes retries re-run the handler, including interceptors). const events$ = (0,rxjs__WEBPACK_IMPORTED_MODULE_0__.of)(req).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_1__.concatMap)((req) => this.handler.handle(req))); // If coming via the API signature which accepts a previously constructed HttpRequest, // the only option is to get the event stream. Otherwise, return the event stream if // that is what was requested. if (first instanceof HttpRequest || options.observe === 'events') { return events$; } // The requested stream contains either the full response or the body. In either // case, the first step is to filter the event stream to extract a stream of // responses(s). const res$ = events$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_2__.filter)((event) => event instanceof HttpResponse)); // Decide which stream to return. switch (options.observe || 'body') { case 'body': // The requested stream is the body. Map the response stream to the response // body. This could be done more simply, but a misbehaving interceptor might // transform the response body into a different format and ignore the requested // responseType. Guard against this by validating that the response is of the // requested type. switch (req.responseType) { case 'arraybuffer': return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)((res) => { // Validate that the body is an ArrayBuffer. if (res.body !== null && !(res.body instanceof ArrayBuffer)) { throw new Error('Response is not an ArrayBuffer.'); } return res.body; })); case 'blob': return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)((res) => { // Validate that the body is a Blob. if (res.body !== null && !(res.body instanceof Blob)) { throw new Error('Response is not a Blob.'); } return res.body; })); case 'text': return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)((res) => { // Validate that the body is a string. if (res.body !== null && typeof res.body !== 'string') { throw new Error('Response is not a string.'); } return res.body; })); case 'json': default: // No validation needed for JSON responses, as they can be of any type. return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)((res) => res.body)); } case 'response': // The response stream was requested directly, so return it. return res$; default: // Guard against new future observe types being added. throw new Error(`Unreachable: unhandled observe type ${options.observe}}`); } } /** * Constructs an observable that, when subscribed, causes the configured * `DELETE` request to execute on the server. See the individual overloads for * details on the return type. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * */ delete(url, options = {}) { return this.request('DELETE', url, options); } /** * Constructs an observable that, when subscribed, causes the configured * `GET` request to execute on the server. See the individual overloads for * details on the return type. */ get(url, options = {}) { return this.request('GET', url, options); } /** * Constructs an observable that, when subscribed, causes the configured * `HEAD` request to execute on the server. The `HEAD` method returns * meta information about the resource without transferring the * resource itself. See the individual overloads for * details on the return type. */ head(url, options = {}) { return this.request('HEAD', url, options); } /** * Constructs an `Observable` that, when subscribed, causes a request with the special method * `JSONP` to be dispatched via the interceptor pipeline. * The [JSONP pattern](https://en.wikipedia.org/wiki/JSONP) works around limitations of certain * API endpoints that don't support newer, * and preferable [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) protocol. * JSONP treats the endpoint API as a JavaScript file and tricks the browser to process the * requests even if the API endpoint is not located on the same domain (origin) as the client-side * application making the request. * The endpoint API must support JSONP callback for JSONP requests to work. * The resource API returns the JSON response wrapped in a callback function. * You can pass the callback function name as one of the query parameters. * Note that JSONP requests can only be used with `GET` requests. * * @param url The resource URL. * @param callbackParam The callback function name. * */ jsonp(url, callbackParam) { return this.request('JSONP', url, { params: new HttpParams().append(callbackParam, 'JSONP_CALLBACK'), observe: 'body', responseType: 'json', }); } /** * Constructs an `Observable` that, when subscribed, causes the configured * `OPTIONS` request to execute on the server. This method allows the client * to determine the supported HTTP methods and other capabilites of an endpoint, * without implying a resource action. See the individual overloads for * details on the return type. */ options(url, options = {}) { return this.request('OPTIONS', url, options); } /** * Constructs an observable that, when subscribed, causes the configured * `PATCH` request to execute on the server. See the individual overloads for * details on the return type. */ patch(url, body, options = {}) { return this.request('PATCH', url, addBody(options, body)); } /** * Constructs an observable that, when subscribed, causes the configured * `POST` request to execute on the server. The server responds with the location of * the replaced resource. See the individual overloads for * details on the return type. */ post(url, body, options = {}) { return this.request('POST', url, addBody(options, body)); } /** * Constructs an observable that, when subscribed, causes the configured * `PUT` request to execute on the server. The `PUT` method replaces an existing resource * with a new set of values. * See the individual overloads for details on the return type. */ put(url, body, options = {}) { return this.request('PUT', url, addBody(options, body)); } } HttpClient.ɵfac = function HttpClient_Factory(t) { return new (t || HttpClient)(_angular_core__WEBPACK_IMPORTED_MODULE_4__["ɵɵinject"](HttpHandler)); }; HttpClient.ɵprov = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_4__["ɵɵdefineInjectable"]({ token: HttpClient, factory: HttpClient.ɵfac }); HttpClient.ctorParameters = () => [ { type: HttpHandler } ]; (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_4__["ɵsetClassMetadata"](HttpClient, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_4__.Injectable }], function () { return [{ type: HttpHandler }]; }, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * `HttpHandler` which applies an `HttpInterceptor` to an `HttpRequest`. * * */ class HttpInterceptorHandler { constructor(next, interceptor) { this.next = next; this.interceptor = interceptor; } handle(req) { return this.interceptor.intercept(req, this.next); } } /** * A multi-provider token that represents the array of registered * `HttpInterceptor` objects. * * @publicApi */ const HTTP_INTERCEPTORS = new _angular_core__WEBPACK_IMPORTED_MODULE_4__.InjectionToken('HTTP_INTERCEPTORS'); class NoopInterceptor { intercept(req, next) { return next.handle(req); } } NoopInterceptor.ɵfac = function NoopInterceptor_Factory(t) { return new (t || NoopInterceptor)(); }; NoopInterceptor.ɵprov = /*@__PURE__*/ _angular_core__WEBPACK_IMPORTED_MODULE_4__["ɵɵdefineInjectable"]({ token: NoopInterceptor, factory: NoopInterceptor.ɵfac }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && _angular_core__WEBPACK_IMPORTED_MODULE_4__["ɵsetClassMetadata"](NoopInterceptor, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_4__.Injectable }], null, null); })(); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // Every request made through JSONP needs a callback name that's unique across the // whole page. Each request is assigned an id and the callback name is constructed // from that. The next id to be assigned is tracked in a global variable here that // is shared among all applications on the page. let nextRequestId = 0; // Error text given when a JSONP script is injected, but doesn't invoke the callback // passed in its URL. const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.'; // Error text given when a request is passed to the JsonpClientBackend that doesn't // have a request method JSONP. const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use JSONP request method.'; const JSONP_ERR_WRONG_RESPONSE_TYPE = 'JSONP requests must use Json response type.'; /** * DI token/abstract type representing a map of JSONP callbacks. * * In the browser, this should always be the `window` object. * * */ class JsonpCallbackContext { } /** * Processes an `HttpRequest` with the JSONP method, * by performing JSONP style requests. * @see `HttpHandler` * @see `HttpXhrBackend` * * @publicApi */ class JsonpClientBackend { constructor(callbackMap, document) { this.callbackMap = callbackMap; this.document = document; /** * A resolved promise that can be used to schedule microtasks in the event handlers. */ this.resolvedPromise = Promise.resolve(); } /** * Get the name of the next callback method, by incrementing the global `nextRequestId`. */ nextCallback() { return `ng_jsonp_callback_${nextRequestId++}`; } /** * Processes a JSONP request and returns an event stream of the results. * @param req The request object. * @returns An observable of the response events. * */ handle(req) { // Firstly, check both the method and response type. If either doesn't match // then the request was improperly routed here and cannot be handled. if (req.method !== 'JSONP') { throw new Error(JSONP_ERR_WRONG_METHOD); } else if (req.responseType !== 'json') { throw new Error(JSONP_ERR_WRONG_RESPONSE_TYPE); } // Everything else happens inside the Observable boundary. return new rxjs__WEBPACK_IMPORTED_MODULE_5__.Observable((observer) => { // The first step to make a request is to generate the callback name, and replace the // callback placeholder in the URL with the name. Care has to be taken here to ensure // a trailing &, if matched, gets inserted back into the URL in the correct place. const callback = this.nextCallback(); const url = req.urlWithParams.replace(/=JSONP_CALLBACK(&|$)/, `=${callback}$1`); // Construct the