Skip to content

Commit fd027e3

Browse files
committed
refactor: remove duplicate code in coordinator service
1 parent 937714e commit fd027e3

File tree

2 files changed

+87
-169
lines changed

2 files changed

+87
-169
lines changed

plugins/maciVoting/contexts/CoordinatorContext.tsx

Lines changed: 87 additions & 165 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import {
66
type TCoordinatorServiceResult,
77
type IGenerateData,
88
type ICoordinatorContextType,
9-
type IGenerateProofsArgs,
109
type FinalizeStatus,
1110
} from "./types";
1211
import { useEthersSigner } from "../hooks/useEthersSigner";
@@ -15,135 +14,73 @@ import { useAlerts } from "@/context/Alerts";
1514

1615
export const CoordinatorContext = createContext<ICoordinatorContextType | undefined>(undefined);
1716

18-
export const CoordinatorProvider = ({ children }: { children: ReactNode }) => {
19-
const [finalizeStatus, setFinalizeStatus] = useState<FinalizeStatus>("notStarted");
20-
21-
const signer = useEthersSigner();
22-
const { addAlert } = useAlerts();
23-
24-
const merge = useCallback(async (pollId: number): Promise<TCoordinatorServiceResult<boolean>> => {
25-
let response: Response;
26-
try {
27-
response = await fetch(`${PUBLIC_COORDINATOR_SERVICE_URL}/proof/merge`, {
28-
method: "POST",
29-
headers: {
30-
"Content-Type": "application/json",
31-
},
32-
body: JSON.stringify({
33-
maciContractAddress: PUBLIC_MACI_ADDRESS,
34-
pollId,
35-
chain: toBackendChainFormat(PUBLIC_CHAIN_NAME),
36-
}),
37-
});
38-
} catch (error) {
39-
return {
40-
success: false,
41-
error: new Error(`Failed to merge: ${error}`),
42-
};
43-
}
17+
async function makeCoordinatorServicePostRequest<T>(url: string, body: string): Promise<TCoordinatorServiceResult<T>> {
18+
try {
19+
const response = await fetch(url, {
20+
method: "POST",
21+
headers: {
22+
"Content-Type": "application/json",
23+
},
24+
body,
25+
});
4426

4527
if (!response.ok) {
4628
const errorData = await response.json();
4729
const errorMessage = errorData.message
4830
? `${response.status} - ${response.statusText}. ${errorData.message}`
4931
: `${response.status} - ${response.statusText}`;
50-
51-
return {
52-
success: false,
53-
error: new Error(`Failed to merge: ${errorMessage}`),
54-
};
32+
return { success: false, error: new Error(`Failed to submit: ${errorMessage}`) };
5533
}
5634

5735
const data = await response.json();
36+
return { success: true, data };
37+
} catch (error) {
5838
return {
59-
success: true,
60-
data: Boolean(data),
39+
success: false,
40+
error: new Error(`Failed to merge: ${error}`),
6141
};
62-
}, []);
42+
}
43+
}
6344

64-
const generateProofs = useCallback(
65-
async ({ pollId }: IGenerateProofsArgs): Promise<TCoordinatorServiceResult<IGenerateData>> => {
66-
let response: Response;
67-
try {
68-
response = await fetch(`${PUBLIC_COORDINATOR_SERVICE_URL}/proof/generate`, {
69-
method: "POST",
70-
headers: {
71-
"Content-Type": "application/json",
72-
},
73-
body: JSON.stringify({
74-
poll: pollId,
75-
maciContractAddress: PUBLIC_MACI_ADDRESS,
76-
mode: EMode.NON_QV,
77-
blocksPerBatch: 1000,
78-
chain: toBackendChainFormat(PUBLIC_CHAIN_NAME),
79-
}),
80-
});
81-
} catch (error) {
82-
return {
83-
success: false,
84-
error: new Error(`Failed to generate proofs: ${error}`),
85-
};
86-
}
45+
export const CoordinatorProvider = ({ children }: { children: ReactNode }) => {
46+
const [finalizeStatus, setFinalizeStatus] = useState<FinalizeStatus>("notStarted");
8747

88-
if (!response.ok) {
89-
const errorData = await response.json();
90-
const partialErrorMessage = errorData.message
91-
? `${response.status} - ${response.statusText}. ${errorData.message}`
92-
: `${response.status} - ${response.statusText}`;
48+
const signer = useEthersSigner();
49+
const { addAlert } = useAlerts();
9350

94-
return {
95-
success: false,
96-
error: new Error(`Failed to generate proofs: ${partialErrorMessage}`),
97-
};
98-
}
51+
const merge = useCallback(async (pollId: number): Promise<TCoordinatorServiceResult<boolean>> => {
52+
return await makeCoordinatorServicePostRequest<boolean>(
53+
`${PUBLIC_COORDINATOR_SERVICE_URL}/proof/merge`,
54+
JSON.stringify({
55+
maciContractAddress: PUBLIC_MACI_ADDRESS,
56+
pollId,
57+
chain: toBackendChainFormat(PUBLIC_CHAIN_NAME),
58+
})
59+
);
60+
}, []);
9961

100-
const data = await response.json();
101-
return {
102-
success: true,
103-
data,
104-
};
105-
},
106-
[]
107-
);
62+
const generateProofs = useCallback(async (pollId: number): Promise<TCoordinatorServiceResult<IGenerateData>> => {
63+
return await makeCoordinatorServicePostRequest<IGenerateData>(
64+
`${PUBLIC_COORDINATOR_SERVICE_URL}/proof/generate`,
65+
JSON.stringify({
66+
poll: pollId,
67+
maciContractAddress: PUBLIC_MACI_ADDRESS,
68+
mode: EMode.NON_QV,
69+
blocksPerBatch: 1000,
70+
chain: toBackendChainFormat(PUBLIC_CHAIN_NAME),
71+
})
72+
);
73+
}, []);
10874

10975
const submit = useCallback(async (pollId: number): Promise<TCoordinatorServiceResult<ITallyData>> => {
110-
let response: Response;
111-
try {
112-
response = await fetch(`${PUBLIC_COORDINATOR_SERVICE_URL}/proof/submit`, {
113-
method: "POST",
114-
headers: {
115-
"Content-Type": "application/json",
116-
},
117-
body: JSON.stringify({
118-
pollId,
119-
maciContractAddress: PUBLIC_MACI_ADDRESS,
120-
chain: toBackendChainFormat(PUBLIC_CHAIN_NAME),
121-
}),
122-
});
123-
} catch (error) {
124-
return {
125-
success: false,
126-
error: new Error(`Failed to submit: ${error}`),
127-
};
128-
}
129-
130-
if (!response.ok) {
131-
const errorData = await response.json();
132-
const partialErrorMessage = errorData.message
133-
? `${response.status} - ${response.statusText}. ${errorData.message}`
134-
: `${response.status} - ${response.statusText}`;
135-
136-
return {
137-
success: false,
138-
error: new Error(`Failed to submit: ${partialErrorMessage}`),
139-
};
140-
}
141-
142-
const data = await response.json();
143-
return {
144-
success: true,
145-
data,
146-
};
76+
return await makeCoordinatorServicePostRequest<ITallyData>(
77+
`${PUBLIC_COORDINATOR_SERVICE_URL}/proof/submit`,
78+
JSON.stringify({
79+
pollId,
80+
maciContractAddress: PUBLIC_MACI_ADDRESS,
81+
chain: toBackendChainFormat(PUBLIC_CHAIN_NAME),
82+
})
83+
);
14784
}, []);
14885

14986
const checkMergeStatus = useCallback(
@@ -159,6 +96,34 @@ export const CoordinatorProvider = ({ children }: { children: ReactNode }) => {
15996
[signer]
16097
);
16198

99+
const executeStep = useCallback(
100+
async <T,>(
101+
status: FinalizeStatus,
102+
step: "merge" | "prove" | "submit",
103+
func: () => Promise<TCoordinatorServiceResult<T>>
104+
) => {
105+
setFinalizeStatus(status);
106+
const result = await func();
107+
if (!result.success) {
108+
setFinalizeStatus("notStarted");
109+
addAlert(`Failed to ${step}`, {
110+
description: `Failed to ${step}. Please try again.`,
111+
type: "error",
112+
});
113+
return;
114+
}
115+
116+
const msg = {
117+
merge: ["Votes merged", "The votes have been merged."],
118+
prove: ["Votes proved", "The votes have been proved."],
119+
submit: ["Votes submitted", "The votes have been submitted."],
120+
} as const;
121+
122+
addAlert(msg[step][0], { description: msg[step][1], type: "success" });
123+
},
124+
[addAlert]
125+
);
126+
162127
const finalizeProposal = useCallback(
163128
async (pollId: number) => {
164129
if (!signer) {
@@ -167,77 +132,34 @@ export const CoordinatorProvider = ({ children }: { children: ReactNode }) => {
167132
return;
168133
}
169134

170-
// check if poll was already finalized
171-
// TODO: what should we do here?
172135
const pollContracts = await getPollContracts({
173136
maciAddress: PUBLIC_MACI_ADDRESS,
174137
pollId,
175138
signer,
176-
}).catch(() => setFinalizeStatus("notStarted"));
177-
if (!pollContracts) {
178-
return;
179-
}
139+
});
140+
180141
const isTallied = await pollContracts.tally.isTallied();
181-
// eslint-disable-next-line no-console
182-
console.log("isTallied", isTallied);
183-
/*if (isTallied) {
142+
if (isTallied) {
184143
console.log("Poll already finalized");
144+
setFinalizeStatus("notStarted");
185145
return;
186-
}*/
146+
}
187147

188-
setFinalizeStatus("merging");
189148
const hasMerged = await checkMergeStatus(pollId).catch(() => setFinalizeStatus("notStarted"));
190149
if (!hasMerged) {
191-
const mergeResult = await merge(pollId);
192-
if (!mergeResult.success) {
193-
setFinalizeStatus("notStarted");
194-
addAlert("Failed to merge", {
195-
description: "Failed to merge. Please try again.",
196-
type: "error",
197-
});
198-
return;
199-
}
150+
await executeStep("merging", "merge", () => merge(pollId));
200151
}
201-
addAlert("Votes merged", {
202-
description: "The votes have been merged.",
203-
type: "success",
204-
});
152+
await executeStep("proving", "prove", () => generateProofs(pollId));
153+
await executeStep("submitting", "submit", () => submit(pollId));
205154

206-
setFinalizeStatus("proving");
207-
const proveResult = await generateProofs({
208-
pollId,
209-
});
210-
if (!proveResult.success) {
211-
setFinalizeStatus("notStarted");
212-
addAlert("Failed to generate proofs", {
213-
description: "The proofs have not been generated. Please try again.",
214-
type: "error",
215-
});
216-
return;
217-
}
218-
addAlert("Votes proved", {
219-
description: "The votes have been proved.",
220-
type: "success",
221-
});
222-
223-
setFinalizeStatus("submitting");
224-
const submitResult = await submit(pollId);
225-
if (!submitResult.success) {
226-
setFinalizeStatus("notStarted");
227-
addAlert("Failed to submit proofs", {
228-
description: "The proofs have not been submitted. Please try again.",
229-
type: "error",
230-
});
231-
return;
232-
}
233155
setFinalizeStatus("submitted");
234156
addAlert("Votes submitted", {
235157
description: "The votes have been submitted.",
236158
type: "success",
237159
});
238160
return;
239161
},
240-
[addAlert, checkMergeStatus, generateProofs, merge, signer, submit]
162+
[addAlert, checkMergeStatus, executeStep, generateProofs, merge, signer, submit]
241163
);
242164

243165
const value = useMemo<ICoordinatorContextType>(

plugins/maciVoting/contexts/types.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,6 @@ export interface IGenerateData {
1414
}
1515
export type TCoordinatorServiceResult<T, E = Error> = { success: true; data: T } | { success: false; error: E };
1616

17-
export interface IGenerateProofsArgs {
18-
pollId: number;
19-
}
20-
2117
export type FinalizeStatus = "notStarted" | "merging" | "proving" | "submitting" | "submitted";
2218

2319
export interface ICoordinatorContextType {

0 commit comments

Comments
 (0)