-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvotingApi.ts
More file actions
408 lines (383 loc) · 12.8 KB
/
Copy pathvotingApi.ts
File metadata and controls
408 lines (383 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Frontend client for the signed-ballot API (server/api.mjs). Wraps
// proposal CRUD, EIP-712 signing via wagmi, and tally/ballots reads.
//
// All endpoints sit behind the same origin (vite proxies /api/* to the
// Fastify server on :7101), so no CORS dance and no separate funnel
// port to manage.
import { mainnet } from "viem/chains";
import type { WalletClient } from "viem";
export interface VoteOption {
id: number;
label: string;
}
export interface Proposal {
id: string;
title: string;
description: string;
votingMode: "quadratic" | "token-weight";
budget: number;
options: VoteOption[];
deadline: string; // ISO
tokenId: string | null; // legacy registry id (server may have a hardcoded entry)
tokenAddress?: `0x${string}` | null; // eligibility-token contract — preferred over tokenId
tokenChainId?: number | null; // chain the token lives on (mainnet=1, arbitrum=42161)
createdAt: string;
createdBy: string | null;
deletedOptionIds?: number[]; // soft-deleted option ids; allocations to these refund
}
export interface Allocation {
issueId: number;
points: number;
}
export interface Ballot {
voter: `0x${string}`;
proposalId: string;
allocations: Allocation[];
budget: number;
deadline: number; // unix seconds
nonce: number;
}
export interface StoredBallot {
ballot: Ballot;
signature: `0x${string}`;
signedAt: string;
badgeBalance: string;
}
// EIP-712 domain. chainId is Ethereum mainnet (1) because that's the
// chain wagmi is configured to connect wallets to. Signatures are
// off-chain (verified server-side via viem's verifyTypedData) so this
// isn't tied to where the badge contract lives — it just needs to
// match the wallet's active chain at sign time, otherwise the wallet
// refuses with "Provided chainId X must match active chainId Y".
const DOMAIN = {
name: "murmurations",
version: "1",
chainId: mainnet.id,
} as const;
const TYPES = {
Allocation: [
{ name: "issueId", type: "uint256" },
{ name: "points", type: "uint256" },
],
Ballot: [
{ name: "voter", type: "address" },
{ name: "proposalId", type: "string" },
{ name: "allocations", type: "Allocation[]" },
{ name: "budget", type: "uint256" },
{ name: "deadline", type: "uint256" },
{ name: "nonce", type: "uint256" },
],
} as const;
// Admin actions (create / delete proposal) are also EIP-712 signed.
// Server verifies the recovered signer is in its admin allowlist.
const ADMIN_ACTION_TYPES = {
AdminAction: [
{ name: "action", type: "string" },
{ name: "proposalId", type: "string" },
{ name: "actor", type: "address" },
{ name: "nonce", type: "uint256" },
{ name: "deadline", type: "uint256" },
],
} as const;
// Same idea but for soft-deleting an individual option (issue) inside a
// vote. Carries optionId in the signed payload so a captured admin sig
// can't be replayed against a different option in the same proposal.
const OPTION_DELETE_TYPES = {
OptionDelete: [
{ name: "action", type: "string" },
{ name: "proposalId", type: "string" },
{ name: "optionId", type: "uint256" },
{ name: "actor", type: "address" },
{ name: "nonce", type: "uint256" },
{ name: "deadline", type: "uint256" },
],
} as const;
// Issue submissions are EIP-712 signed by the submitter and verified
// against the proposal's eligibility-badge balanceOf check server-side.
const ISSUE_SUBMISSION_TYPES = {
IssueSubmission: [
{ name: "submitter", type: "address" },
{ name: "proposalId", type: "string" },
{ name: "label", type: "string" },
{ name: "body", type: "string" },
{ name: "nonce", type: "uint256" },
{ name: "deadline", type: "uint256" },
],
} as const;
async function signAdminAction(
walletClient: WalletClient,
actor: `0x${string}`,
action: "create_proposal" | "delete_proposal",
proposalId: string,
): Promise<{ action: object; signature: `0x${string}` }> {
const nonce = Date.now();
const deadline = Math.floor(Date.now() / 1000) + 5 * 60; // 5 min signing window
const message = {
action,
proposalId,
actor,
nonce: BigInt(nonce),
deadline: BigInt(deadline),
};
const signature = await walletClient.signTypedData({
account: actor,
domain: DOMAIN,
types: ADMIN_ACTION_TYPES,
primaryType: "AdminAction",
message,
});
return {
action: { action, proposalId, actor, nonce, deadline },
signature,
};
}
export async function fetchProposals(): Promise<Proposal[]> {
const res = await fetch("/api/proposals");
if (!res.ok) throw new Error(`fetchProposals: ${res.status}`);
const j = await res.json();
return j.proposals || [];
}
export async function fetchProposal(id: string): Promise<{
proposal: Proposal;
tally: Record<string, number>;
voterCount: number;
}> {
const res = await fetch(`/api/proposals/${encodeURIComponent(id)}`);
if (!res.ok) throw new Error(`fetchProposal: ${res.status}`);
return res.json();
}
export async function fetchBallots(id: string): Promise<StoredBallot[]> {
const res = await fetch(`/api/proposals/${encodeURIComponent(id)}/ballots`);
if (!res.ok) throw new Error(`fetchBallots: ${res.status}`);
const j = await res.json();
return j.ballots || [];
}
export async function deleteOption(
proposalId: string,
optionId: number,
walletClient: WalletClient,
actor: `0x${string}`,
): Promise<void> {
const nonce = Date.now();
const deadline = Math.floor(Date.now() / 1000) + 5 * 60;
const message = {
action: "delete_option",
proposalId,
optionId: BigInt(optionId),
actor,
nonce: BigInt(nonce),
deadline: BigInt(deadline),
};
const signature = await walletClient.signTypedData({
account: actor,
domain: DOMAIN,
types: OPTION_DELETE_TYPES,
primaryType: "OptionDelete",
message,
});
const optionDeleteAuth = {
action: { action: "delete_option", proposalId, optionId, actor, nonce, deadline },
signature,
};
const res = await fetch(
`/api/proposals/${encodeURIComponent(proposalId)}/options/${encodeURIComponent(String(optionId))}`,
{
method: "DELETE",
headers: { "content-type": "application/json" },
body: JSON.stringify({ optionDeleteAuth }),
},
);
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(`deleteOption: ${res.status} ${err.error || ""}`);
}
}
export async function deleteProposal(
id: string,
walletClient: WalletClient,
actor: `0x${string}`,
): Promise<void> {
const adminAuth = await signAdminAction(walletClient, actor, "delete_proposal", id);
const res = await fetch(`/api/proposals/${encodeURIComponent(id)}`, {
method: "DELETE",
headers: { "content-type": "application/json" },
body: JSON.stringify({ adminAuth }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(`deleteProposal: ${res.status} ${err.error || ""}`);
}
}
export async function fetchGithubPreview(url: string): Promise<{
number: number;
html_url: string;
title: string;
body: string;
labels: string[];
}> {
const res = await fetch(`/api/github/preview?url=${encodeURIComponent(url)}`);
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(`preview: ${res.status} ${err.error || ""} ${err.detail || ""}`);
}
return res.json();
}
export async function addOption(
proposalId: string,
label: string,
body: string,
walletClient: WalletClient,
submitter: `0x${string}`,
githubUrl?: string,
): Promise<{ option: VoteOption; proposal: Proposal }> {
const nonce = Date.now();
const deadline = Math.floor(Date.now() / 1000) + 5 * 60; // 5 min signing window
const submission = { submitter, proposalId, label, body: body || "", nonce, deadline };
const signature = await walletClient.signTypedData({
account: submitter,
domain: DOMAIN,
types: ISSUE_SUBMISSION_TYPES,
primaryType: "IssueSubmission",
message: {
submitter,
proposalId,
label,
body: body || "",
nonce: BigInt(nonce),
deadline: BigInt(deadline),
},
});
const res = await fetch(`/api/proposals/${encodeURIComponent(proposalId)}/options`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ label, body, submission, signature, githubUrl: githubUrl || undefined }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(`addOption: ${res.status} ${err.error || ""}`);
}
return res.json();
}
export async function createProposal(
input: {
id: string;
title: string;
description?: string;
votingMode: "quadratic" | "token-weight";
budget: number;
options: VoteOption[];
deadline: string;
opensAt?: string | null; // ISO; when set, server rejects ballots before it
tokenId?: string | null;
tokenAddress?: `0x${string}` | null;
tokenChainId?: number | null;
},
walletClient: WalletClient,
actor: `0x${string}`,
): Promise<Proposal> {
const adminAuth = await signAdminAction(walletClient, actor, "create_proposal", input.id);
const res = await fetch("/api/proposals", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ ...input, adminAuth }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(`createProposal: ${res.status} ${err.error || ""}`);
}
const j = await res.json();
return j.proposal;
}
/**
* Sign + submit a ballot. Throws on validation failures (over-budget,
* not a badgeholder, etc.) — caller renders the error.
*/
// MetaMask (and most wallets) refuse to sign EIP-712 typed data whose
// domain.chainId doesn't match the wallet's ACTIVE chain — it throws
// "provided chainId 1 must match the active chainId X". Our DOMAIN is pinned
// to mainnet (chainId 1). On desktop the wallet is usually already on mainnet
// so this is invisible, but MetaMask MOBILE over WalletConnect keeps whatever
// chain the user had open, so signing silently failed there ("Couldn't sign
// the ballot"). Put the wallet on mainnet before signing. This changes ONLY
// the active network, never the signed payload or the domain, so every ballot
// already cast still verifies bit-for-bit identically. Throws WRONG_CHAIN
// (surfaced as a "switch to mainnet" message) if the wallet won't switch.
async function ensureSigningChain(walletClient: WalletClient): Promise<void> {
let active: number;
try {
active = await walletClient.getChainId();
} catch {
return; // can't read the chain; let the sign attempt surface the real error
}
if (active === mainnet.id) return;
try {
await walletClient.switchChain({ id: mainnet.id });
} catch {
throw new Error("WRONG_CHAIN: switch your wallet to Ethereum mainnet to vote.");
}
// Some mobile wallets ACK the switch but don't actually change chains —
// re-read and refuse rather than produce a signature the wallet will reject.
let after: number;
try {
after = await walletClient.getChainId();
} catch {
after = active;
}
if (after !== mainnet.id) {
throw new Error("WRONG_CHAIN: switch your wallet to Ethereum mainnet to vote.");
}
}
// WebKit (all iOS browsers) returns Invalid Date for the API's legacy
// "YYYY-MM-DD HH:mm UTC" deadline strings, so a bare new Date() here made
// BigInt(NaN) throw before the wallet was ever asked to sign. Normalize to
// ISO the same way app.jsx does everywhere else. ISO inputs pass through
// unchanged, so ballots signed on desktop are byte-identical to before.
export function deadlineEpochSec(deadline: string): number {
return Math.floor(
new Date(String(deadline).replace(" UTC", "Z").replace(" ", "T")).getTime() / 1000,
);
}
export async function castVote(
walletClient: WalletClient,
voter: `0x${string}`,
proposal: Proposal,
allocations: Allocation[],
): Promise<{ ok: true; voter: `0x${string}` }> {
await ensureSigningChain(walletClient);
const deadlineSec = deadlineEpochSec(proposal.deadline);
const ballot: Ballot = {
voter,
proposalId: proposal.id,
allocations,
budget: proposal.budget,
deadline: deadlineSec,
nonce: Date.now(),
};
const signature = await walletClient.signTypedData({
account: voter,
domain: DOMAIN,
types: TYPES,
primaryType: "Ballot",
message: {
voter,
proposalId: ballot.proposalId,
allocations: allocations.map((a) => ({
issueId: BigInt(a.issueId),
points: BigInt(a.points),
})),
budget: BigInt(ballot.budget),
deadline: BigInt(ballot.deadline),
nonce: BigInt(ballot.nonce),
},
});
const res = await fetch(`/api/proposals/${encodeURIComponent(proposal.id)}/vote`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ ballot, signature }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(`castVote ${res.status}: ${body.error || "unknown"}`);
}
return body;
}