-
Notifications
You must be signed in to change notification settings - Fork 31
/
62644.b8ba4100.iframe.bundle.js.map
1 lines (1 loc) · 9.28 KB
/
62644.b8ba4100.iframe.bundle.js.map
1
{"version":3,"file":"62644.b8ba4100.iframe.bundle.js","mappings":";AAoMA;AAeA","sources":["webpack://metamask-crx/./node_modules/@metamask/eth-token-tracker/node_modules/@metamask/eth-block-tracker/dist/PollingBlockTracker.js"],"sourcesContent":["\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PollingBlockTracker = void 0;\nconst safe_event_emitter_1 = __importDefault(require(\"@metamask/safe-event-emitter\"));\nconst json_rpc_random_id_1 = __importDefault(require(\"json-rpc-random-id\"));\nconst pify_1 = __importDefault(require(\"pify\"));\nconst logging_utils_1 = require(\"./logging-utils\");\nconst log = (0, logging_utils_1.createModuleLogger)(logging_utils_1.projectLogger, 'polling-block-tracker');\nconst createRandomId = (0, json_rpc_random_id_1.default)();\nconst sec = 1000;\nconst calculateSum = (accumulator, currentValue) => accumulator + currentValue;\nconst blockTrackerEvents = ['sync', 'latest'];\nclass PollingBlockTracker extends safe_event_emitter_1.default {\n constructor(opts = {}) {\n // parse + validate args\n if (!opts.provider) {\n throw new Error('PollingBlockTracker - no provider specified.');\n }\n super();\n // config\n this._blockResetDuration = opts.blockResetDuration || 20 * sec;\n this._usePastBlocks = opts.usePastBlocks || false;\n // state\n this._currentBlock = null;\n this._isRunning = false;\n // bind functions for internal use\n this._onNewListener = this._onNewListener.bind(this);\n this._onRemoveListener = this._onRemoveListener.bind(this);\n this._resetCurrentBlock = this._resetCurrentBlock.bind(this);\n // listen for handler changes\n this._setupInternalEvents();\n // config\n this._provider = opts.provider;\n this._pollingInterval = opts.pollingInterval || 20 * sec;\n this._retryTimeout = opts.retryTimeout || this._pollingInterval / 10;\n this._keepEventLoopActive =\n opts.keepEventLoopActive === undefined ? true : opts.keepEventLoopActive;\n this._setSkipCacheFlag = opts.setSkipCacheFlag || false;\n }\n async destroy() {\n this._cancelBlockResetTimeout();\n this._maybeEnd();\n super.removeAllListeners();\n }\n isRunning() {\n return this._isRunning;\n }\n getCurrentBlock() {\n return this._currentBlock;\n }\n async getLatestBlock() {\n // return if available\n if (this._currentBlock) {\n return this._currentBlock;\n }\n // wait for a new latest block\n const latestBlock = await new Promise((resolve) => this.once('latest', resolve));\n // return newly set current block\n return latestBlock;\n }\n // dont allow module consumer to remove our internal event listeners\n removeAllListeners(eventName) {\n // perform default behavior, preserve fn arity\n if (eventName) {\n super.removeAllListeners(eventName);\n }\n else {\n super.removeAllListeners();\n }\n // re-add internal events\n this._setupInternalEvents();\n // trigger stop check just in case\n this._onRemoveListener();\n return this;\n }\n _setupInternalEvents() {\n // first remove listeners for idempotence\n this.removeListener('newListener', this._onNewListener);\n this.removeListener('removeListener', this._onRemoveListener);\n // then add them\n this.on('newListener', this._onNewListener);\n this.on('removeListener', this._onRemoveListener);\n }\n _onNewListener(eventName) {\n // `newListener` is called *before* the listener is added\n if (blockTrackerEvents.includes(eventName)) {\n // TODO: Handle dangling promise\n this._maybeStart();\n }\n }\n _onRemoveListener() {\n // `removeListener` is called *after* the listener is removed\n if (this._getBlockTrackerEventCount() > 0) {\n return;\n }\n this._maybeEnd();\n }\n _maybeStart() {\n if (this._isRunning) {\n return;\n }\n this._isRunning = true;\n // cancel setting latest block to stale\n this._cancelBlockResetTimeout();\n this._start();\n this.emit('_started');\n }\n _maybeEnd() {\n if (!this._isRunning) {\n return;\n }\n this._isRunning = false;\n this._setupBlockResetTimeout();\n this._end();\n this.emit('_ended');\n }\n _getBlockTrackerEventCount() {\n return blockTrackerEvents\n .map((eventName) => this.listenerCount(eventName))\n .reduce(calculateSum);\n }\n _shouldUseNewBlock(newBlock) {\n const currentBlock = this._currentBlock;\n if (!currentBlock) {\n return true;\n }\n const newBlockInt = hexToInt(newBlock);\n const currentBlockInt = hexToInt(currentBlock);\n return ((this._usePastBlocks && newBlockInt < currentBlockInt) ||\n newBlockInt > currentBlockInt);\n }\n _newPotentialLatest(newBlock) {\n if (!this._shouldUseNewBlock(newBlock)) {\n return;\n }\n this._setCurrentBlock(newBlock);\n }\n _setCurrentBlock(newBlock) {\n const oldBlock = this._currentBlock;\n this._currentBlock = newBlock;\n this.emit('latest', newBlock);\n this.emit('sync', { oldBlock, newBlock });\n }\n _setupBlockResetTimeout() {\n // clear any existing timeout\n this._cancelBlockResetTimeout();\n // clear latest block when stale\n this._blockResetTimeout = setTimeout(this._resetCurrentBlock, this._blockResetDuration);\n // nodejs - dont hold process open\n if (this._blockResetTimeout.unref) {\n this._blockResetTimeout.unref();\n }\n }\n _cancelBlockResetTimeout() {\n if (this._blockResetTimeout) {\n clearTimeout(this._blockResetTimeout);\n }\n }\n _resetCurrentBlock() {\n this._currentBlock = null;\n }\n // trigger block polling\n async checkForLatestBlock() {\n await this._updateLatestBlock();\n return await this.getLatestBlock();\n }\n _start() {\n // Intentionally not awaited as this starts the polling via a timeout chain.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._updateAndQueue();\n }\n _end() {\n this._clearPollingTimeout();\n }\n async _updateLatestBlock() {\n // fetch + set latest block\n const latestBlock = await this._fetchLatestBlock();\n this._newPotentialLatest(latestBlock);\n }\n async _fetchLatestBlock() {\n const req = {\n jsonrpc: '2.0',\n id: createRandomId(),\n method: 'eth_blockNumber',\n params: [],\n };\n if (this._setSkipCacheFlag) {\n req.skipCache = true;\n }\n log('Making request', req);\n const res = await (0, pify_1.default)((cb) => this._provider.sendAsync(req, cb))();\n log('Got response', res);\n if (res.error) {\n throw new Error(`PollingBlockTracker - encountered error fetching block:\\n${res.error.message}`);\n }\n return res.result;\n }\n /**\n * The core polling function that runs after each interval.\n * Updates the latest block and then queues the next update.\n */\n async _updateAndQueue() {\n var _a;\n let interval = this._pollingInterval;\n try {\n await this._updateLatestBlock();\n }\n catch (err) {\n const newErr = new Error(`PollingBlockTracker - encountered an error while attempting to update latest block:\\n${(_a = err.stack) !== null && _a !== void 0 ? _a : err}`);\n try {\n this.emit('error', newErr);\n }\n catch (emitErr) {\n console.error(newErr);\n }\n interval = this._retryTimeout;\n }\n if (!this._isRunning) {\n return;\n }\n this._clearPollingTimeout();\n const timeoutRef = setTimeout(() => {\n // Intentionally not awaited as this just continues the polling loop.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._updateAndQueue();\n }, interval);\n if (timeoutRef.unref && !this._keepEventLoopActive) {\n timeoutRef.unref();\n }\n this._pollingTimeout = timeoutRef;\n this.emit('_waitingForNextIteration');\n }\n _clearPollingTimeout() {\n if (this._pollingTimeout) {\n clearTimeout(this._pollingTimeout);\n this._pollingTimeout = undefined;\n }\n }\n}\nexports.PollingBlockTracker = PollingBlockTracker;\n/**\n * Converts a number represented as a string in hexadecimal format into a native\n * number.\n *\n * @param hexInt - The hex string.\n * @returns The number.\n */\nfunction hexToInt(hexInt) {\n return Number.parseInt(hexInt, 16);\n}\n//# sourceMappingURL=PollingBlockTracker.js.map"],"names":[],"sourceRoot":""}