@vocdoni/skills 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +27 -15
- package/CHANGELOG.md +22 -0
- package/README.md +38 -24
- package/bin/install.js +13 -2
- package/package.json +1 -1
- package/plugins/agentic-dev/.claude-plugin/plugin.json +1 -1
- package/plugins/agentic-dev/skills/subagent-driven-development/SKILL.md +6 -4
- package/plugins/agentic-dev/skills/subagent-driven-development/references/dispatch.md +6 -1
- package/plugins/agentic-dev/skills/subagent-driven-development/references/ledger.md +8 -5
- package/plugins/agentic-dev/skills/subagent-driven-development/references/models.md +38 -6
- package/plugins/agentic-dev/skills/subagent-driven-development/scripts/init-workspace.sh +1 -0
- package/plugins/agentic-dev/skills/subagent-driven-development/scripts/model-inventory.sh +6 -4
- package/plugins/claude-pi-subagent/plugins/pi-subagent/package-lock.json +4 -3
- package/plugins/vocdoni-contributing/.claude-plugin/plugin.json +2 -2
- package/plugins/vocdoni-contributing/hooks/session-start.sh +1 -1
- package/plugins/vocdoni-contributing/skills/contributing/SKILL.md +33 -6
- package/plugins/vocdoni-go/.claude-plugin/plugin.json +2 -2
- package/plugins/vocdoni-go/skills/vocdoni-backend-review/SKILL.md +522 -0
- package/plugins/vocdoni-go/skills/vocdoni-backend-review/references/prompts.md +260 -0
- package/plugins/vocdoni-go/skills/vocdoni-backend-review/scripts/untracked-list.sh +35 -0
- package/plugins/vocdoni-sdk/.claude-plugin/plugin.json +4 -5
- package/plugins/vocdoni-sdk/skills/vocdoni-ballot-protocol/SKILL.md +61 -38
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/SKILL.md +35 -21
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/approval-vote.ts +3 -3
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/basic-poll.ts +6 -6
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/csp-vote.ts +12 -7
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/multichoice-vote.ts +3 -3
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/quadratic-vote.ts +3 -3
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/ranked-vote.ts +3 -3
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/weighted-census.ts +3 -3
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/accounts.md +26 -15
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/census.md +9 -10
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/client.md +15 -13
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/csp.md +43 -18
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/elections.md +4 -4
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/errors.md +24 -21
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/removed-features.md +98 -0
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/results.md +0 -1
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/voting.md +30 -34
- package/plugins/vocdoni-sequencer/.claude-plugin/plugin.json +21 -0
- package/plugins/vocdoni-sequencer/skills/vocdoni-sequencer/SKILL.md +169 -0
- package/plugins/vocdoni-sequencer/skills/vocdoni-sequencer/references/removed-routes.md +60 -0
- package/plugins/davinci-sdk/.claude-plugin/plugin.json +0 -13
- package/plugins/davinci-sdk/skills/davinci-sdk/SKILL.md +0 -120
- package/plugins/davinci-sdk/skills/davinci-sdk/recipes/bootstrap.ts +0 -61
- package/plugins/davinci-sdk/skills/davinci-sdk/recipes/cast-vote.ts +0 -78
- package/plugins/davinci-sdk/skills/davinci-sdk/recipes/create-process.ts +0 -102
- package/plugins/davinci-sdk/skills/davinci-sdk/recipes/full-election.ts +0 -128
- package/plugins/davinci-sdk/skills/davinci-sdk/recipes/read-results.ts +0 -73
- package/plugins/davinci-sdk/skills/davinci-sdk/recipes/token-census.ts +0 -111
- package/plugins/davinci-sdk/skills/davinci-sdk/references/ballot-modes.md +0 -125
- package/plugins/davinci-sdk/skills/davinci-sdk/references/census.md +0 -168
- package/plugins/davinci-sdk/skills/davinci-sdk/references/contracts.md +0 -133
- package/plugins/davinci-sdk/skills/davinci-sdk/references/errors.md +0 -83
- package/plugins/davinci-sdk/skills/davinci-sdk/references/process.md +0 -225
- package/plugins/davinci-sdk/skills/davinci-sdk/references/protocol.md +0 -65
- package/plugins/davinci-sdk/skills/davinci-sdk/references/sequencer.md +0 -135
- package/plugins/davinci-sdk/skills/davinci-sdk/references/setup.md +0 -123
- package/plugins/davinci-sdk/skills/davinci-sdk/references/voting.md +0 -128
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/anonymous-vote.ts +0 -108
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/token-census.ts +0 -121
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/anonymous.md +0 -183
- package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/census3.md +0 -308
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
# `references/setup.md` — Install, construct, `init()`, environment
|
|
2
|
-
|
|
3
|
-
Companion to the [[davinci-sdk]] skill. Read this first when starting a Davinci project.
|
|
4
|
-
|
|
5
|
-
## Install
|
|
6
|
-
|
|
7
|
-
```sh
|
|
8
|
-
npm install @vocdoni/davinci-sdk ethers
|
|
9
|
-
# bundled runtime deps: @noble/curves, @noble/hashes, circomlibjs, snarkjs
|
|
10
|
-
```
|
|
11
|
-
|
|
12
|
-
Node ≥ 18 (for global `fetch`) or a modern browser. `ethers` v6 is a peer you import yourself.
|
|
13
|
-
|
|
14
|
-
## Single root import — there are no subpaths
|
|
15
|
-
|
|
16
|
-
```ts
|
|
17
|
-
import {
|
|
18
|
-
DavinciSDK,
|
|
19
|
-
OffchainCensus, OffchainDynamicCensus, CspCensus, OnchainCensus, PublishedCensus,
|
|
20
|
-
CensusOrigin, VoteStatus, TxStatus,
|
|
21
|
-
} from "@vocdoni/davinci-sdk";
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
`@vocdoni/davinci-sdk` exports **only** the package root (its `package.json` `exports` map has a single `"."` entry). Do **not** write `@vocdoni/davinci-sdk/sequencer`, `/contracts`, or `/core` — those paths do not exist.
|
|
25
|
-
|
|
26
|
-
## Construct the facade
|
|
27
|
-
|
|
28
|
-
```ts
|
|
29
|
-
import { JsonRpcProvider, Wallet } from "ethers";
|
|
30
|
-
import { DavinciSDK } from "@vocdoni/davinci-sdk";
|
|
31
|
-
|
|
32
|
-
const sdk = new DavinciSDK({
|
|
33
|
-
signer: new Wallet(PRIVATE_KEY, new JsonRpcProvider(RPC_URL)),
|
|
34
|
-
sequencerUrl: SEQUENCER_API_URL, // required
|
|
35
|
-
censusUrl: CENSUS_API_URL, // optional — only to publish Merkle censuses
|
|
36
|
-
});
|
|
37
|
-
await sdk.init(); // REQUIRED before any other method
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
### `DavinciSDKConfig`
|
|
41
|
-
|
|
42
|
-
```ts
|
|
43
|
-
interface DavinciSDKConfig {
|
|
44
|
-
signer: Signer; // ethers v6 Signer (required)
|
|
45
|
-
sequencerUrl: string; // sequencer REST base URL (required)
|
|
46
|
-
censusUrl?: string; // census service base URL (optional)
|
|
47
|
-
addresses?: { processRegistry?: string }; // override; else fetched from sequencer /info
|
|
48
|
-
censusProviders?: CensusProviders; // custom proof providers (CSP voting needs one)
|
|
49
|
-
verifyCircuitFiles?: boolean; // verify downloaded circuit hashes (default: true)
|
|
50
|
-
verifyProof?: boolean; // verify generated proof before submit (default: true)
|
|
51
|
-
}
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
- **`censusUrl`** is needed only when you build and publish a Merkle census (`OffchainCensus` / `OffchainDynamicCensus`) — i.e. on the *organizer* who calls `createProcess`, and on a *voter* who needs the sequencer to fetch its census proof. It is **not** needed for an organizer using a pre-published / on-chain / CSP census, and you can omit it for voting if you supply a custom `censusProviders`.
|
|
55
|
-
- **Contract addresses are auto-resolved.** Leave `addresses` unset and `init()` reads `processRegistry` for the signer's chain from the sequencer's `/info`. Only set `addresses.processRegistry` to pin a custom deployment.
|
|
56
|
-
- **Keep `verifyCircuitFiles` / `verifyProof` on** (the defaults) unless you have a measured reason: they protect against tampered circuit downloads and malformed proofs.
|
|
57
|
-
|
|
58
|
-
## The signer-vs-provider rule (the #1 setup gotcha)
|
|
59
|
-
|
|
60
|
-
| Operation | Needs `signer.provider`? |
|
|
61
|
-
| -------------------------------------------------------- | ------------------------ |
|
|
62
|
-
| `createProcess`, `createProcessStream` | **Yes** (on-chain tx) |
|
|
63
|
-
| `getProcess` (rich `ProcessInfo` from the contract) | **Yes** |
|
|
64
|
-
| `endProcess`/`pauseProcess`/`cancelProcess`/`resumeProcess`/`setProcessMaxVoters` | **Yes** |
|
|
65
|
-
| `submitVote` | No — bare `Wallet` is fine |
|
|
66
|
-
| `getVoteStatus`/`watchVoteStatus`/`waitForVoteStatus` | No |
|
|
67
|
-
| `hasAddressVoted`/`isAddressAbleToVote`/`getAddressWeight`| No |
|
|
68
|
-
| `sdk.api.sequencer.getProcess` (lightweight, REST) | No |
|
|
69
|
-
|
|
70
|
-
So an **organizer** wallet must be `new Wallet(pk, provider)`; a **voter** wallet can be `new Wallet(pk)`. Calling an on-chain method without a provider throws: *"Provider required for blockchain operations…"*. To act as two different people in one script, build two `DavinciSDK` instances.
|
|
71
|
-
|
|
72
|
-
```ts
|
|
73
|
-
// organizer (on-chain) — provider required
|
|
74
|
-
const organizer = new DavinciSDK({ signer: new Wallet(pk, provider), sequencerUrl, censusUrl });
|
|
75
|
-
// voter (voting only) — no provider
|
|
76
|
-
const voter = new DavinciSDK({ signer: new Wallet(voterPk), sequencerUrl, censusUrl });
|
|
77
|
-
await organizer.init(); await voter.init();
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
## Environment variables (from the SDK's example `.env`)
|
|
81
|
-
|
|
82
|
-
```
|
|
83
|
-
SEQUENCER_API_URL=https://sequencer-dev.davinci.vote # sequencer REST base URL
|
|
84
|
-
CENSUS_API_URL=https://c3-dev.davinci.vote # census service base URL
|
|
85
|
-
RPC_URL=https://... # ethers JsonRpcProvider endpoint
|
|
86
|
-
PRIVATE_KEY=... # organizer/voter EOA key (no 0x ok)
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
Known endpoints (verify against current docs / the sequencer's `/info`):
|
|
90
|
-
|
|
91
|
-
| Env | Sequencer | Census |
|
|
92
|
-
| -------- | -------------------------------------- | ---------------------------- |
|
|
93
|
-
| Dev | `https://sequencer-dev.davinci.vote` | `https://c3-dev.davinci.vote`|
|
|
94
|
-
| Staging | `https://sequencer1.davinci.vote` | (per docs) |
|
|
95
|
-
|
|
96
|
-
The **chain is determined by the sequencer**, not by you — the RPC must point at the chain the sequencer expects. The voter/organizer needs testnet gas on that chain to create/end processes (voting itself is gasless for the voter — it goes to the sequencer, not on-chain).
|
|
97
|
-
|
|
98
|
-
## ethers v6 (this SDK is v6, not v5)
|
|
99
|
-
|
|
100
|
-
| v5 (legacy `@vocdoni/sdk`) | v6 (Davinci SDK) |
|
|
101
|
-
| ------------------------------------------- | ----------------------------------------- |
|
|
102
|
-
| `new ethers.providers.JsonRpcProvider(url)` | `new ethers.JsonRpcProvider(url)` |
|
|
103
|
-
| `ethers.utils.parseUnits(...)` | `ethers.parseUnits(...)` |
|
|
104
|
-
| `BigNumber` | native `bigint` |
|
|
105
|
-
| `provider.getNetwork()` → `{chainId: number}` | → `{chainId: bigint}` (use `Number(...)`)|
|
|
106
|
-
|
|
107
|
-
## Sanity check after `init()`
|
|
108
|
-
|
|
109
|
-
```ts
|
|
110
|
-
const info = await sdk.api.sequencer.getInfo(); // reachable? which chains/circuits?
|
|
111
|
-
const net = await provider.getNetwork();
|
|
112
|
-
const supported = Object.values(info.networks).some(n => n.chainID === Number(net.chainId));
|
|
113
|
-
console.assert(supported, "RPC chain not supported by this sequencer");
|
|
114
|
-
```
|
|
115
|
-
|
|
116
|
-
A chain mismatch here is the root cause of most later "process not found" / proof-verification failures.
|
|
117
|
-
|
|
118
|
-
## Cross-references
|
|
119
|
-
|
|
120
|
-
- `references/process.md` — `createProcess` and lifecycle.
|
|
121
|
-
- `references/census.md` — which census class, and the `maxVoters` rule.
|
|
122
|
-
- `references/voting.md` — the encrypted-vote flow.
|
|
123
|
-
- `recipes/bootstrap.ts` — this wiring as a runnable file.
|
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
# `references/voting.md` — Casting an encrypted vote
|
|
2
|
-
|
|
3
|
-
Companion to the [[davinci-sdk]] skill. Casting a vote is the part most likely to confuse, but the `DavinciSDK` facade hides all the cryptography: you supply `choices`, it builds the ballot, ElGamal-encrypts it, generates the zk-SNARK proof, signs, and submits. None of `submitVote`'s methods need a provider — a bare `Wallet` is enough.
|
|
4
|
-
|
|
5
|
-
## Act as the voter
|
|
6
|
-
|
|
7
|
-
The SDK votes **as its `signer`**. To cast a voter's ballot, construct a `DavinciSDK` with that voter's wallet:
|
|
8
|
-
|
|
9
|
-
```ts
|
|
10
|
-
import { DavinciSDK, VoteStatus } from "@vocdoni/davinci-sdk";
|
|
11
|
-
import { Wallet } from "ethers";
|
|
12
|
-
|
|
13
|
-
const voter = new DavinciSDK({
|
|
14
|
-
signer: new Wallet(VOTER_PRIVATE_KEY), // no provider needed for voting
|
|
15
|
-
sequencerUrl: SEQUENCER_API_URL,
|
|
16
|
-
censusUrl: CENSUS_API_URL, // needed so the SDK can fetch the census proof
|
|
17
|
-
});
|
|
18
|
-
await voter.init();
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
(`censusUrl` is required for voting on Merkle censuses unless you pass a custom `censusProviders`. CSP censuses need a `censusProviders.csp` — see `references/census.md`.)
|
|
22
|
-
|
|
23
|
-
## Submit
|
|
24
|
-
|
|
25
|
-
```ts
|
|
26
|
-
const result = await voter.submitVote({
|
|
27
|
-
processId,
|
|
28
|
-
choices: [1, 0], // length MUST equal the process's ballot.numFields
|
|
29
|
-
// randomness?: string // optional; auto-generated if omitted
|
|
30
|
-
});
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
### `VoteConfig` / `VoteResult`
|
|
34
|
-
|
|
35
|
-
```ts
|
|
36
|
-
interface VoteConfig {
|
|
37
|
-
processId: string;
|
|
38
|
-
choices: number[]; // one integer per ballot field
|
|
39
|
-
randomness?: string; // optional hex/decimal entropy for encryption (the "k")
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
interface VoteResult {
|
|
43
|
-
voteId: string; // track this
|
|
44
|
-
signature: string;
|
|
45
|
-
voterAddress: string;
|
|
46
|
-
processId: string;
|
|
47
|
-
status: VoteStatus; // initial status, usually "pending"
|
|
48
|
-
}
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
### The `choices` model (read this before guessing)
|
|
52
|
-
|
|
53
|
-
`choices` is a flat array of integers, **one per ballot field**, and `choices.length` must equal `ballot.numFields`. Each integer must lie in `[ballot.minValue, ballot.maxValue]` (the SDK validates this and throws "Choice X is out of range" otherwise).
|
|
54
|
-
|
|
55
|
-
- **Single-choice question, N options** → encoded one-hot as N fields. To pick option *j*, send an array of N zeros with a 1 at index *j*: `[0,0,1,0]` picks option 2.
|
|
56
|
-
- **Weighted voting** → put the voter's weight at the chosen index instead of 1: `[0, 5, 0, 0]`.
|
|
57
|
-
- **Multiple questions** → concatenate each question's fields: two 4-option questions → `numFields: 8`, `choices: [...q1(4), ...q2(4)]`.
|
|
58
|
-
- **Approval / ranked / quadratic / budget** → the field meaning changes per ballot mode; see `references/ballot-modes.md`.
|
|
59
|
-
|
|
60
|
-
`submitVote` internally fetches the live process (must be `isAcceptingVotes` or it throws *"Process is not currently accepting votes"*), gets the voter's census weight/proof, encrypts, proves, and submits.
|
|
61
|
-
|
|
62
|
-
## The two-phase status flow
|
|
63
|
-
|
|
64
|
-
`submitVote` returns as soon as the sequencer accepts the payload — the vote is **not yet counted**. It progresses through `VoteStatus`:
|
|
65
|
-
|
|
66
|
-
```ts
|
|
67
|
-
enum VoteStatus {
|
|
68
|
-
Pending = "pending", // received by sequencer
|
|
69
|
-
Verified = "verified", // proof + signature checked
|
|
70
|
-
Aggregated = "aggregated", // included in a batch
|
|
71
|
-
Processed = "processed", // state transition applied
|
|
72
|
-
Settled = "settled", // finalized on-chain — it counts
|
|
73
|
-
Error = "error", // rejected
|
|
74
|
-
}
|
|
75
|
-
```
|
|
76
|
-
|
|
77
|
-
Always wait for it to settle:
|
|
78
|
-
|
|
79
|
-
```ts
|
|
80
|
-
const final = await voter.waitForVoteStatus(
|
|
81
|
-
processId, result.voteId,
|
|
82
|
-
VoteStatus.Settled, // target (default: Settled)
|
|
83
|
-
300_000, // timeout ms (default 300_000 = 5 min) — settlement can take minutes
|
|
84
|
-
5_000, // poll interval ms (default 5_000)
|
|
85
|
-
);
|
|
86
|
-
// final: VoteStatusInfo { voteId, status, processId }
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
> Settlement depends on the sequencer batching and submitting a state transition; under light load it can take several minutes. For many votes, bump the timeout (the SDK's own demo uses ~800_000ms per vote).
|
|
90
|
-
|
|
91
|
-
### Stream status changes (for UI)
|
|
92
|
-
|
|
93
|
-
```ts
|
|
94
|
-
for await (const s of voter.watchVoteStatus(processId, voteId, {
|
|
95
|
-
targetStatus: VoteStatus.Settled, timeoutMs: 800_000, pollIntervalMs: 5_000,
|
|
96
|
-
})) {
|
|
97
|
-
console.log(s.status); // yields only on change
|
|
98
|
-
if (s.status === VoteStatus.Error) throw new Error("vote rejected");
|
|
99
|
-
}
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
`waitForVoteStatus` is `watchVoteStatus` consumed for you, returning the final status. A one-off poll: `await voter.getVoteStatus(processId, voteId)` → `{ voteId, status, processId }`.
|
|
103
|
-
|
|
104
|
-
## Eligibility & dedup checks (no provider needed)
|
|
105
|
-
|
|
106
|
-
```ts
|
|
107
|
-
await sdk.isAddressAbleToVote(processId, address); // boolean — in the census?
|
|
108
|
-
await sdk.hasAddressVoted(processId, address); // boolean — already voted?
|
|
109
|
-
await sdk.getAddressWeight(processId, address); // string — voting weight ("0" if none)
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
Use `isAddressAbleToVote` before submitting to give a clean "not eligible" message instead of a thrown error. Voters may **overwrite** their vote during the voting period (last-vote-wins) — `hasAddressVoted` true doesn't prevent re-voting.
|
|
113
|
-
|
|
114
|
-
## Custom randomness
|
|
115
|
-
|
|
116
|
-
`randomness` seeds the ElGamal encryption nonce (`k`) and the vote-id derivation. Omit it (recommended) to let the SDK sample fresh entropy. Supply it only for reproducible tests; reusing the same `k` across votes is unsafe.
|
|
117
|
-
|
|
118
|
-
## Verification toggles (from SDK config)
|
|
119
|
-
|
|
120
|
-
`verifyCircuitFiles` (default true) checks the SHA-256 of downloaded circuit artifacts against the hashes in the sequencer's `/info`; `verifyProof` (default true) verifies the generated proof locally before submitting. Leave both on unless profiling shows a need.
|
|
121
|
-
|
|
122
|
-
## Cross-references
|
|
123
|
-
|
|
124
|
-
- `references/ballot-modes.md` — what `choices` means under each voting system.
|
|
125
|
-
- `references/census.md` — CSP voting providers; how the census proof is fetched.
|
|
126
|
-
- `references/sequencer.md` — the REST calls underneath (`submitVote`, `getVoteStatus`, `getProcess`).
|
|
127
|
-
- `references/errors.md` — "not accepting votes", out-of-range, proof failures.
|
|
128
|
-
- `recipes/cast-vote.ts`.
|
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* recipes/anonymous-vote.ts
|
|
3
|
-
*
|
|
4
|
-
* Anonymous voting using zero-knowledge proofs. Each voter registers a Secret
|
|
5
|
-
* Identity Key (SIK) and submits an AnonymousVote; the chain verifies the
|
|
6
|
-
* voter is in the census and hasn't voted before, without learning who they are.
|
|
7
|
-
*
|
|
8
|
-
* Key differences from basic-poll.ts:
|
|
9
|
-
* - electionType.anonymous = true
|
|
10
|
-
* - Each voter calls createAccount({ sik: true, password })
|
|
11
|
-
* - submitVote receives an AnonymousVote (with the same password)
|
|
12
|
-
* - hasAlreadyVoted / votesLeftCount need an explicit voteId on this election
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import { Wallet } from '@ethersproject/wallet';
|
|
16
|
-
import {
|
|
17
|
-
AnonymousVote,
|
|
18
|
-
Election,
|
|
19
|
-
ElectionStatus,
|
|
20
|
-
EnvOptions,
|
|
21
|
-
VocdoniSDKClient,
|
|
22
|
-
WeightedCensus,
|
|
23
|
-
} from '@vocdoni/sdk';
|
|
24
|
-
|
|
25
|
-
const VOTERS_NUM = 5;
|
|
26
|
-
// Use a non-default password to make the SIK derivation explicit
|
|
27
|
-
const SIK_PASSWORD = 'demo-password';
|
|
28
|
-
|
|
29
|
-
async function waitForElectionReady(c: VocdoniSDKClient, id: string) {
|
|
30
|
-
while ((await c.fetchElection(id)).status !== ElectionStatus.ONGOING) {
|
|
31
|
-
await new Promise((r) => setTimeout(r, 5_000));
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
async function main() {
|
|
36
|
-
// 1. Creator
|
|
37
|
-
const creator = Wallet.createRandom();
|
|
38
|
-
const client = new VocdoniSDKClient({ env: EnvOptions.STG, wallet: creator });
|
|
39
|
-
await client.createAccount();
|
|
40
|
-
|
|
41
|
-
// 2. Voters + anonymous census. Same WeightedCensus code as a regular one —
|
|
42
|
-
// the election's `anonymous: true` flag causes it to be published as
|
|
43
|
-
// CensusType.ANONYMOUS at createElection() time.
|
|
44
|
-
const voters = Array.from({ length: VOTERS_NUM }, () => Wallet.createRandom());
|
|
45
|
-
const census = new WeightedCensus();
|
|
46
|
-
census.add(voters.map((v) => ({ key: v.address, weight: BigInt(1) })));
|
|
47
|
-
|
|
48
|
-
// 3. Election with anonymous = true
|
|
49
|
-
const election = Election.from({
|
|
50
|
-
title: 'Secret ballot',
|
|
51
|
-
description: 'Anonymous yes/no',
|
|
52
|
-
endDate: new Date(Date.now() + 60 * 60 * 1000),
|
|
53
|
-
census,
|
|
54
|
-
maxCensusSize: voters.length,
|
|
55
|
-
electionType: { anonymous: true },
|
|
56
|
-
});
|
|
57
|
-
election.addQuestion('Approve?', '', [
|
|
58
|
-
{ title: 'Yes', value: 0 },
|
|
59
|
-
{ title: 'No', value: 1 },
|
|
60
|
-
]);
|
|
61
|
-
|
|
62
|
-
const electionId = await client.createElection(election);
|
|
63
|
-
client.setElectionId(electionId);
|
|
64
|
-
console.log(`Election created: ${client.explorerUrl}/processes/show/#/${electionId}`);
|
|
65
|
-
|
|
66
|
-
await waitForElectionReady(client, electionId);
|
|
67
|
-
|
|
68
|
-
// 4. Each voter: register SIK then vote
|
|
69
|
-
const voteIds: string[] = [];
|
|
70
|
-
for (let i = 0; i < voters.length; i++) {
|
|
71
|
-
const voter = voters[i];
|
|
72
|
-
const voterClient = new VocdoniSDKClient({
|
|
73
|
-
env: EnvOptions.STG,
|
|
74
|
-
wallet: voter,
|
|
75
|
-
electionId,
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
// Register the SIK on the chain. Same password must be used at vote time.
|
|
79
|
-
await voterClient.createAccount({ sik: true, password: SIK_PASSWORD });
|
|
80
|
-
|
|
81
|
-
// Submit the anonymous vote. Pass undefined for signature so the SDK
|
|
82
|
-
// derives it from voterClient.wallet via signSIKPayload.
|
|
83
|
-
const vote = new AnonymousVote([i % 2], undefined, SIK_PASSWORD);
|
|
84
|
-
const voteId = await voterClient.submitVote(vote);
|
|
85
|
-
voteIds.push(voteId);
|
|
86
|
-
console.log(`voter ${i} voted: ${voteId}`);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// 5. Read results. NOTE: hasAlreadyVoted on an anonymous election needs the
|
|
90
|
-
// voteId because the nullifier isn't recoverable from address alone.
|
|
91
|
-
const result = await client.fetchElection();
|
|
92
|
-
console.log('Tallies:', result.results);
|
|
93
|
-
|
|
94
|
-
// Example: check voter 0 already voted
|
|
95
|
-
const stillCount = await client.votesLeftCount({
|
|
96
|
-
wallet: voters[0],
|
|
97
|
-
voteId: voteIds[0],
|
|
98
|
-
});
|
|
99
|
-
console.log(`voter 0 has ${stillCount} votes left`);
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
main().then(
|
|
103
|
-
() => process.exit(0),
|
|
104
|
-
(err) => {
|
|
105
|
-
console.error(err);
|
|
106
|
-
process.exit(1);
|
|
107
|
-
},
|
|
108
|
-
);
|
|
@@ -1,121 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* recipes/token-census.ts
|
|
3
|
-
*
|
|
4
|
-
* Create an election whose voters are holders of an on-chain ERC20/721 token,
|
|
5
|
-
* using Census3 to materialise the merkle census.
|
|
6
|
-
*
|
|
7
|
-
* Two flavours shown:
|
|
8
|
-
* A) Single-token census — createTokenCensus
|
|
9
|
-
* B) Strategy-based census — createStrategyCensus (with a predicate)
|
|
10
|
-
*
|
|
11
|
-
* Holders cast votes from their own wallets like a normal Vocdoni election.
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
import { Wallet } from '@ethersproject/wallet';
|
|
15
|
-
import {
|
|
16
|
-
Election,
|
|
17
|
-
ElectionStatus,
|
|
18
|
-
EnvOptions,
|
|
19
|
-
StrategyCensus,
|
|
20
|
-
TokenCensus,
|
|
21
|
-
VocdoniCensus3Client,
|
|
22
|
-
VocdoniSDKClient,
|
|
23
|
-
Vote,
|
|
24
|
-
} from '@vocdoni/sdk';
|
|
25
|
-
|
|
26
|
-
async function waitForElectionReady(c: VocdoniSDKClient, id: string) {
|
|
27
|
-
while ((await c.fetchElection(id)).status !== ElectionStatus.ONGOING) {
|
|
28
|
-
await new Promise((r) => setTimeout(r, 5_000));
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
async function createSingleTokenCensus(census3: VocdoniCensus3Client): Promise<TokenCensus> {
|
|
33
|
-
// YAM token on Ethereum mainnet (chainID 1). Replace as needed.
|
|
34
|
-
const TOKEN = '0x0AaCfbeC6a24756c20D41914F2caba817C0d8521';
|
|
35
|
-
const CHAIN_ID = 1;
|
|
36
|
-
|
|
37
|
-
// Verify the token is synced before building a census against it.
|
|
38
|
-
const tokenInfo = await census3.getToken(TOKEN, CHAIN_ID);
|
|
39
|
-
if (!tokenInfo.status.synced) {
|
|
40
|
-
throw new Error(`Token ${TOKEN} not yet synced (progress ${tokenInfo.status.progress}%)`);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// Long-running: polls the Census3 queue until the merkle tree is ready.
|
|
44
|
-
return census3.createTokenCensus(TOKEN, CHAIN_ID);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
async function createStrategyTokenCensus(census3: VocdoniCensus3Client): Promise<StrategyCensus> {
|
|
48
|
-
// Example: holders of (YAM AND API3) on Ethereum mainnet.
|
|
49
|
-
const strategyId = await census3.createStrategy(
|
|
50
|
-
`demo-${Date.now()}`,
|
|
51
|
-
'(YAM AND API3)',
|
|
52
|
-
{
|
|
53
|
-
YAM: { ID: '0x0AaCfbeC6a24756c20D41914F2caba817C0d8521', chainID: 1, minBalance: '1' },
|
|
54
|
-
API3: { ID: '0x0b38210ea11411557c13457D4dA7dC6ea731B88a', chainID: 1, minBalance: '1' },
|
|
55
|
-
},
|
|
56
|
-
);
|
|
57
|
-
|
|
58
|
-
const estimate = await census3.getStrategyEstimation(strategyId);
|
|
59
|
-
console.log(`Strategy ${strategyId} estimated size: ${estimate.size}`);
|
|
60
|
-
|
|
61
|
-
return census3.createStrategyCensus(strategyId);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
async function main() {
|
|
65
|
-
// Use PROD for real token data. Switch to STG/DEV if you have testnet tokens.
|
|
66
|
-
const census3 = new VocdoniCensus3Client({
|
|
67
|
-
env: EnvOptions.PROD,
|
|
68
|
-
tx_wait: { retry_time: 3000, attempts: 30 }, // larger censuses take longer
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
const creator = Wallet.createRandom();
|
|
72
|
-
const vocdoni = new VocdoniSDKClient({ env: EnvOptions.PROD, wallet: creator });
|
|
73
|
-
// On PROD you must pass a real faucet package:
|
|
74
|
-
// await vocdoni.createAccount({ faucetPackage: '<base64>' });
|
|
75
|
-
// Use STG instead for an env where createAccount() auto-funds:
|
|
76
|
-
// const vocdoni = new VocdoniSDKClient({ env: EnvOptions.STG, wallet: creator });
|
|
77
|
-
await vocdoni.createAccount();
|
|
78
|
-
|
|
79
|
-
// Pick one flavour:
|
|
80
|
-
const census = await createSingleTokenCensus(census3);
|
|
81
|
-
// const census = await createStrategyTokenCensus(census3);
|
|
82
|
-
|
|
83
|
-
const election = Election.from({
|
|
84
|
-
title: 'Token holders vote',
|
|
85
|
-
description: `Holders of ${census.token.symbol} (chain ${census.token.chainID})`,
|
|
86
|
-
endDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
|
87
|
-
census, // TokenCensus or StrategyCensus extends PublishedCensus
|
|
88
|
-
maxCensusSize: census.size, // pin to the snapshot size
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
election.addQuestion('Proposal X?', '', [
|
|
92
|
-
{ title: 'Yes', value: 0 },
|
|
93
|
-
{ title: 'No', value: 1 },
|
|
94
|
-
]);
|
|
95
|
-
|
|
96
|
-
const electionId = await vocdoni.createElection(election);
|
|
97
|
-
console.log(`Election created: ${vocdoni.explorerUrl}/processes/show/#/${electionId}`);
|
|
98
|
-
|
|
99
|
-
// Voting: each holder uses their own wallet (the one that holds the token).
|
|
100
|
-
// The SDK will fetch the relevant proof from the census published by Census3.
|
|
101
|
-
//
|
|
102
|
-
// const voterClient = new VocdoniSDKClient({
|
|
103
|
-
// env: EnvOptions.PROD,
|
|
104
|
-
// wallet: holderWallet,
|
|
105
|
-
// electionId,
|
|
106
|
-
// });
|
|
107
|
-
// await voterClient.submitVote(new Vote([0]));
|
|
108
|
-
//
|
|
109
|
-
// Voting weight = holder's token balance at the snapshot block.
|
|
110
|
-
|
|
111
|
-
await waitForElectionReady(vocdoni, electionId);
|
|
112
|
-
console.log('Election is ONGOING; holders can now vote.');
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
main().then(
|
|
116
|
-
() => process.exit(0),
|
|
117
|
-
(err) => {
|
|
118
|
-
console.error(err);
|
|
119
|
-
process.exit(1);
|
|
120
|
-
},
|
|
121
|
-
);
|
|
@@ -1,183 +0,0 @@
|
|
|
1
|
-
# `references/anonymous.md` — Anonymous (ZK) voting
|
|
2
|
-
|
|
3
|
-
Companion to the [[vocdoni-sdk]] skill. Use this when the election should hide *who voted for what* using zero-knowledge proofs. Read `voting.md` and `census.md` first for the baseline; this builds on both.
|
|
4
|
-
|
|
5
|
-
## When to use anonymous voting
|
|
6
|
-
|
|
7
|
-
The voter's identity is hidden even from the chain. Useful for:
|
|
8
|
-
|
|
9
|
-
- Confidential governance ballots where stakeholder identities are sensitive.
|
|
10
|
-
- Whistleblower polls.
|
|
11
|
-
- Any case where coercion-resistance is more important than auditing per-voter votes.
|
|
12
|
-
|
|
13
|
-
Trade-offs: extra setup per voter (SIK signature, ZK proof generation), heavier client-side compute (Groth16 prover via WASM), slightly higher election creation cost.
|
|
14
|
-
|
|
15
|
-
## How it works (intuition)
|
|
16
|
-
|
|
17
|
-
- Voters publish a one-time **Secret Identity Key (SIK)** to the chain, derived from `(address, signature, password)`. The address ↔ SIK link is not derivable without the signature.
|
|
18
|
-
- The census is a merkle tree of *(address, weight)* pairs, just like a `WeightedCensus`, but published with `CensusType.ANONYMOUS`.
|
|
19
|
-
- When voting, the voter produces a **ZK proof** that:
|
|
20
|
-
- "I know a SIK in the SIK tree and an address in the census tree with weight ≥ what I'm spending."
|
|
21
|
-
- "My nullifier matches `Poseidon(signature, password, electionId)`" — so the chain can detect double-voting without learning the address.
|
|
22
|
-
- The chain verifies the proof and accepts the vote without learning the voter.
|
|
23
|
-
|
|
24
|
-
The SDK abstracts most of this. You as the agent:
|
|
25
|
-
|
|
26
|
-
1. Mark the election anonymous.
|
|
27
|
-
2. Build an anonymous census (same code as `WeightedCensus`, the census service picks the type).
|
|
28
|
-
3. Ensure each voter has a SIK registered (call once per voter per password).
|
|
29
|
-
4. Submit `AnonymousVote` instead of `Vote`.
|
|
30
|
-
|
|
31
|
-
## Creating an anonymous election
|
|
32
|
-
|
|
33
|
-
```ts
|
|
34
|
-
import { Election, EnvOptions, VocdoniSDKClient, WeightedCensus } from '@vocdoni/sdk';
|
|
35
|
-
|
|
36
|
-
const census = new WeightedCensus();
|
|
37
|
-
for (const voter of voters) {
|
|
38
|
-
census.add({ key: voter.address, weight: BigInt(1) });
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
const election = Election.from({
|
|
42
|
-
title: 'Secret ballot',
|
|
43
|
-
endDate: new Date(Date.now() + 24 * 3600 * 1000),
|
|
44
|
-
census,
|
|
45
|
-
electionType: {
|
|
46
|
-
anonymous: true,
|
|
47
|
-
},
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
election.addQuestion('Yes or no?', '', [
|
|
51
|
-
{ title: 'Yes', value: 0 },
|
|
52
|
-
{ title: 'No', value: 1 },
|
|
53
|
-
]);
|
|
54
|
-
|
|
55
|
-
const electionId = await client.createElection(election);
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
The election creation logic picks the right `CensusType.ANONYMOUS` automatically when `electionType.anonymous` is set.
|
|
59
|
-
|
|
60
|
-
## Voter setup: registering the SIK
|
|
61
|
-
|
|
62
|
-
Each voter needs a Secret Identity Key on chain *before* their first anonymous vote. The SDK does this implicitly during `createAccount`:
|
|
63
|
-
|
|
64
|
-
```ts
|
|
65
|
-
// As the voter:
|
|
66
|
-
const voterClient = new VocdoniSDKClient({ env: EnvOptions.STG, wallet: voterWallet });
|
|
67
|
-
await voterClient.createAccount({
|
|
68
|
-
sik: true, // default true; explicit for clarity
|
|
69
|
-
password: 'optional-pwd', // default '0'
|
|
70
|
-
});
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
If you want to check whether a SIK already exists for a given (address, signature, password):
|
|
74
|
-
|
|
75
|
-
```ts
|
|
76
|
-
const signature = await client.anonymousService.signSIKPayload(voterWallet);
|
|
77
|
-
const exists = await client.anonymousService.hasRegisteredSIK(
|
|
78
|
-
voterWallet.address,
|
|
79
|
-
signature,
|
|
80
|
-
'optional-pwd', // same one used at registration
|
|
81
|
-
);
|
|
82
|
-
```
|
|
83
|
-
|
|
84
|
-
The signed payload (`signSIKPayload`) is constant text:
|
|
85
|
-
|
|
86
|
-
> `This signature request is used to create your own secret identity key...`
|
|
87
|
-
|
|
88
|
-
Same wallet + same password → same SIK. Same wallet + different password → different SIK. Voters using a single password are effectively a single identity across elections; voters using a unique per-election password get election-specific identities.
|
|
89
|
-
|
|
90
|
-
## Casting an anonymous vote
|
|
91
|
-
|
|
92
|
-
```ts
|
|
93
|
-
import { AnonymousVote } from '@vocdoni/sdk';
|
|
94
|
-
|
|
95
|
-
// As the voter
|
|
96
|
-
const voterClient = new VocdoniSDKClient({
|
|
97
|
-
env: EnvOptions.STG,
|
|
98
|
-
wallet: voterWallet,
|
|
99
|
-
electionId,
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
const vote = new AnonymousVote(
|
|
103
|
-
[0], // ballot — same shape rules as base Vote
|
|
104
|
-
undefined, // signature — let the SDK derive from client.wallet
|
|
105
|
-
'optional-pwd', // must match the one used at SIK registration
|
|
106
|
-
);
|
|
107
|
-
|
|
108
|
-
const voteId = await voterClient.submitVote(vote);
|
|
109
|
-
```
|
|
110
|
-
|
|
111
|
-
Internally `submitVote` will:
|
|
112
|
-
|
|
113
|
-
1. Sign the SIK payload (or use the provided `signature`).
|
|
114
|
-
2. Fetch the voter's census proof + SIK proof.
|
|
115
|
-
3. Compute a nullifier and prepare circuit inputs.
|
|
116
|
-
4. Generate a Groth16 ZK proof (downloads the circuit on first use).
|
|
117
|
-
5. Submit the encoded transaction.
|
|
118
|
-
|
|
119
|
-
If you want to see progress (proof generation can take a couple of seconds), use `submitVoteSteps` — the `'calc-zk-proof'` step is the heavy one.
|
|
120
|
-
|
|
121
|
-
## Vote IDs are not deterministic
|
|
122
|
-
|
|
123
|
-
For regular elections, the vote ID equals `keccak256(address || electionId)` so the SDK can recompute it. For anonymous, the nullifier comes from `(signature, password, electionId)`, and the SDK needs the *signature* to recompute — which it doesn't keep across sessions.
|
|
124
|
-
|
|
125
|
-
This means `hasAlreadyVoted` / `votesLeftCount` / `isAbleToVote` **must receive `voteId`** explicitly when called against an anonymous election:
|
|
126
|
-
|
|
127
|
-
```ts
|
|
128
|
-
await client.hasAlreadyVoted({ voteId: '<the vote id you got from submitVote>' });
|
|
129
|
-
```
|
|
130
|
-
|
|
131
|
-
Save the vote ID at submission time if you want to let voters check status later.
|
|
132
|
-
|
|
133
|
-
## Circuits
|
|
134
|
-
|
|
135
|
-
ZK voting uses public proving/verifying keys (Groth16) and a WASM circuit. The SDK fetches them from the chain on first use and verifies their hashes match what the chain expects:
|
|
136
|
-
|
|
137
|
-
```ts
|
|
138
|
-
const circuits = await client.anonymousService.fetchCircuits();
|
|
139
|
-
// Object containing: zKeyData, zKeyHash, zKeyURI, vKeyData, vKeyHash, vKeyURI, wasmData, wasmHash, wasmURI
|
|
140
|
-
```
|
|
141
|
-
|
|
142
|
-
You almost never call this directly — first vote triggers it. If you want to ship the circuits with your bundle (avoid first-vote latency), pass them via `client.anonymousService.setCircuits(precomputedCircuits)`.
|
|
143
|
-
|
|
144
|
-
## `AnonymousVote` reference
|
|
145
|
-
|
|
146
|
-
```ts
|
|
147
|
-
class AnonymousVote extends Vote {
|
|
148
|
-
constructor(
|
|
149
|
-
votes: Array<number | bigint>,
|
|
150
|
-
signature?: string, // optional; SDK derives via signSIKPayload(client.wallet) if absent
|
|
151
|
-
password?: string, // default '0'
|
|
152
|
-
);
|
|
153
|
-
signature?: string;
|
|
154
|
-
password?: string;
|
|
155
|
-
}
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
## Encrypted-until-end + anonymous
|
|
159
|
-
|
|
160
|
-
Both can be on:
|
|
161
|
-
|
|
162
|
-
```ts
|
|
163
|
-
electionType: {
|
|
164
|
-
anonymous: true,
|
|
165
|
-
secretUntilTheEnd: true,
|
|
166
|
-
}
|
|
167
|
-
```
|
|
168
|
-
|
|
169
|
-
Then votes are ballot-encrypted *and* identity-hidden — even live tallies are hidden until the election ends.
|
|
170
|
-
|
|
171
|
-
## Pitfalls
|
|
172
|
-
|
|
173
|
-
- **Password discipline matters.** A voter who uses a different password than at SIK registration gets `"hasRegisteredSIK = false"` and can't vote.
|
|
174
|
-
- **Anonymous census ≠ anonymous election.** `electionType.anonymous = true` tells the SDK to publish the census as `ANONYMOUS` — but if you reuse a pre-published `PublishedCensus` of type `WEIGHTED`, voting will fail. Either build the census in the same flow as the election, or ensure the existing census was published as `ANONYMOUS`.
|
|
175
|
-
- **First vote downloads ~MBs of circuit data.** Pre-fetch in production frontends.
|
|
176
|
-
- **Vote ID is the nullifier.** Save it; voters can't look it up later otherwise.
|
|
177
|
-
|
|
178
|
-
## Cross-references
|
|
179
|
-
|
|
180
|
-
- `elections.md` — base election creation (set `electionType.anonymous`).
|
|
181
|
-
- `census.md` — `WeightedCensus` is what backs anonymous elections; publishing produces `CensusType.ANONYMOUS` when the election is anonymous.
|
|
182
|
-
- `voting.md` — `submitVote` accepts `AnonymousVote` directly.
|
|
183
|
-
- `recipes/anonymous-vote.ts` — runnable end-to-end example.
|