UNPKG

@parity/api

Version:

The Parity Promise-based API library for interfacing with Ethereum over RPC

88 lines (87 loc) 3.32 kB
"use strict"; // Copyright 2015-2019 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. var BigNumber = require('bignumber.js'); var Eth = /** @class */ (function () { function Eth(updateSubscriptions, api) { var _this = this; this._api = api; this._updateSubscriptions = updateSubscriptions; this._started = false; this._lastBlock = new BigNumber(-1); this._pollTimerId = null; this._pollBlockNumber = this._pollBlockNumber.bind(this); this._api.provider.on('close', function () { if (_this.isStarted) { _this.start(); } }); } Object.defineProperty(Eth.prototype, "isStarted", { get: function () { return this._started; }, enumerable: true, configurable: true }); Eth.prototype.start = function () { var _this = this; this._started = true; if (this._api.isPubSub) { return Promise.all([ this._pollBlockNumber(false), this._api.pubsub .subscribeAndGetResult(function (callback) { return _this._api.pubsub.eth.newHeads(callback); }, function () { return _this._api.eth .blockNumber() .then(function (blockNumber) { _this.updateBlock(blockNumber); return blockNumber; }); }) ]); } return this._pollBlockNumber(true); }; Eth.prototype._pollBlockNumber = function (doTimeout) { var _this = this; var nextTimeout = function (timeout, forceTimeout) { if (timeout === void 0) { timeout = 1000; } if (forceTimeout === void 0) { forceTimeout = doTimeout; } if (forceTimeout) { _this._pollTimerId = setTimeout(function () { _this._pollBlockNumber(doTimeout); }, timeout); } }; if (!this._api.provider.isConnected) { nextTimeout(500, true); return; } return this._api.eth .blockNumber() .then(function (blockNumber) { _this.updateBlock(blockNumber); nextTimeout(); }) .catch(function () { return nextTimeout(); }); }; Eth.prototype.updateBlock = function (blockNumber) { if (!blockNumber.eq(this._lastBlock)) { this._lastBlock = blockNumber; this._updateSubscriptions('eth_blockNumber', null, blockNumber); } }; return Eth; }()); module.exports = Eth;