From 39ed99d816c485e3df573fe844e7acab457a0a2e Mon Sep 17 00:00:00 2001 From: Sumanjeet Date: Tue, 18 Feb 2025 16:11:05 +0530 Subject: [PATCH 1/2] Fix: Prevent function from spamming API after sleep - Adjusted the function to calculate the next round by time when the computer wakes from sleep, preventing unnecessary API calls. --- lib/index.ts | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/lib/index.ts b/lib/index.ts index faeae63..5d82013 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -94,15 +94,25 @@ export async function* watch( options: WatchOptions = defaultWatchOptions, ): AsyncGenerator { const info = await client.chain().info() - let currentRound = roundAt(Date.now(), info) - + while (!abortController.signal.aborted) { const now = Date.now() - await sleep(roundTime(info, currentRound) - now) - - const beacon = await retryOnError(async () => client.get(currentRound), options.retriesOnFailure) - yield validatedBeacon(client, beacon, currentRound) - currentRound = currentRound + 1 + const targetRound = roundAt(now, info) + + const nextRoundTime = roundTime(info, targetRound) + const waitTime = nextRoundTime - now + + await sleep(Math.max(0, waitTime)) + + try { + const beacon = await retryOnError( + async () => client.get(targetRound), + options.retriesOnFailure + ) + yield validatedBeacon(client, beacon, targetRound) + } catch (error) { + throw error + } } } From 62107c3bda1d241e94c33ac864e611e03d5efdfd Mon Sep 17 00:00:00 2001 From: Sumanjeet Date: Wed, 19 Feb 2025 16:31:35 +0530 Subject: [PATCH 2/2] Removed Unnecessary try/catch wrapper --- lib/index.ts | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/lib/index.ts b/lib/index.ts index 5d82013..aab4820 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -104,15 +104,11 @@ export async function* watch( await sleep(Math.max(0, waitTime)) - try { - const beacon = await retryOnError( - async () => client.get(targetRound), - options.retriesOnFailure - ) - yield validatedBeacon(client, beacon, targetRound) - } catch (error) { - throw error - } + const beacon = await retryOnError( + async () => client.get(targetRound), + options.retriesOnFailure + ) + yield validatedBeacon(client, beacon, targetRound) } }