UNPKG

@lifi/rpc-wrapper

Version:
38 lines (37 loc) 1.52 kB
import * as providers from '@ethersproject/providers'; export 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; } } }