Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update useScaffoldEventHistory hook #827

Merged
merged 3 commits into from
Apr 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 75 additions & 79 deletions packages/nextjs/hooks/scaffold-eth/useScaffoldEventHistory.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTargetNetwork } from "./useTargetNetwork";
import { Abi, AbiEvent, ExtractAbiEventNames } from "abitype";
import { useInterval } from "usehooks-ts";
Expand Down Expand Up @@ -45,7 +45,7 @@ export const useScaffoldEventHistory = <
watch,
enabled = true,
}: UseScaffoldEventHistoryConfig<TContractName, TEventName, TBlockData, TTransactionData, TReceiptData>) => {
const [events, setEvents] = useState<any[]>();
const [events, setEvents] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string>();
damianmarti marked this conversation as resolved.
Show resolved Hide resolved
const [fromBlockUpdated, setFromBlockUpdated] = useState<bigint>(fromBlock);
Expand All @@ -56,95 +56,91 @@ export const useScaffoldEventHistory = <
chainId: targetNetwork.id,
});

const readEvents = async (fromBlock?: bigint) => {
setIsLoading(true);
try {
if (!deployedContractData) {
throw new Error("Contract not found");
}
const readEvents = useCallback(
async () => {
setIsLoading(true);
try {
if (!deployedContractData) {
throw new Error("Contract not found");
}

if (!enabled) {
throw new Error("Hook disabled");
}
if (!enabled) {
throw new Error("Hook disabled");
}

if (!publicClient) {
throw new Error("Public client not found");
}
if (!publicClient) {
throw new Error("Public client not found");
}

const event = (deployedContractData.abi as Abi).find(
part => part.type === "event" && part.name === eventName,
) as AbiEvent;

const event = (deployedContractData.abi as Abi).find(
part => part.type === "event" && part.name === eventName,
) as AbiEvent;

const blockNumber = await publicClient.getBlockNumber({ cacheTime: 0 });

if ((fromBlock && blockNumber >= fromBlock) || blockNumber >= fromBlockUpdated) {
const logs = await publicClient.getLogs({
address: deployedContractData?.address,
event,
args: filters as any,
fromBlock: fromBlock || fromBlockUpdated,
toBlock: blockNumber,
});
setFromBlockUpdated(blockNumber + 1n);

const newEvents = [];
for (let i = logs.length - 1; i >= 0; i--) {
newEvents.push({
log: logs[i],
args: logs[i].args,
block:
blockData && logs[i].blockHash === null
? null
: await publicClient.getBlock({ blockHash: logs[i].blockHash as Hash }),
transaction:
transactionData && logs[i].transactionHash !== null
? await publicClient.getTransaction({ hash: logs[i].transactionHash as Hash })
: null,
receipt:
receiptData && logs[i].transactionHash !== null
? await publicClient.getTransactionReceipt({ hash: logs[i].transactionHash as Hash })
: null,
const blockNumber = await publicClient.getBlockNumber({ cacheTime: 0 });

if (blockNumber >= fromBlockUpdated) {
const logs = await publicClient.getLogs({
address: deployedContractData?.address,
event,
args: filters as any,
fromBlock: fromBlockUpdated,
toBlock: blockNumber,
});
}
if (events && typeof fromBlock === "undefined") {
setFromBlockUpdated(blockNumber + 1n);

const newEvents = [];
for (let i = logs.length - 1; i >= 0; i--) {
newEvents.push({
log: logs[i],
args: logs[i].args,
block:
blockData && logs[i].blockHash === null
? null
: await publicClient.getBlock({ blockHash: logs[i].blockHash as Hash }),
transaction:
transactionData && logs[i].transactionHash !== null
? await publicClient.getTransaction({ hash: logs[i].transactionHash as Hash })
: null,
receipt:
receiptData && logs[i].transactionHash !== null
? await publicClient.getTransactionReceipt({ hash: logs[i].transactionHash as Hash })
: null,
});
}
setEvents([...newEvents, ...events]);
} else {
setEvents(newEvents);
setError(undefined);
}
setError(undefined);
} catch (e: any) {
if (events.length > 0) {
setEvents([]);
}
setError(e);
console.error(e);
} finally {
setIsLoading(false);
}
} catch (e: any) {
console.error(e);
setEvents(undefined);
setError(e);
} finally {
setIsLoading(false);
}
};

useEffect(() => {
readEvents(fromBlock);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fromBlock, enabled]);
[
blockData,
deployedContractData,
enabled,
eventName,
events,
// eslint-disable-next-line react-hooks/exhaustive-deps
JSON.stringify(filters, replacer),
fromBlockUpdated,
publicClient,
receiptData,
transactionData,
],
);

useEffect(() => {
if (!deployedContractLoading) {
readEvents();
Pabl0cks marked this conversation as resolved.
Show resolved Hide resolved
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
publicClient,
contractName,
eventName,
deployedContractLoading,
deployedContractData?.address,
deployedContractData,
// eslint-disable-next-line react-hooks/exhaustive-deps
JSON.stringify(filters, replacer),
blockData,
transactionData,
receiptData,
]);
}, [readEvents, deployedContractLoading]);

useEffect(() => {
// Reset the internal state when target network or fromBlock changed
Expand All @@ -159,7 +155,7 @@ export const useScaffoldEventHistory = <
readEvents();
}
},
watch ? (targetNetwork.id !== chains.hardhat.id ? scaffoldConfig.pollingInterval : 4_000) : null,
watch && enabled ? (targetNetwork.id !== chains.hardhat.id ? scaffoldConfig.pollingInterval : 4_000) : null,
);

const eventHistoryData = useMemo(
Expand Down
Loading