|
1 | 1 | import { PUBLIC_MACI_ADDRESS, PUBLIC_MACI_DEPLOYMENT_BLOCK } from "@/constants";
|
2 | 2 | import { generateMaciStateTreeWithEndKey, getJoinedUserData, joinPoll } from "@maci-protocol/sdk/browser";
|
3 |
| -import { useCallback, useEffect, useState } from "react"; |
| 3 | +import { useCallback, useMemo, useState } from "react"; |
4 | 4 | import { usePublicClient } from "wagmi";
|
5 | 5 | import { DEFAULT_IVCP_DATA, DEFAULT_SG_DATA } from "../../contexts/MaciContext";
|
6 | 6 | import { clientToSigner, useEthersSigner } from "../useEthersSigner";
|
7 | 7 | import { useMaci } from "../useMaci";
|
8 | 8 | import { type IJoinPollData } from "../../contexts/types";
|
| 9 | +import { useQuery, useQueryClient } from "@tanstack/react-query"; |
9 | 10 |
|
10 | 11 | export const useJoinPoll = (pollId?: bigint) => {
|
11 | 12 | const signer = useEthersSigner();
|
12 | 13 | const publicClient = usePublicClient();
|
| 14 | + const queryClient = useQueryClient(); |
13 | 15 | const { maciKeypair, isRegistered, stateIndex, artifacts } = useMaci();
|
14 | 16 |
|
15 | 17 | const [isLoading, setIsLoading] = useState(false);
|
16 | 18 | const [error, setError] = useState<string | undefined>();
|
17 |
| - const [hasJoinedPoll, setHasJoinedPoll] = useState(false); |
18 |
| - const [joinedPollData, setJoinedPollData] = useState<IJoinPollData | undefined>(); |
| 19 | + // Keep track of newly joined poll data that will be returned when joining a poll |
| 20 | + const [newlyJoinedPollData, setNewlyJoinedPollData] = useState<IJoinPollData | undefined>(); |
19 | 21 |
|
20 |
| - // check if the user has joined the poll |
21 |
| - useEffect(() => { |
22 |
| - (async () => { |
| 22 | + // Query key for consistent cache access |
| 23 | + const joinedUserQueryKey = useMemo( |
| 24 | + () => ["joinedUserData", pollId?.toString(), maciKeypair?.publicKey.serialize()], |
| 25 | + [pollId, maciKeypair] |
| 26 | + ); |
| 27 | + |
| 28 | + // check if the user has joined the poll using useQuery |
| 29 | + const { data: joinedPollData, isLoading: isLoadingQuery } = useQuery({ |
| 30 | + queryKey: joinedUserQueryKey, |
| 31 | + queryFn: async () => { |
23 | 32 | if (!pollId || !publicClient || !maciKeypair || !isRegistered || !artifacts) {
|
24 |
| - return; |
| 33 | + return null; |
25 | 34 | }
|
26 | 35 |
|
27 |
| - // TODO: use useQuery for this |
| 36 | + setIsLoading(true); |
| 37 | + try { |
| 38 | + const publicSigner = clientToSigner(publicClient); |
28 | 39 |
|
29 |
| - const publicSigner = clientToSigner(publicClient); |
| 40 | + const joinedUser = await getJoinedUserData({ |
| 41 | + maciAddress: PUBLIC_MACI_ADDRESS, |
| 42 | + pollPublicKey: maciKeypair.publicKey.serialize(), |
| 43 | + signer: publicSigner, |
| 44 | + startBlock: PUBLIC_MACI_DEPLOYMENT_BLOCK, |
| 45 | + pollId, |
| 46 | + }); |
30 | 47 |
|
31 |
| - const joinedUser = await getJoinedUserData({ |
32 |
| - maciAddress: PUBLIC_MACI_ADDRESS, |
33 |
| - pollPublicKey: maciKeypair.publicKey.serialize(), |
34 |
| - signer: publicSigner, |
35 |
| - startBlock: PUBLIC_MACI_DEPLOYMENT_BLOCK, |
36 |
| - pollId, |
37 |
| - }).catch((error) => { |
| 48 | + if (joinedUser && joinedUser.isJoined) { |
| 49 | + return { |
| 50 | + pollStateIndex: joinedUser.pollStateIndex ?? "", |
| 51 | + voiceCredits: joinedUser.voiceCredits ?? "0", |
| 52 | + // these two attributes are returned only when the user joins the poll |
| 53 | + nullifier: "", |
| 54 | + hash: "", |
| 55 | + }; |
| 56 | + } |
| 57 | + } catch (error) { |
38 | 58 | // eslint-disable-next-line no-console
|
39 |
| - console.log("Error checking if user has joined poll", error); |
40 |
| - return; |
41 |
| - }); |
42 |
| - |
43 |
| - console.log("joinedUser", joinedUser); |
44 |
| - console.log("pollId", pollId); |
45 |
| - |
46 |
| - if (joinedUser && joinedUser.isJoined) { |
47 |
| - setHasJoinedPoll(true); |
48 |
| - setJoinedPollData({ |
49 |
| - pollStateIndex: joinedUser.pollStateIndex ?? "", |
50 |
| - voiceCredits: joinedUser.voiceCredits ?? "0", |
51 |
| - // these two attributes are returned only when the user joins the poll |
52 |
| - nullifier: "", |
53 |
| - hash: "", |
54 |
| - }); |
| 59 | + console.error("Error checking if user has joined poll", error); |
55 | 60 | }
|
56 |
| - })(); |
57 |
| - }, [artifacts, isRegistered, maciKeypair, pollId, publicClient]); |
| 61 | + |
| 62 | + setIsLoading(false); |
| 63 | + return null; |
| 64 | + }, |
| 65 | + enabled: Boolean(pollId && publicClient && maciKeypair && isRegistered && artifacts), |
| 66 | + staleTime: Infinity, // Cache forever as mentioned by user |
| 67 | + gcTime: Infinity, // Keep in cache forever |
| 68 | + }); |
58 | 69 |
|
59 | 70 | const joinPollFunction = useCallback(async () => {
|
60 | 71 | if (!pollId || !signer || !maciKeypair || !isRegistered || !artifacts) {
|
61 |
| - setHasJoinedPoll(false); |
62 | 72 | return;
|
63 | 73 | }
|
64 | 74 |
|
65 |
| - const stateTree = await generateMaciStateTreeWithEndKey({ |
66 |
| - maciContractAddress: PUBLIC_MACI_ADDRESS, |
67 |
| - signer, |
68 |
| - userPublicKey: maciKeypair.publicKey, |
69 |
| - startBlock: PUBLIC_MACI_DEPLOYMENT_BLOCK, |
70 |
| - }); |
71 |
| - |
72 |
| - const inclusionProof = stateTree.signUpTree.generateProof(Number(stateIndex)); |
73 |
| - |
74 |
| - const joinedData = await joinPoll({ |
75 |
| - maciAddress: PUBLIC_MACI_ADDRESS, |
76 |
| - privateKey: maciKeypair.privateKey.serialize(), |
77 |
| - signer, |
78 |
| - pollId, |
79 |
| - inclusionProof: inclusionProof, |
80 |
| - pollJoiningZkey: artifacts.zKey as unknown as string, |
81 |
| - pollWasm: artifacts.wasm as unknown as string, |
82 |
| - sgDataArg: DEFAULT_SG_DATA, |
83 |
| - ivcpDataArg: DEFAULT_IVCP_DATA, |
84 |
| - blocksPerBatch: 1000, |
85 |
| - }).catch((error) => { |
86 |
| - if (error.message.includes("0xa3281672")) { |
| 75 | + if (joinedPollData) { |
| 76 | + setNewlyJoinedPollData(joinedPollData); |
| 77 | + } |
| 78 | + |
| 79 | + setIsLoading(true); |
| 80 | + setError(undefined); |
| 81 | + |
| 82 | + try { |
| 83 | + const stateTree = await generateMaciStateTreeWithEndKey({ |
| 84 | + maciContractAddress: PUBLIC_MACI_ADDRESS, |
| 85 | + signer, |
| 86 | + userPublicKey: maciKeypair.publicKey, |
| 87 | + startBlock: PUBLIC_MACI_DEPLOYMENT_BLOCK, |
| 88 | + }); |
| 89 | + |
| 90 | + const inclusionProof = stateTree.signUpTree.generateProof(Number(stateIndex)); |
| 91 | + |
| 92 | + const joinedData = await joinPoll({ |
| 93 | + maciAddress: PUBLIC_MACI_ADDRESS, |
| 94 | + privateKey: maciKeypair.privateKey.serialize(), |
| 95 | + signer, |
| 96 | + pollId, |
| 97 | + inclusionProof: inclusionProof, |
| 98 | + pollJoiningZkey: artifacts.zKey as unknown as string, |
| 99 | + pollWasm: artifacts.wasm as unknown as string, |
| 100 | + sgDataArg: DEFAULT_SG_DATA, |
| 101 | + ivcpDataArg: DEFAULT_IVCP_DATA, |
| 102 | + blocksPerBatch: 1000, |
| 103 | + }); |
| 104 | + |
| 105 | + if (joinedData) { |
| 106 | + setNewlyJoinedPollData(joinedData); |
| 107 | + // After successfully joining, manually invalidate the query to trigger a refetch |
| 108 | + queryClient.invalidateQueries({ queryKey: joinedUserQueryKey }); |
| 109 | + } |
| 110 | + } catch (error: any) { |
| 111 | + if (error.message?.includes("0xa3281672")) { |
87 | 112 | // 0xa3281672 -> signature of BalanceTooLow()
|
88 | 113 | setError(`Address balance is too low to join the poll`);
|
89 |
| - setIsLoading(false); |
90 |
| - return; |
| 114 | + } else { |
| 115 | + // eslint-disable-next-line no-console |
| 116 | + console.error("Error joining poll", error); |
| 117 | + setError("Error joining poll"); |
91 | 118 | }
|
92 |
| - // eslint-disable-next-line no-console |
93 |
| - console.log("Error joining poll", error); |
94 |
| - setError("Error joining poll"); |
95 |
| - return; |
96 |
| - }); |
97 |
| - |
98 |
| - if (!joinedData) { |
99 |
| - setHasJoinedPoll(false); |
100 |
| - return; |
| 119 | + } finally { |
| 120 | + setIsLoading(false); |
101 | 121 | }
|
| 122 | + }, [ |
| 123 | + pollId, |
| 124 | + signer, |
| 125 | + maciKeypair, |
| 126 | + isRegistered, |
| 127 | + artifacts, |
| 128 | + joinedPollData, |
| 129 | + stateIndex, |
| 130 | + queryClient, |
| 131 | + joinedUserQueryKey, |
| 132 | + ]); |
102 | 133 |
|
103 |
| - setHasJoinedPoll(true); |
104 |
| - setJoinedPollData(joinedData); |
105 |
| - }, [artifacts, isRegistered, maciKeypair, pollId, signer, stateIndex]); |
| 134 | + // Use the query data or the newly joined data if available |
| 135 | + const effectiveJoinedPollData = newlyJoinedPollData ?? joinedPollData; |
| 136 | + const effectiveHasJoinedPoll = Boolean(effectiveJoinedPollData); |
106 | 137 |
|
107 | 138 | return {
|
108 |
| - isLoading, |
| 139 | + isLoading: isLoading || isLoadingQuery, |
109 | 140 | error,
|
110 |
| - hasJoinedPoll, |
111 |
| - joinedPollData, |
| 141 | + hasJoinedPoll: effectiveHasJoinedPoll, |
| 142 | + joinedPollData: effectiveJoinedPollData, |
112 | 143 | joinPollFunction,
|
113 | 144 | };
|
114 | 145 | };
|
0 commit comments