diff --git a/packages/rpc-provider/src/http/index.spec.ts b/packages/rpc-provider/src/http/index.spec.ts index fc19049d91..00e85c6d3e 100644 --- a/packages/rpc-provider/src/http/index.spec.ts +++ b/packages/rpc-provider/src/http/index.spec.ts @@ -31,6 +31,16 @@ describe('Http', (): void => { ).not.toThrow(); }); + it('should throw error on negative cache capacity or TTL', () => { + expect(() => + new HttpProvider(TEST_HTTP_URL, {}, -5, 30000) + ).toThrow(/'capacity' must be a non-negative integer/); + + expect(() => + new HttpProvider(TEST_HTTP_URL, {}, 1024, -1000) + ).toThrow(/'ttl' must be between 0 and 1800000 ms or null to disable/); + }); + it('allow clone', (): void => { const clone = http.clone(); /* eslint-disable */ diff --git a/packages/rpc-provider/src/lru.ts b/packages/rpc-provider/src/lru.ts index 3c644be548..cac27f4730 100644 --- a/packages/rpc-provider/src/lru.ts +++ b/packages/rpc-provider/src/lru.ts @@ -6,7 +6,8 @@ // for Kusama/Polkadot/Substrate falls between 600-750K, 2x for estimate) export const DEFAULT_CAPACITY = 1024; -export const DEFAULT_TTL = 30000; +export const DEFAULT_TTL = 30000; // 30 seconds +const MAX_TTL = 1800_000; // 30 minutes // If the user decides to disable the TTL we set the value // to a very high number (A year = 365 * 24 * 60 * 60 * 1000). @@ -52,6 +53,16 @@ export class LRUCache { readonly #ttl: number; constructor (capacity = DEFAULT_CAPACITY, ttl: number | null = DEFAULT_TTL) { + // Validate capacity + if (!Number.isInteger(capacity) || capacity < 0) { + throw new Error(`LRUCache initialization error: 'capacity' must be a non-negative integer. Received: ${capacity}`); + } + + // Validate ttl + if (ttl !== null && (!Number.isFinite(ttl) || ttl < 0 || ttl > MAX_TTL)) { + throw new Error(`LRUCache initialization error: 'ttl' must be between 0 and ${MAX_TTL} ms or null to disable. Received: ${ttl}`); + } + this.capacity = capacity; ttl ? this.#ttl = ttl : this.#ttl = DISABLED_TTL; this.#head = this.#tail = new LRUNode('', this.#ttl); diff --git a/packages/rpc-provider/src/ws/index.spec.ts b/packages/rpc-provider/src/ws/index.spec.ts index 96274ab4d9..a4cc450275 100644 --- a/packages/rpc-provider/src/ws/index.spec.ts +++ b/packages/rpc-provider/src/ws/index.spec.ts @@ -60,6 +60,11 @@ describe('Endpoint Parsing', (): void => { new WsProvider(TEST_WS_URL, 0); }); + it('should throw error on negative cache capacity or TTL', () => { + expect(() => new WsProvider(TEST_WS_URL, false, {}, undefined, -5, 30000)).toThrow(/'capacity' must be a non-negative integer/); + expect(() => new WsProvider(TEST_WS_URL, false, {}, undefined, 1024, -1000)).toThrow(/'ttl' must be between 0 and 1800000 ms or null to disable/); + }); + it('Throws when WsProvider endpoint is an invalid string', () => { expect( () => new WsProvider('http://127.0.0.1:9955', 0)