UNPKG

@lifi/rpc-wrapper

Version:
65 lines (64 loc) 2.71 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (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.RPCProviderCache = void 0; const providers = __importStar(require("@ethersproject/providers")); class RPCProviderCache { constructor(cacheTTL, pollingInterval) { this.cacheTTL = 60 * 60 * 24 * 1000; // ms, defaults to a day this.pollingInterval = 8000; // number of ms between polling getBlockNumbers this.providerCache = {}; if (cacheTTL) this.cacheTTL = cacheTTL; if (pollingInterval) this.pollingInterval = pollingInterval; } /** * getProvider is a wrapper around getting a provider. It's mainly repsonsible for * writing and reading from the providerCache. This reduces the setup time for each provider. * @param providerConfig<string> - the configuration, currently a string * @returns a StaticJsonRpcProvider */ getProvider(providerConfig) { // create hash of providerConfig const hash = providerConfig; const providerCache = this.providerCache[hash]; const timestampMs = Date.now(); if (providerCache && providerCache.expiresAt > timestampMs) { return providerCache.provider; } else { const provider = new providers.StaticJsonRpcProvider(providerConfig); provider._pollingInterval = this.pollingInterval; const providerCacheObject = { provider, expiresAt: timestampMs + this.cacheTTL, }; this.providerCache[hash] = providerCacheObject; return provider; } } } exports.RPCProviderCache = RPCProviderCache;