Skip to content

Commit

Permalink
deal with single item and array of proposals
Browse files Browse the repository at this point in the history
  • Loading branch information
thevolcanomanishere committed Dec 13, 2024
1 parent 16c621e commit a74d6c6
Showing 1 changed file with 30 additions and 15 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
ProposalSelectionFragment,
ProposalStatus,
ProposalWithVotesFragment,
} from "@bera/graphql/governance";
Expand All @@ -7,35 +8,49 @@ import { useRouter } from "next/navigation";
import { useBlockNumber } from "wagmi";
import { useSWRConfig } from "swr";

type ProposalInput = ProposalSelectionFragment | ProposalSelectionFragment[];

/**
* Monitors the status of a proposal and refreshes the page when the status changes.
* @param proposal
* Monitors the status of one or multiple proposals and refetches them when their status changes
* @param proposals - Single proposal or array of proposals to monitor
*/
export const useProposalStatusMonitor = (
proposal: ProposalWithVotesFragment,
) => {
export const useProposalStatusMonitor = (proposals: ProposalInput) => {
const { data: currentBlockNumber } = useBlockNumber({
watch: {
pollingInterval: 5000,
enabled: true,
poll: true,
},
});
const router = useRouter();
const { mutate: refreshPollProposal } = useSWRConfig();

useEffect(() => {
if (!currentBlockNumber || !proposal) return;
console.log("Updating all prop status");
if (proposals === undefined) return;
if (!currentBlockNumber || !proposals) return;

const proposalsArray = Array.isArray(proposals) ? proposals : [proposals];

const statusChecks = {
[ProposalStatus.Pending]: proposal.voteStartBlock,
[ProposalStatus.Active]: proposal.voteEndBlock,
[ProposalStatus.InQueue]: proposal.queueEnd,
[ProposalStatus.Pending]: (p: ProposalSelectionFragment) =>
p.voteStartBlock,
[ProposalStatus.Active]: (p: ProposalSelectionFragment) => p.voteEndBlock,
[ProposalStatus.InQueue]: (p: ProposalSelectionFragment) => p.queueEnd,
};

const threshold =
statusChecks[proposal.status as keyof typeof statusChecks];
proposalsArray.forEach((proposal) => {
const getThreshold =
statusChecks[proposal.status as keyof typeof statusChecks];
if (!getThreshold) return;

if (threshold && currentBlockNumber >= BigInt(threshold)) {
refreshPollProposal(["usePollProposal", proposal.id]);
}
}, [proposal, currentBlockNumber, router]);
const threshold = getThreshold(proposal);
if (currentBlockNumber >= BigInt(threshold)) {
console.log(
`Proposal ${proposal.id} status changed to ${proposal.status}`,
);
refreshPollProposal(["usePollProposal", proposal.id]);
}
});
}, [proposals, currentBlockNumber, router]);
};

0 comments on commit a74d6c6

Please sign in to comment.