From 14dbeb9f7328683dee4f9d1563a6a7ee9211279a Mon Sep 17 00:00:00 2001 From: Julian Gruber Date: Thu, 16 May 2024 04:30:47 -0700 Subject: [PATCH] add { signal } option (#3) --- README.md | 1 + index.js | 21 ++++++++++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e87f1b8..09fd356 100644 --- a/README.md +++ b/README.md @@ -30,3 +30,4 @@ Options: - `provider`: Ethers provider - `rpcUrl`: JSON-RPC endpoint URL - `rpcHeader`: JSON-RPC headers object +- `signal`: Optional `AbortSignal` diff --git a/index.js b/index.js index 32afaf7..6464621 100644 --- a/index.js +++ b/index.js @@ -12,7 +12,8 @@ const makeRequest = async ({ address, rpcUrl, rpcHeaders, - fromBlock + fromBlock, + signal }) => { const req = { jsonrpc: '2.0', @@ -31,7 +32,8 @@ const makeRequest = async ({ ...rpcHeaders, 'content-type': 'application/json' }, - body: JSON.stringify(req) + body: JSON.stringify(req), + signal }) if (!res.ok) { throw new Error( @@ -58,7 +60,8 @@ export async function * onContractEvent ({ contract, provider, rpcUrl, - rpcHeaders + rpcHeaders, + signal }) { const address = await contract.getAddress() let lastBlock = await provider.getBlockNumber() @@ -76,9 +79,13 @@ export async function * onContractEvent ({ address, rpcUrl, rpcHeaders, - fromBlock: lastBlock + fromBlock: lastBlock, + signal })) } catch (err) { + if (err.name === 'AbortError') { + throw err + } console.error(err) } @@ -95,7 +102,11 @@ export async function * onContractEvent ({ const iterationEnd = new Date() const iterationDuration = iterationEnd - iterationStart if (iterationDuration < MIN_POLL_INTERVAL) { - await timers.setTimeout(MIN_POLL_INTERVAL - iterationDuration) + await timers.setTimeout( + MIN_POLL_INTERVAL - iterationDuration, + null, + { signal } + ) } } }