@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.
Files changed (63) hide show
  1. package/.claude-plugin/marketplace.json +27 -15
  2. package/CHANGELOG.md +22 -0
  3. package/README.md +38 -24
  4. package/bin/install.js +13 -2
  5. package/package.json +1 -1
  6. package/plugins/agentic-dev/.claude-plugin/plugin.json +1 -1
  7. package/plugins/agentic-dev/skills/subagent-driven-development/SKILL.md +6 -4
  8. package/plugins/agentic-dev/skills/subagent-driven-development/references/dispatch.md +6 -1
  9. package/plugins/agentic-dev/skills/subagent-driven-development/references/ledger.md +8 -5
  10. package/plugins/agentic-dev/skills/subagent-driven-development/references/models.md +38 -6
  11. package/plugins/agentic-dev/skills/subagent-driven-development/scripts/init-workspace.sh +1 -0
  12. package/plugins/agentic-dev/skills/subagent-driven-development/scripts/model-inventory.sh +6 -4
  13. package/plugins/claude-pi-subagent/plugins/pi-subagent/package-lock.json +4 -3
  14. package/plugins/vocdoni-contributing/.claude-plugin/plugin.json +2 -2
  15. package/plugins/vocdoni-contributing/hooks/session-start.sh +1 -1
  16. package/plugins/vocdoni-contributing/skills/contributing/SKILL.md +33 -6
  17. package/plugins/vocdoni-go/.claude-plugin/plugin.json +2 -2
  18. package/plugins/vocdoni-go/skills/vocdoni-backend-review/SKILL.md +522 -0
  19. package/plugins/vocdoni-go/skills/vocdoni-backend-review/references/prompts.md +260 -0
  20. package/plugins/vocdoni-go/skills/vocdoni-backend-review/scripts/untracked-list.sh +35 -0
  21. package/plugins/vocdoni-sdk/.claude-plugin/plugin.json +4 -5
  22. package/plugins/vocdoni-sdk/skills/vocdoni-ballot-protocol/SKILL.md +61 -38
  23. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/SKILL.md +35 -21
  24. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/approval-vote.ts +3 -3
  25. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/basic-poll.ts +6 -6
  26. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/csp-vote.ts +12 -7
  27. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/multichoice-vote.ts +3 -3
  28. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/quadratic-vote.ts +3 -3
  29. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/ranked-vote.ts +3 -3
  30. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/weighted-census.ts +3 -3
  31. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/accounts.md +26 -15
  32. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/census.md +9 -10
  33. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/client.md +15 -13
  34. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/csp.md +43 -18
  35. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/elections.md +4 -4
  36. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/errors.md +24 -21
  37. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/removed-features.md +98 -0
  38. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/results.md +0 -1
  39. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/voting.md +30 -34
  40. package/plugins/vocdoni-sequencer/.claude-plugin/plugin.json +21 -0
  41. package/plugins/vocdoni-sequencer/skills/vocdoni-sequencer/SKILL.md +169 -0
  42. package/plugins/vocdoni-sequencer/skills/vocdoni-sequencer/references/removed-routes.md +60 -0
  43. package/plugins/davinci-sdk/.claude-plugin/plugin.json +0 -13
  44. package/plugins/davinci-sdk/skills/davinci-sdk/SKILL.md +0 -120
  45. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/bootstrap.ts +0 -61
  46. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/cast-vote.ts +0 -78
  47. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/create-process.ts +0 -102
  48. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/full-election.ts +0 -128
  49. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/read-results.ts +0 -73
  50. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/token-census.ts +0 -111
  51. package/plugins/davinci-sdk/skills/davinci-sdk/references/ballot-modes.md +0 -125
  52. package/plugins/davinci-sdk/skills/davinci-sdk/references/census.md +0 -168
  53. package/plugins/davinci-sdk/skills/davinci-sdk/references/contracts.md +0 -133
  54. package/plugins/davinci-sdk/skills/davinci-sdk/references/errors.md +0 -83
  55. package/plugins/davinci-sdk/skills/davinci-sdk/references/process.md +0 -225
  56. package/plugins/davinci-sdk/skills/davinci-sdk/references/protocol.md +0 -65
  57. package/plugins/davinci-sdk/skills/davinci-sdk/references/sequencer.md +0 -135
  58. package/plugins/davinci-sdk/skills/davinci-sdk/references/setup.md +0 -123
  59. package/plugins/davinci-sdk/skills/davinci-sdk/references/voting.md +0 -128
  60. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/anonymous-vote.ts +0 -108
  61. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/token-census.ts +0 -121
  62. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/anonymous.md +0 -183
  63. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/census3.md +0 -308
@@ -1,133 +0,0 @@
1
- # `references/contracts.md` — The raw contract service (`sdk.processes`)
2
-
3
- Companion to the [[davinci-sdk]] skill. This is an **escape hatch**. The `DavinciSDK` facade (`createProcess`, `endProcess`, `getProcess`, …) wraps the on-chain `ProcessRegistryService` and is what you should use. Drop here only when you need an event subscription, a raw read, or a method the facade doesn't expose.
4
-
5
- > There is **no** `OrganizationRegistryService`, `deployedAddresses`, `getAddresses`, or `AbiRegistry` in this SDK. The process creator is simply the signer's address (`ProcessInfo.creator` / `organizationId`). The `contracts` module exports exactly: `SmartContractService`, `ProcessRegistryService`, the contract types/enums, and the error classes.
6
-
7
- ## Getting the service
8
-
9
- ```ts
10
- const registry = sdk.processes; // ProcessRegistryService, wired to your signer's chain
11
- ```
12
-
13
- `sdk.processes` requires a signer **with a provider** and that the registry address is resolved (it is, after `init()` against a sequencer that knows your chain). Constructing one by hand:
14
-
15
- ```ts
16
- import { ProcessRegistryService } from "@vocdoni/davinci-sdk";
17
- const registry = new ProcessRegistryService(contractAddress, signerOrProvider /* ContractRunner */);
18
- ```
19
-
20
- ## Transactions are async generators of `TxStatusEvent`
21
-
22
- Every write method returns `AsyncGenerator<TxStatusEvent<T>>`, not a receipt. Consume it, or unwrap with the static helper.
23
-
24
- ```ts
25
- enum TxStatus { Pending = "pending", Completed = "completed", Reverted = "reverted", Failed = "failed" }
26
- type TxStatusEvent<T> =
27
- | { status: TxStatus.Pending; hash: string }
28
- | { status: TxStatus.Completed; response: T }
29
- | { status: TxStatus.Reverted; reason?: string }
30
- | { status: TxStatus.Failed; error: Error };
31
- ```
32
-
33
- ```ts
34
- import { SmartContractService } from "@vocdoni/davinci-sdk";
35
- // unwrap a stream to a promise of the final response:
36
- await SmartContractService.executeTx(registry.setProcessStatus(processId, ProcessStatus.ENDED));
37
- ```
38
-
39
- The facade's lifecycle methods are thin wrappers around exactly these streams.
40
-
41
- ## `ProcessRegistryService` — methods
42
-
43
- ### Writes (all → `AsyncGenerator<TxStatusEvent<{ success: true }>>`)
44
-
45
- ```ts
46
- registry.newProcess(
47
- status: ProcessStatus, startTime: number, duration: number, maxVoters: number,
48
- ballotMode: BallotMode, census: CensusData, metadata: string, encryptionKey: EncryptionKey
49
- )
50
- registry.setProcessStatus(processID: string, newStatus: ProcessStatus)
51
- registry.setProcessCensus(processID: string, census: CensusData)
52
- registry.setProcessDuration(processID: string, duration: number)
53
- registry.setProcessMaxVoters(processID: string, maxVoters: number)
54
- // sequencer-only in practice (your app never calls these):
55
- registry.submitStateTransition(processID: string, proof: string, input: string)
56
- registry.setProcessResults(processID: string, proof: string, input: string)
57
- ```
58
-
59
- > `newProcess` here takes **positional args** and the contract-shaped structs below. This is *not* the friendly `ProcessConfig` — use `sdk.createProcess` for that. The facade computes `startTime`/`duration`, fetches the `encryptionKey` from the sequencer, builds `CensusData`, uploads metadata, and calls this for you.
60
-
61
- ### Reads
62
-
63
- ```ts
64
- registry.getProcess(processID: string) // raw contract struct
65
- registry.getProcessCount(): Promise<number>
66
- registry.getChainID(): Promise<string>
67
- registry.getNextProcessId(organizationId: string): Promise<string> // precompute the id
68
- registry.getProcessEndTime(processID: string): Promise<bigint>
69
- registry.getProcessNonce(address: string): Promise<bigint>
70
- registry.getRVerifier(): Promise<string> // + getSTVerifier, *VKeyHash, getMaxCensusOrigin, getMaxStatus
71
- ```
72
-
73
- ### Events (the main reason to come here)
74
-
75
- ```ts
76
- registry.onProcessCreated((processID, creator) => …)
77
- registry.onProcessStatusChanged((processID, oldStatus, newStatus) => …) // bigints
78
- registry.onCensusUpdated((processID, root, uri) => …)
79
- registry.onProcessDurationChanged((processID, duration) => …)
80
- registry.onStateTransitioned((processID, sender, oldRoot, newRoot, voters, overwritten) => …)
81
- registry.onProcessResultsSet((processID, sender, result /* bigint[] */) => …) // ← results landed
82
- registry.onProcessMaxVotersChanged((processID, maxVoters) => …)
83
- registry.removeAllListeners()
84
- registry.setEventPollingInterval(ms) // default 5000
85
- ```
86
-
87
- `onProcessResultsSet` is the clean way to know the tally is final (see `recipes/read-results.ts`).
88
-
89
- ## Contract-shaped types
90
-
91
- These differ from the friendly SDK config; the facade converts at the boundary, coercing to `bigint` where the contract needs it.
92
-
93
- ```ts
94
- // core types — what newProcess consumes
95
- interface BallotMode { // SAME field names as ProcessConfig.ballot; bounds are decimal strings
96
- numFields: number; groupSize?: number;
97
- minValue: string; maxValue: string; uniqueValues: boolean;
98
- costExponent: number; minValueSum: string; maxValueSum: string;
99
- }
100
- interface CensusData {
101
- censusOrigin: CensusOrigin; censusRoot: string;
102
- contractAddress?: string; // set for Onchain censuses (else zero address)
103
- censusURI: string; onchainAllowAnyValidRoot?: boolean;
104
- }
105
- interface EncryptionKey { x: string; y: string; } // BabyJubJub pubkey (from sequencer getProcessKeys)
106
- ```
107
-
108
- `ProcessStatus`:
109
-
110
- ```ts
111
- enum ProcessStatus { READY = 0, ENDED = 1, CANCELED = 2, PAUSED = 3, RESULTS = 4 }
112
- ```
113
-
114
- ## `SmartContractService` (base class)
115
-
116
- ```ts
117
- class SmartContractService {
118
- static executeTx<T>(stream: AsyncGenerator<TxStatusEvent<T>>): Promise<T> // unwrap → promise
119
- setEventPollingInterval(ms: number): void
120
- }
121
- ```
122
-
123
- `ProcessRegistryService` extends it; the streaming + event plumbing lives here.
124
-
125
- ## Errors
126
-
127
- All contract-layer errors extend `ContractServiceError` (`.operation` field), e.g. `ProcessCreateError`, `ProcessStatusError`, `ProcessCensusError`, `CensusNotUpdatable`, `ProcessDurationError`, `ProcessStateTransitionError`, `ProcessResultError`. No numeric codes here (those are the sequencer's — see `references/sequencer.md`).
128
-
129
- ## Cross-references
130
-
131
- - `references/process.md` — the facade methods you should normally use instead.
132
- - `references/sequencer.md` — the off-chain side and where `encryptionKey` comes from.
133
- - `references/errors.md` — `TxStatus.Reverted`/`Failed` handling and revert reasons.
@@ -1,83 +0,0 @@
1
- # `references/errors.md` — Errors, reverts, and gotchas
2
-
3
- Companion to the [[davinci-sdk]] skill. Failure modes grouped by where they come from.
4
-
5
- ## The two status enums — don't confuse them
6
-
7
- | Enum | Where | Values |
8
- | ------------ | --------------------------------------- | ------------------------------------------------------------- |
9
- | `TxStatus` | on-chain txs (create/end/pause/…) | `pending` · `completed` · `reverted` · `failed` |
10
- | `VoteStatus` | a vote's processing journey | `pending` · `verified` · `aggregated` · `processed` · `settled` · `error` |
11
-
12
- A `TxStatus.Reverted` is the contract rejecting a transaction; a `VoteStatus.Error` is the sequencer rejecting a ballot. They are unrelated code paths.
13
-
14
- ## Setup / wiring
15
-
16
- | Symptom | Cause / fix |
17
- | ------- | ----------- |
18
- | *"SDK must be initialized… Call sdk.init() first."* | You called a method before `await sdk.init()`. |
19
- | *"Provider required for blockchain operations…"* | An on-chain method (`createProcess`, `getProcess`, lifecycle) ran on a signer with **no provider**. Use `new Wallet(pk, provider)`. Voting doesn't need one. |
20
- | *"Census URL is required for voting."* | Voting on a Merkle census without `censusUrl` and without a custom `censusProviders`. Add `censusUrl` to the config. |
21
- | *"Census API URL is required to publish Merkle censuses…"* | `createProcess` tried to auto-publish an `OffchainCensus` but the SDK has no `censusUrl`. Add it, or pass a pre-published / on-chain / CSP census. |
22
- | *"Failed to fetch contract addresses from sequencer…"* | `init()` couldn't resolve the registry for your chain. The RPC chain isn't supported by this sequencer, or `sequencerUrl` is wrong. Check `getInfo().networks` vs `provider.getNetwork()`, or pass `addresses.processRegistry`. |
23
- | *"Signer chainId N is not supported by sequencer."* | RPC points at a chain the sequencer doesn't serve. Point RPC at the sequencer's chain. |
24
-
25
- ## Process creation
26
-
27
- | Symptom | Cause / fix |
28
- | ------- | ----------- |
29
- | *"maxVoters is required…"* | Census type needs an explicit `maxVoters` (Onchain/CSP/Published/manual, or an unpublished census). Only published `OffchainCensus`/`OffchainDynamicCensus` auto-derive it. See `references/census.md`. |
30
- | *"Cannot specify both 'duration' and 'endDate'."* | Pick one in `timing`. |
31
- | *"Must specify either 'duration' … or 'endDate'."* | `timing` had neither. |
32
- | *"Start date cannot be in the past."* | `startDate` is >30s before now. Default is now+60s; leave it unset for "start soon". |
33
- | `TxStatus.Reverted` from `createProcessStream` | On-chain rejection — wrong chain, insufficient gas, malformed struct, or not the organizer. Inspect `event.reason`. |
34
- | `TxStatus.Failed` | The tx couldn't be sent/mined (`event.error`) — usually RPC/gas/nonce. |
35
-
36
- ## Sequencer (numeric error codes)
37
-
38
- REST errors throw with a numeric `.code`:
39
-
40
- | Code | Meaning | Typical handling |
41
- | ---- | ------- | ---------------- |
42
- | `40007` | Process not found / not yet indexed | Right after `createProcess` the sequencer hasn't indexed it. Poll `getProcess` with backoff until it appears and `isAcceptingVotes`. |
43
- | `40001` | Address not in census | Surface a clean "not eligible" message; pre-check with `isAddressAbleToVote`. |
44
-
45
- ```ts
46
- try { const p = await sdk.api.sequencer.getProcess(id); }
47
- catch (e: any) {
48
- if (e.code === 40007) { /* wait & retry */ }
49
- else throw e;
50
- }
51
- ```
52
-
53
- ## Voting
54
-
55
- | Symptom | Cause / fix |
56
- | ------- | ----------- |
57
- | *"Process is not currently accepting votes"* | Process isn't `READY`/started yet, is paused/ended, or not indexed. Poll `sdk.api.sequencer.getProcess(id).isAcceptingVotes` first. |
58
- | *"Choice X is out of range [min, max]"* | A `choices` entry violates `ballot.minValue`/`maxValue`. Also ensure `choices.length === ballot.numFields`. |
59
- | *"CSP voting requires a CSP census proof provider."* | Voting on a `CspCensus` without `censusProviders.csp`. Supply one (see `references/census.md`). |
60
- | *"Hash verification failed for circuit.wasm/…"* | A downloaded circuit artifact didn't match the sequencer's published hash (`verifyCircuitFiles`). Don't disable the check — investigate the sequencer/CDN. |
61
- | *"Generated proof is invalid"* | `verifyProof` caught a bad proof before submit — usually mismatched circuit artifacts or inputs. Confirm the SDK and sequencer agree on the chain/process. |
62
- | *"Vote did not reach status … within …ms"* | `waitForVoteStatus` timed out. Settlement can take minutes under load; raise the timeout (the SDK demo uses ~800_000ms). |
63
- | `VoteStatus.Error` | The sequencer rejected the ballot (bad proof/signature/eligibility). Re-check census membership and that the process is live. |
64
-
65
- ## Reading results
66
-
67
- - `getProcess(...).result` is only meaningful once the process is `ENDED`/`RESULTS` **and** votes have settled and results are set on-chain. Before that it may be empty/zeros. Wait for `votersCount` to match expectations, `endProcess`, then await `sdk.processes.onProcessResultsSet` (see `recipes/read-results.ts`).
68
- - `result` is `bigint[]` per **ballot field**, not per question — map by index to your one-hot options.
69
-
70
- ## Quick reference: handling a TxStatus stream safely
71
-
72
- ```ts
73
- for await (const e of sdk.createProcessStream(cfg)) {
74
- if (e.status === TxStatus.Completed) return e.response.processId;
75
- if (e.status === TxStatus.Failed) throw e.error;
76
- if (e.status === TxStatus.Reverted) throw new Error(`reverted: ${e.reason ?? "unknown"}`);
77
- }
78
- ```
79
-
80
- ## Cross-references
81
-
82
- - `references/setup.md` — the signer/provider rule behind half of these.
83
- - `references/voting.md`, `references/process.md`, `references/sequencer.md`.
@@ -1,225 +0,0 @@
1
- # `references/process.md` — Creating & managing a process, reading results
2
-
3
- Companion to the [[davinci-sdk]] skill. A **process** is one election. This file covers `createProcess`, its config shape, the lifecycle methods, and `getProcess` / result reading — all on the `DavinciSDK` facade. All of these require a **signer with a provider** (see `references/setup.md`).
4
-
5
- ## Create a process
6
-
7
- ```ts
8
- const result = await sdk.createProcess(config); // Promise<ProcessCreationResult>
9
- // result = { processId: string, transactionHash: string }
10
- ```
11
-
12
- The facade does everything: validates timing, computes the next `processId`, auto-publishes the census if needed, uploads metadata, fetches the per-process encryption key from the sequencer, and sends the on-chain create transaction.
13
-
14
- ### `ProcessConfig`
15
-
16
- ```ts
17
- interface ProcessConfig {
18
- // Census: a Census object (recommended) OR manual { type, root, size, uri }.
19
- census: Census | { type: CensusOrigin; root: string; size: number; uri: string };
20
-
21
- ballot: BallotMode; // the voting rules — see references/ballot-modes.md
22
-
23
- timing: {
24
- startDate?: Date | string | number; // default: now + 60s
25
- duration?: number; // seconds — use this OR endDate, not both
26
- endDate?: Date | string | number; // alternative to duration
27
- };
28
-
29
- maxVoters?: number; // see "the maxVoters rule" below
30
-
31
- // EITHER inline metadata (uploaded for you) …
32
- title?: string;
33
- description?: string;
34
- questions?: [ProcessQuestion, ...ProcessQuestion[]]; // ≥1 required in this form
35
- // … OR a pre-uploaded metadata URI:
36
- metadataUri?: string;
37
- }
38
-
39
- type ProcessQuestion = {
40
- title: string;
41
- description?: string;
42
- choices: Array<{ title: string; value: number }>;
43
- };
44
- ```
45
-
46
- `ProcessConfig` is a union: provide **either** `title`+`questions` (the SDK builds & uploads `ElectionMetadata` for you) **or** a `metadataUri` you uploaded yourself. You cannot mix `duration` and `endDate`.
47
-
48
- ### `BallotMode` (the `ballot` field)
49
-
50
- ```ts
51
- interface BallotMode {
52
- numFields: number; // number of ballot fields; choices.length must equal this
53
- groupSize?: number; // optional grouping (advanced)
54
- minValue: string; // min value per field (decimal STRING)
55
- maxValue: string; // max value per field (decimal STRING)
56
- uniqueValues: boolean; // all field values must differ (ranking)
57
- costExponent: number; // exponent in the cost sum (2 = quadratic)
58
- minValueSum: string; // floor on Σ value^costExponent (decimal STRING)
59
- maxValueSum: string; // ceiling on Σ value^costExponent (decimal STRING)
60
- }
61
- ```
62
-
63
- > Bounds are **decimal strings**, not numbers — bigint-safe JSON. `numFields`/`costExponent` are plain `number`. How to set these for approval/ranked/quadratic/budget/single/multiple choice is in `references/ballot-modes.md`.
64
-
65
- ### The `maxVoters` rule
66
-
67
- `maxVoters` caps how many voters the process accepts. When you can omit it vs must supply it:
68
-
69
- | Census you pass | `maxVoters` |
70
- | -------------------------------------------- | ----------- |
71
- | Published `OffchainCensus`/`OffchainDynamicCensus` (Merkle) | **Optional** — defaults to the participant count |
72
- | `OnchainCensus` (token / on-chain) | **Required** |
73
- | `CspCensus` | **Required** |
74
- | `PublishedCensus` | **Required** |
75
- | Manual `{ type, root, size, uri }` | **Required** |
76
-
77
- Omitting it when required throws: *"maxVoters is required…"*. See `references/census.md`.
78
-
79
- ### Timing notes
80
-
81
- - `startDate` defaults to **now + 60 seconds**; a start date more than 30s in the past throws.
82
- - Accepts `Date`, ISO string, or Unix timestamp (seconds; values > 1e10 are treated as ms and divided).
83
- - Give `duration` (seconds) **or** `endDate`, never both. `endDate` must be after `startDate`.
84
-
85
- ### Minimal example
86
-
87
- ```ts
88
- import { OffchainCensus } from "@vocdoni/davinci-sdk";
89
-
90
- const census = new OffchainCensus();
91
- census.add(["0xAaa…", "0xBbb…", "0xCcc…"]);
92
-
93
- const { processId, transactionHash } = await sdk.createProcess({
94
- title: "Community Decision",
95
- description: "What should we build next?",
96
- census, // auto-published; maxVoters auto
97
- ballot: {
98
- numFields: 3, minValue: "0", maxValue: "1",
99
- uniqueValues: false, costExponent: 1, minValueSum: "0", maxValueSum: "1",
100
- },
101
- timing: { startDate: new Date(Date.now() + 60_000), duration: 3600 * 24 },
102
- questions: [{
103
- title: "Which initiative?",
104
- choices: [
105
- { title: "Garden", value: 0 },
106
- { title: "Workshop", value: 1 },
107
- { title: "Gallery", value: 2 },
108
- ],
109
- }],
110
- });
111
- ```
112
-
113
- ## Real-time creation: `createProcessStream`
114
-
115
- For UIs that show transaction progress, use the streaming variant. It yields `TxStatusEvent`s:
116
-
117
- ```ts
118
- import { TxStatus } from "@vocdoni/davinci-sdk";
119
-
120
- let processId = "";
121
- for await (const event of sdk.createProcessStream(config)) {
122
- switch (event.status) {
123
- case TxStatus.Pending: console.log("submitted:", event.hash); break;
124
- case TxStatus.Completed: processId = event.response.processId; // + event.response.transactionHash
125
- break;
126
- case TxStatus.Failed: throw event.error;
127
- case TxStatus.Reverted: throw new Error(`reverted: ${event.reason}`);
128
- }
129
- }
130
- ```
131
-
132
- `createProcess(config)` is exactly this loop consumed for you, returning `{ processId, transactionHash }`. Use the plain method for scripts; the stream for progress UX.
133
-
134
- ## Lifecycle
135
-
136
- Every lifecycle method has a plain (`Promise<void>`) form and a `…Stream` form yielding `TxStatusEvent`s. All require a signer with a provider, and revert if you're not the process organizer or the transition is invalid.
137
-
138
- ```ts
139
- await sdk.endProcess(processId); // → status ENDED (stops accepting votes; triggers tally)
140
- await sdk.pauseProcess(processId); // → status PAUSED
141
- await sdk.resumeProcess(processId); // PAUSED → READY (resume a paused process)
142
- await sdk.cancelProcess(processId); // → status CANCELED (abandon; no results)
143
- await sdk.setProcessMaxVoters(processId, 750); // change the voter cap
144
-
145
- // streaming equivalents: endProcessStream, pauseProcessStream, resumeProcessStream,
146
- // cancelProcessStream, setProcessMaxVotersStream — same TxStatusEvent shape as above.
147
- ```
148
-
149
- `ProcessStatus` (contract enum — note the values):
150
-
151
- ```ts
152
- enum ProcessStatus { READY = 0, ENDED = 1, CANCELED = 2, PAUSED = 3, RESULTS = 4 }
153
- ```
154
-
155
- A process becomes accepting-votes once it is `READY` **and** its `startDate` has passed; check `sdk.api.sequencer.getProcess(id).isAcceptingVotes` (see `references/sequencer.md`). After `endProcess`, the sequencer computes the final tally and the contract moves to `RESULTS`.
156
-
157
- ## Read a process & results: `getProcess`
158
-
159
- ```ts
160
- const info = await sdk.getProcess(processId); // Promise<ProcessInfo>
161
- ```
162
-
163
- ```ts
164
- interface ProcessInfo {
165
- processId: string;
166
- title: string;
167
- description?: string;
168
- census: { type: CensusOrigin; root: string; uri: string };
169
- ballot: BallotMode;
170
- questions: ProcessQuestion[];
171
-
172
- status: ProcessStatus; // READY/ENDED/CANCELED/PAUSED/RESULTS
173
- creator: string; // the organizer's address
174
- startDate: Date;
175
- endDate: Date;
176
- duration: number; // seconds
177
- timeRemaining: number; // seconds (0 if ended, negative if not started)
178
- maxVoters: number;
179
-
180
- result: bigint[]; // tally — one entry per ballot field
181
- votersCount: number; // votes cast
182
- overwrittenVotesCount: number; // overwrites (last-vote-wins)
183
- metadataURI: string;
184
- raw?: any; // raw contract struct, for advanced use
185
- }
186
- ```
187
-
188
- `getProcess` reads the contract and fetches metadata, so it needs a provider. For a lightweight, provider-free read (status, `isAcceptingVotes`, `votersCount`, encryption key), use `sdk.api.sequencer.getProcess(processId)` — see `references/sequencer.md`.
189
-
190
- ### Reading the tally
191
-
192
- `result` is a `bigint[]`, **one entry per ballot field** (not per question, not per choice — though for one-hot single-choice questions each field *is* a choice). Each entry is the weighted sum of that field's values across all voters.
193
-
194
- ```ts
195
- const info = await sdk.getProcess(processId);
196
- // e.g. one question "favourite colour" encoded as 4 one-hot fields:
197
- info.questions[0].choices.forEach((c, i) => {
198
- console.log(`${c.title}: ${info.result[i].toString()}`);
199
- });
200
- ```
201
-
202
- Results are meaningful only once the process is `ENDED`/`RESULTS` and the sequencer has settled all votes and set results on-chain. To be notified the instant results land, subscribe to the contract event (escape hatch, needs `sdk.processes`):
203
-
204
- ```ts
205
- sdk.processes.onProcessResultsSet((id, sender, result /* bigint[] */) => {
206
- if (id.toLowerCase() === processId.toLowerCase()) console.log("results:", result);
207
- });
208
- ```
209
-
210
- See `recipes/read-results.ts` for the full "wait for all votes counted → end → await results" pattern.
211
-
212
- ## Listing processes
213
-
214
- ```ts
215
- const ids: string[] = await sdk.listProcesses(); // uses signer's chain
216
- const ids2 = await sdk.listProcesses(chainId /* number */); // explicit chain
217
- ```
218
-
219
- ## Cross-references
220
-
221
- - `references/census.md` — building the `census` you pass in.
222
- - `references/ballot-modes.md` — configuring `ballot` for a voting system.
223
- - `references/voting.md` — casting votes once the process is live.
224
- - `references/contracts.md` — the raw `ProcessRegistryService` behind these methods.
225
- - `recipes/create-process.ts`, `recipes/read-results.ts`, `recipes/full-election.ts`.
@@ -1,65 +0,0 @@
1
- # `references/protocol.md` — How Davinci works (the *why* under the SDK)
2
-
3
- Companion to the [[davinci-sdk]] skill. This file explains the protocol the SDK calls into: the actors, the five phases, the cryptography, the census models, and the state tree. Read it when the question is conceptual ("why ElGamal", "what's a vote id", "how is the tally kept secret until the end", "what does a sequencer actually do") rather than "how do I call X". It is distilled from the Davinci whitepaper/spec.
4
-
5
- ## One-paragraph intuition
6
-
7
- An election is governed by **Ethereum smart contracts** (the source of truth). Voters never put votes on-chain directly: they **encrypt** their ballot and send it, with **zero-knowledge proofs** of validity and eligibility, to a **sequencer**. Sequencers verify many ballots, **aggregate** them into a single proof, **re-encrypt** them (so voters can't later prove how they voted), and submit a **state-transition proof** on-chain. Individual votes stay encrypted the whole time; only the **final aggregated tally** is decrypted at the end by a threshold of **key wardens**. A results proof anchors the tally to the final state on-chain, where anyone can audit it.
8
-
9
- ## Actors
10
-
11
- - **Organizer** — defines the election (ballot mode + census) and submits the create transaction. In the SDK this is just your `signer`; there is no separate "organization" object.
12
- - **Key wardens** — a decentralized group that runs a DKG to produce the **encryption public key** voters use, and later cooperate (threshold) to decrypt only the final tally. The SDK fetches the per-process encryption key from the sequencer (`getProcessKeys`); you don't manage wardens.
13
- - **Voters** — census members; they encrypt and submit ballots off-chain to a sequencer.
14
- - **Sequencers** — collect, verify, aggregate, re-encrypt, and commit votes to the shared state. You *talk to* a sequencer over REST; you don't run one.
15
-
16
- ## The five phases (and where the SDK sits)
17
-
18
- 1. **Election setup** — organizer commits ballot mode + census commitment on-chain. → `sdk.createProcess`.
19
- 2. **Encryption-key generation** — wardens publish the process encryption key (DKG). → fetched for you during `createProcess`.
20
- 3. **Voting period** — voters cast encrypted ballots; sequencers batch and commit them. Runs continuously until the deadline; voters may **overwrite** their vote (coercion resistance, last-vote-wins). → `sdk.submitVote` + `waitForVoteStatus`.
21
- 4. **Tally decryption** — after the deadline, a threshold of wardens publish partial decryptions of the aggregated result (never the individual votes). → triggered by `sdk.endProcess`.
22
- 5. **Finalization** — results + correctness proof are verified on-chain and recorded immutably. → readable via `sdk.getProcess(...).result` / the `onProcessResultsSet` event.
23
-
24
- This maps directly onto the SDK's two status enums: on-chain steps surface as `TxStatus`; a single vote's journey through the sequencer surfaces as `VoteStatus` (`pending → verified → aggregated → processed → settled`).
25
-
26
- ## Cryptography in one screen
27
-
28
- - **Homomorphic encryption (ElGamal on BabyJubJub).** Ballots are encrypted to the process public key. Ciphertexts add up, so sequencers can accumulate the encrypted tally without decrypting anything. A ciphertext is a pair of curve points `{ c1, c2 }`, serialized as decimal `[string, string]` coordinate pairs.
29
- - **zk-SNARKs (Groth16, BN254 for the ballot circuit).** The voter's **ballot circuit** proves the encrypted ballot satisfies the ballot mode *and* that the vote id was derived correctly — without revealing the vote. The SDK runs this locally with `snarkjs`, using circuit artifacts downloaded from the sequencer's `/info`. Sequencers then run **verifier**, **aggregation**, **state-transition**, and **results** circuits.
30
- - **Re-encryption.** Sequencers re-randomize ciphertexts so a voter can no longer prove their original plaintext — mitigating vote-buying/coercion — without changing the tally.
31
- - **Signatures (EdDSA).** The voter signs the vote id to prove identity ownership. The SDK signs the 32-byte big-endian vote id for you.
32
-
33
- ## Vote identifiers (not classic nullifiers)
34
-
35
- A **vote id** is `voteID = N + Hash(processID, address, k) mod N` (with `N = 2^63`), where `k` is fresh randomness. It lets a voter confirm their vote was included **without linking to the encrypted ballot**. Uniqueness isn't enforced by a nullifier set; instead the state-transition circuit only inserts a vote id into an *empty* leaf — on the rare collision the voter just resamples `k`. This is why `submitVote` accepts an optional `randomness` (the `k`) and why overwriting is natural: a re-vote writes the voter's reserved ballot slot again (last-vote-wins), updating the tally by subtracting the old contribution and adding the new.
36
-
37
- ## Census models (the four `CensusOrigin`s)
38
-
39
- The contract stores three census parameters — `censusOrigin`, `censusURI`, `censusRoot` — interpreted per model:
40
-
41
- | `CensusOrigin` | `censusRoot` means… | Membership proof | Updates during voting |
42
- | ------------------- | ----------------------------- | ------------------------- | --------------------- |
43
- | `OffchainStatic` (1)| Merkle root | Merkle path | no |
44
- | `OffchainDynamic`(2)| latest Merkle root | Merkle path | append-only |
45
- | `Onchain` (3) | census contract address | Merkle path vs on-chain roots | append-only |
46
- | `CSP` (4) | hash of the CSP public key | CSP signature over `(processID, idx, address, weight)` | external |
47
-
48
- Each voter has an index `idx`, an `address`, and a `weight`. Weights enable weighted voting; by default everyone is weight 1. The SDK's census classes (`OffchainCensus`, …) are thin builders over this — see `references/census.md`.
49
-
50
- ## State tree (why results appear when they do)
51
-
52
- Election state is one fixed-depth (D=64) sparse Merkle tree committed on-chain as `stateRoot`. Low indices hold config (process id, ballot mode, encryption key, the encrypted `resultsAdd`/`resultsSub` accumulators, census origin); a middle region holds each voter's reserved encrypted-ballot slot (derived from `idx`); the upper half holds vote ids. Each sequencer batch produces a new `stateRoot` proven by the state-transition circuit and verified on-chain. The tally stays encrypted in the accumulators until the process ends and wardens decrypt it — which is exactly why `getProcess(...).result` is only meaningful after `endProcess` and settlement.
53
-
54
- ## What this means for SDK users
55
-
56
- - You can't read individual votes — by design. You read aggregate `result` after the election ends.
57
- - "It takes minutes to settle" is the batching + on-chain state transition, not a bug. Size your `waitForVoteStatus` timeouts accordingly.
58
- - Overwriting is supported and expected; don't treat `hasAddressVoted === true` as final.
59
- - The encryption key, circuits, and contract addresses all come from the sequencer's `/info` — keep the SDK pointed at a sequencer that matches your chain.
60
-
61
- ## Cross-references
62
-
63
- - `references/ballot-modes.md` — the parametric ballot protocol in practice.
64
- - `references/voting.md` — the `VoteStatus` lifecycle that mirrors phases 3–5.
65
- - `references/sequencer.md` — `getInfo`, circuits, the encryption key.
@@ -1,135 +0,0 @@
1
- # `references/sequencer.md` — The sequencer REST client (`sdk.api.sequencer`)
2
-
3
- Companion to the [[davinci-sdk]] skill. The sequencer is the off-chain service that collects encrypted ballots, verifies their zk proofs, aggregates them, and drives the on-chain state. Its REST client is `VocdoniSequencerService`, reachable as **`sdk.api.sequencer`** (and `sdk.api.census` for the census service — see `references/census.md`). The `DavinciSDK` facade calls these for you; reach here when you need a lightweight, provider-free read or a call the facade doesn't wrap.
4
-
5
- ```ts
6
- const seq = sdk.api.sequencer; // VocdoniSequencerService, base URL = config.sequencerUrl
7
- ```
8
-
9
- ## Methods (exact signatures)
10
-
11
- ```ts
12
- // Health / discovery
13
- seq.ping(): Promise<void>
14
- seq.getInfo(): Promise<InfoResponse> // circuit URLs+hashes, networks, sequencer addr
15
-
16
- // Processes (lightweight, no provider needed)
17
- seq.getProcess(processId: string): Promise<GetProcessResponse>
18
- seq.getProcessKeys(processId: string): Promise<{ encryptionPubKey: [string, string] }>
19
- seq.listProcesses(chainId?: number): Promise<string[]>
20
-
21
- // Votes
22
- seq.submitVote(vote: VoteRequest): Promise<void> // facade builds the VoteRequest
23
- seq.getVoteStatus(processId, voteId): Promise<{ status: VoteStatus }>
24
- seq.hasAddressVoted(processId, address): Promise<boolean>
25
- seq.isAddressAbleToVote(processId, address): Promise<boolean>
26
- seq.getAddressWeight(processId, address): Promise<string> // "0" if not in census
27
-
28
- // Metadata (used by createProcess)
29
- seq.pushMetadata(metadata: ElectionMetadata): Promise<string> // → content hash
30
- seq.getMetadata(hashOrUrl: string): Promise<ElectionMetadata>
31
- seq.getMetadataUrl(hash: string): string
32
-
33
- // Stats
34
- seq.getStats(): Promise<SequencerStats>
35
- seq.getWorkers(): Promise<WorkersResponse>
36
- ```
37
-
38
- No network call on construction. The base URL comes from the SDK config.
39
-
40
- ## `getInfo` — the source of circuit artifacts & chains
41
-
42
- ```ts
43
- interface InfoResponse {
44
- circuitUrl: string; circuitHash: string; // ballot-proof WASM
45
- provingKeyUrl: string; provingKeyHash: string; // zkey
46
- verificationKeyUrl: string; verificationKeyHash: string; // vkey (JSON)
47
- networks: Record<string /* chainId */, {
48
- chainID: number;
49
- shortName: string;
50
- processRegistryContract: string; // contract address per chain
51
- processIDVersion: string; // 4-byte version embedded in process IDs
52
- }>;
53
- sequencerAddress: string;
54
- }
55
- ```
56
-
57
- `init()` uses `networks[chainId].processRegistryContract` to wire the contract service. The vote flow downloads `circuitUrl`/`provingKeyUrl`/`verificationKeyUrl` (multi-MB; the SDK caches them in memory) and verifies their SHA-256 against the `*Hash` fields when `verifyCircuitFiles` is on.
58
-
59
- ## `getProcess` (REST) vs `sdk.getProcess` (contract)
60
-
61
- `seq.getProcess` is the **lightweight, provider-free** view straight from the sequencer; `sdk.getProcess` reads the contract + metadata and returns the richer `ProcessInfo` (and needs a provider). Use the REST one for status/readiness polling.
62
-
63
- ```ts
64
- interface GetProcessResponse {
65
- id: string;
66
- status: number; // ProcessStatus as a number
67
- organizationId: string; // creator address
68
- encryptionKey: { x: string; y: string };
69
- stateRoot: string;
70
- result: string[] | null; // decimal strings once tallied
71
- startTime: string;
72
- duration: number;
73
- metadataURI: string;
74
- ballotMode: BallotMode; // string-bounded shape
75
- census: { censusOrigin: number; censusRoot: string; censusURI: string; /* … */ };
76
- votersCount: string;
77
- maxVoters: string;
78
- overwrittenVotesCount: string;
79
- isAcceptingVotes: boolean; // ← poll this for readiness
80
- sequencerStats: { /* per-process processing counters */ };
81
- }
82
- ```
83
-
84
- The canonical readiness check before voting:
85
-
86
- ```ts
87
- const p = await sdk.api.sequencer.getProcess(processId);
88
- if (p.isAcceptingVotes) { /* safe to submitVote */ }
89
- ```
90
-
91
- ## `VoteRequest` (the wire payload — the facade builds it)
92
-
93
- You normally never construct this; `sdk.submitVote` does. Shown for debugging:
94
-
95
- ```ts
96
- interface VoteRequest {
97
- processId: string;
98
- censusProof?: CensusProof; // only for CSP; omitted for Merkle
99
- ballot: { curveType: string; ciphertexts: { c1: [string,string]; c2: [string,string] }[] };
100
- ballotProof: { pi_a; pi_b; pi_c; protocol }; // groth16
101
- ballotInputsHash: string;
102
- address: string;
103
- signature: string; // EdDSA over the 32-byte voteId
104
- voteId: string;
105
- }
106
- ```
107
-
108
- `submitVote` returns `void`; the sequencer assigns/echoes the `voteId` you computed. Track the `voteId` from `sdk.submitVote`'s `VoteResult` and poll `getVoteStatus`.
109
-
110
- ## Errors
111
-
112
- REST errors throw with a numeric `code` you can switch on. Common ones:
113
-
114
- - **`40007`** — process not found / not yet indexed (right after `createProcess`; retry with backoff).
115
- - **`40001`** — address not in census (surfaces from `hasAddressVoted`/`isAddressAbleToVote`).
116
-
117
- ```ts
118
- try { await sdk.api.sequencer.getProcess(id); }
119
- catch (e: any) { if (e.code === 40007) { /* not indexed yet, wait & retry */ } else throw e; }
120
- ```
121
-
122
- See `references/errors.md` for the full catalogue.
123
-
124
- ## Gotchas
125
-
126
- - **Decimal strings, not numbers.** `votersCount`, `maxValue`, weights, results are strings over the wire — `BigInt(...)` / `Number(...)` before arithmetic.
127
- - **Encryption-key points are `[string,string]` / `{x,y}` decimal coordinate pairs** (BabyJubJub), not hex.
128
- - **The sequencer doesn't bundle circuits** — `getInfo()` gives URLs you download at proof time.
129
- - **`isAcceptingVotes` can be false right after creation** until the start time passes and the sequencer indexes the process.
130
-
131
- ## Cross-references
132
-
133
- - `references/voting.md` — how these calls compose into the vote flow.
134
- - `references/census.md` — `sdk.api.census` (the other REST service).
135
- - `references/contracts.md` — the on-chain side (`sdk.processes`).