@machinomy/hdwallet-provider
Version:
HD Wallet-enabled Web3 provider
75 lines • 2.95 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PollingBlockTracker = void 0;
const base_1 = require("./base");
const util_1 = require("../util");
class PollingBlockTracker extends base_1.BaseBlockTracker {
constructor(opts) {
// parse + validate args
if (!opts.provider)
throw new Error("PollingBlockTracker - no provider specified.");
const pollingInterval = opts.pollingInterval || 20 * base_1.SECOND;
const retryTimeout = opts.retryTimeout || pollingInterval / 10;
const keepEventLoopActive = opts.keepEventLoopActive !== undefined ? opts.keepEventLoopActive : true;
const setSkipCacheFlag = opts.setSkipCacheFlag || false;
// BaseBlockTracker constructor
super(Object.assign({
blockResetDuration: pollingInterval
}, opts));
// config
this._provider = opts.provider;
this._pollingInterval = pollingInterval;
this._retryTimeout = retryTimeout;
this._keepEventLoopActive = keepEventLoopActive;
this._setSkipCacheFlag = setSkipCacheFlag;
}
// trigger block polling
async checkForLatestBlock() {
await this._updateLatestBlock();
return await this.getLatestBlock();
}
_start() {
this._performSync().catch(err => this.emit("error", err));
}
_end() {
// Noop
}
async _performSync() {
while (this.isRunning()) {
try {
await this._updateLatestBlock();
await util_1.timeout(this._pollingInterval, !this._keepEventLoopActive);
}
catch (err) {
const newErr = new Error(`PollingBlockTracker - encountered an error while attempting to update latest block:\n${err.stack}`);
try {
this.emit("error", newErr);
}
catch (emitErr) {
console.error(newErr);
}
await util_1.timeout(this._retryTimeout, !this._keepEventLoopActive);
}
}
}
async _updateLatestBlock() {
// fetch + set latest block
const latestBlock = await this._fetchLatestBlock();
this._newPotentialLatest(latestBlock);
}
async _fetchLatestBlock() {
const req = { jsonrpc: "2.0", id: 1, method: "eth_blockNumber", params: [], skipCache: false };
if (this._setSkipCacheFlag)
req.skipCache = true;
const res = await new Promise(((resolve, reject) => {
this._provider.sendAsync(req, (err, result) => {
return err ? reject(err) : resolve(result);
});
}));
if (res.error)
throw new Error(`PollingBlockTracker - encountered error fetching block:\n${res.error}`);
return res.result;
}
}
exports.PollingBlockTracker = PollingBlockTracker;
//# sourceMappingURL=polling.js.map