@vocdoni/skills 0.5.3 → 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 (77) hide show
  1. package/.claude-plugin/marketplace.json +29 -27
  2. package/CHANGELOG.md +38 -0
  3. package/README.md +66 -41
  4. package/bin/install.js +13 -2
  5. package/package.json +1 -1
  6. package/plugins/agentic-dev/.claude-plugin/plugin.json +2 -2
  7. package/plugins/agentic-dev/agents/model-router.md +105 -0
  8. package/plugins/agentic-dev/skills/subagent-driven-development/SKILL.md +25 -13
  9. package/plugins/agentic-dev/skills/subagent-driven-development/references/audits.md +20 -13
  10. package/plugins/agentic-dev/skills/subagent-driven-development/references/dispatch.md +42 -1
  11. package/plugins/agentic-dev/skills/subagent-driven-development/references/ledger.md +11 -6
  12. package/plugins/agentic-dev/skills/subagent-driven-development/references/model-catalog.md +118 -0
  13. package/plugins/agentic-dev/skills/subagent-driven-development/references/models.md +126 -71
  14. package/plugins/agentic-dev/skills/subagent-driven-development/scripts/init-workspace.sh +2 -1
  15. package/plugins/agentic-dev/skills/subagent-driven-development/scripts/model-inventory.sh +142 -0
  16. package/plugins/claude-pi-subagent/plugins/pi-subagent/package-lock.json +4 -3
  17. package/plugins/vocdoni-comments/.claude-plugin/plugin.json +2 -2
  18. package/plugins/vocdoni-comments/hooks/hooks.json +28 -0
  19. package/plugins/vocdoni-comments/hooks/session-start.sh +45 -0
  20. package/plugins/vocdoni-contributing/.claude-plugin/plugin.json +3 -2
  21. package/plugins/vocdoni-contributing/hooks/hooks.json +14 -2
  22. package/plugins/vocdoni-contributing/hooks/session-start.sh +18 -6
  23. package/plugins/vocdoni-contributing/skills/contributing/SKILL.md +41 -7
  24. package/plugins/vocdoni-go/.claude-plugin/plugin.json +2 -2
  25. package/plugins/vocdoni-go/skills/vocdoni-backend-review/SKILL.md +522 -0
  26. package/plugins/vocdoni-go/skills/vocdoni-backend-review/references/prompts.md +260 -0
  27. package/plugins/vocdoni-go/skills/vocdoni-backend-review/scripts/untracked-list.sh +35 -0
  28. package/plugins/vocdoni-sdk/.claude-plugin/plugin.json +4 -5
  29. package/plugins/vocdoni-sdk/skills/vocdoni-ballot-protocol/SKILL.md +61 -38
  30. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/SKILL.md +35 -21
  31. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/approval-vote.ts +3 -3
  32. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/basic-poll.ts +6 -6
  33. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/csp-vote.ts +12 -7
  34. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/multichoice-vote.ts +3 -3
  35. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/quadratic-vote.ts +3 -3
  36. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/ranked-vote.ts +3 -3
  37. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/weighted-census.ts +3 -3
  38. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/accounts.md +26 -15
  39. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/census.md +9 -10
  40. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/client.md +15 -13
  41. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/csp.md +43 -18
  42. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/elections.md +4 -4
  43. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/errors.md +24 -21
  44. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/removed-features.md +98 -0
  45. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/results.md +0 -1
  46. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/voting.md +30 -34
  47. package/plugins/vocdoni-sequencer/.claude-plugin/plugin.json +21 -0
  48. package/plugins/vocdoni-sequencer/skills/vocdoni-sequencer/SKILL.md +169 -0
  49. package/plugins/vocdoni-sequencer/skills/vocdoni-sequencer/references/removed-routes.md +60 -0
  50. package/plugins/davinci-sdk/.claude-plugin/plugin.json +0 -13
  51. package/plugins/davinci-sdk/skills/davinci-sdk/SKILL.md +0 -120
  52. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/bootstrap.ts +0 -61
  53. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/cast-vote.ts +0 -78
  54. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/create-process.ts +0 -102
  55. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/full-election.ts +0 -128
  56. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/read-results.ts +0 -73
  57. package/plugins/davinci-sdk/skills/davinci-sdk/recipes/token-census.ts +0 -111
  58. package/plugins/davinci-sdk/skills/davinci-sdk/references/ballot-modes.md +0 -125
  59. package/plugins/davinci-sdk/skills/davinci-sdk/references/census.md +0 -168
  60. package/plugins/davinci-sdk/skills/davinci-sdk/references/contracts.md +0 -133
  61. package/plugins/davinci-sdk/skills/davinci-sdk/references/errors.md +0 -83
  62. package/plugins/davinci-sdk/skills/davinci-sdk/references/process.md +0 -225
  63. package/plugins/davinci-sdk/skills/davinci-sdk/references/protocol.md +0 -65
  64. package/plugins/davinci-sdk/skills/davinci-sdk/references/sequencer.md +0 -135
  65. package/plugins/davinci-sdk/skills/davinci-sdk/references/setup.md +0 -123
  66. package/plugins/davinci-sdk/skills/davinci-sdk/references/voting.md +0 -128
  67. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/anonymous-vote.ts +0 -108
  68. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/recipes/token-census.ts +0 -121
  69. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/anonymous.md +0 -183
  70. package/plugins/vocdoni-sdk/skills/vocdoni-sdk/references/census3.md +0 -308
  71. package/plugins/vocdoni-stripe/.claude-plugin/plugin.json +0 -22
  72. package/plugins/vocdoni-stripe/skills/stripe-subscription/SKILL.md +0 -276
  73. package/plugins/vocdoni-stripe/skills/stripe-subscription/references/backend-contract.md +0 -142
  74. package/plugins/vocdoni-stripe/skills/stripe-subscription/references/product-templates.md +0 -132
  75. package/plugins/vocdoni-stripe/skills/stripe-subscription/references/stripe-cli.md +0 -212
  76. package/plugins/vocdoni-stripe/skills/stripe-subscription/scripts/clone-product.sh +0 -247
  77. package/plugins/vocdoni-stripe/skills/stripe-subscription/scripts/stripe-json.sh +0 -223
@@ -1,128 +0,0 @@
1
- /**
2
- * recipes/full-election.ts
3
- *
4
- * The complete Davinci flow in one file, condensed from the SDK's own demo:
5
- *
6
- * 1. organizer SDK (signer WITH provider)
7
- * 2. build an OffchainCensus of N random voters
8
- * 3. createProcess (one 4-option question)
9
- * 4. wait until the process accepts votes
10
- * 5. each voter votes from their OWN SDK (signer, no provider)
11
- * 6. wait for every vote to settle
12
- * 7. end the process and print the tally
13
- *
14
- * This is the spine; every variant (CSP, on-chain, weighted, multi-question)
15
- * is this shape with a different census and/or ballot mode. See the other
16
- * recipes and references/ for those.
17
- *
18
- * Usage:
19
- * tsx full-election.ts
20
- */
21
-
22
- import { JsonRpcProvider, Wallet } from "ethers";
23
- import { DavinciSDK, OffchainCensus, VoteStatus, TxStatus } from "@vocdoni/davinci-sdk";
24
-
25
- const { SEQUENCER_API_URL, CENSUS_API_URL, RPC_URL, PRIVATE_KEY } = process.env as Record<string, string>;
26
- const NUM_VOTERS = 3;
27
-
28
- function organizerConfig() {
29
- return {
30
- signer: new Wallet(PRIVATE_KEY, new JsonRpcProvider(RPC_URL)),
31
- sequencerUrl: SEQUENCER_API_URL,
32
- censusUrl: CENSUS_API_URL,
33
- };
34
- }
35
- function voterConfig(pk: string) {
36
- // Voting needs no provider — a bare Wallet is enough.
37
- return { signer: new Wallet(pk), sequencerUrl: SEQUENCER_API_URL, censusUrl: CENSUS_API_URL };
38
- }
39
-
40
- async function main() {
41
- // 1. Organizer
42
- const sdk = new DavinciSDK(organizerConfig());
43
- await sdk.init();
44
-
45
- // 2. Census of random voters (weight 1 each)
46
- const voters = Array.from({ length: NUM_VOTERS }, () => Wallet.createRandom());
47
- const census = new OffchainCensus();
48
- census.add(voters.map((v) => v.address));
49
-
50
- // 3. Create the process (single question, 4 one-hot options)
51
- let processId = "";
52
- for await (const e of sdk.createProcessStream({
53
- title: "Favourite colour " + Date.now(),
54
- description: "Demo election",
55
- census,
56
- ballot: {
57
- numFields: 4, minValue: "0", maxValue: "1",
58
- uniqueValues: false, costExponent: 1, minValueSum: "1", maxValueSum: "1",
59
- },
60
- timing: { startDate: new Date(Date.now() + 60_000), duration: 3600 * 8 },
61
- questions: [{
62
- title: "What is your favourite colour?",
63
- choices: [
64
- { title: "Red", value: 0 }, { title: "Blue", value: 1 },
65
- { title: "Green", value: 2 }, { title: "Yellow", value: 3 },
66
- ],
67
- }],
68
- })) {
69
- if (e.status === TxStatus.Completed) processId = e.response.processId;
70
- else if (e.status === TxStatus.Failed) throw e.error;
71
- else if (e.status === TxStatus.Reverted) throw new Error(`reverted: ${e.reason}`);
72
- }
73
- console.log("processId:", processId);
74
-
75
- // 4. Wait until the sequencer reports the process is accepting votes
76
- await new Promise((r) => setTimeout(r, 10_000));
77
- for (let i = 0; i < 30; i++) {
78
- try {
79
- if ((await sdk.api.sequencer.getProcess(processId)).isAcceptingVotes) break;
80
- } catch (e: any) {
81
- if (e.code !== 40007) throw e; // not indexed yet
82
- }
83
- await new Promise((r) => setTimeout(r, 10_000));
84
- }
85
- console.log("accepting votes");
86
-
87
- // 5. Each voter votes from their own SDK. Random one-hot choice.
88
- const voteIds: string[] = [];
89
- for (const v of voters) {
90
- const voterSdk = new DavinciSDK(voterConfig(v.privateKey));
91
- await voterSdk.init();
92
- const choice = Math.floor(Math.random() * 4);
93
- const choices = [0, 0, 0, 0];
94
- choices[choice] = 1;
95
- const { voteId } = await voterSdk.submitVote({ processId, choices });
96
- voteIds.push(voteId);
97
- console.log(`voter ${v.address} → option ${choice}, voteId ${voteId}`);
98
- }
99
-
100
- // 6. Wait for all votes to settle (settlement can take minutes)
101
- await Promise.all(
102
- voteIds.map((voteId) =>
103
- sdk.waitForVoteStatus(processId, voteId, VoteStatus.Settled, 800_000, 5_000),
104
- ),
105
- );
106
- console.log("all votes settled");
107
-
108
- // 7. End the process and read the tally
109
- await sdk.endProcess(processId);
110
- await new Promise<void>((resolve) =>
111
- sdk.processes.onProcessResultsSet((id) => {
112
- if (id.toLowerCase() === processId.toLowerCase()) resolve();
113
- }),
114
- );
115
- const info = await sdk.getProcess(processId);
116
- console.log("\nResults:");
117
- info.questions[0].choices.forEach((c, i) =>
118
- console.log(` ${c.title}: ${info.result[i]?.toString() ?? "0"}`),
119
- );
120
- }
121
-
122
- main().then(
123
- () => process.exit(0),
124
- (err) => {
125
- console.error(err);
126
- process.exit(1);
127
- },
128
- );
@@ -1,73 +0,0 @@
1
- /**
2
- * recipes/read-results.ts
3
- *
4
- * End a process and read its final tally.
5
- *
6
- * - (optionally) wait until all expected votes are counted on-chain
7
- * - endProcess (triggers tally decryption + on-chain results)
8
- * - await the ProcessResultsSet contract event
9
- * - print result[] mapped back to the question's options
10
- *
11
- * Needs an organizer signer WITH a provider (reading the contract + ending the
12
- * process are on-chain operations).
13
- *
14
- * Usage:
15
- * tsx read-results.ts <processId> [expectedVoteCount]
16
- */
17
-
18
- import { JsonRpcProvider, Wallet } from "ethers";
19
- import { DavinciSDK, TxStatus } from "@vocdoni/davinci-sdk";
20
-
21
- const { SEQUENCER_API_URL, CENSUS_API_URL, RPC_URL, PRIVATE_KEY } = process.env as Record<string, string>;
22
- const processId = process.argv[2];
23
- const expected = process.argv[3] ? Number(process.argv[3]) : undefined;
24
-
25
- async function main() {
26
- if (!processId) throw new Error("usage: tsx read-results.ts <processId> [expectedVoteCount]");
27
-
28
- const sdk = new DavinciSDK({
29
- signer: new Wallet(PRIVATE_KEY, new JsonRpcProvider(RPC_URL)),
30
- sequencerUrl: SEQUENCER_API_URL,
31
- censusUrl: CENSUS_API_URL,
32
- });
33
- await sdk.init();
34
-
35
- // 1. Optionally wait for the on-chain vote count to reach the expected number.
36
- if (expected !== undefined) {
37
- while (true) {
38
- const info = await sdk.getProcess(processId);
39
- if (Number(info.votersCount) >= expected) break;
40
- console.log(`counted ${info.votersCount}/${expected}…`);
41
- await new Promise((r) => setTimeout(r, 10_000));
42
- }
43
- }
44
-
45
- // 2. End the process (stops voting; triggers tally). Stream the tx.
46
- for await (const event of sdk.endProcessStream(processId)) {
47
- if (event.status === TxStatus.Completed) console.log("Process ended");
48
- else if (event.status === TxStatus.Failed) throw event.error;
49
- else if (event.status === TxStatus.Reverted) throw new Error(`Reverted: ${event.reason}`);
50
- }
51
-
52
- // 3. Wait for results to be set on-chain (escape-hatch contract event).
53
- await new Promise<void>((resolve) => {
54
- sdk.processes.onProcessResultsSet((id, _sender, _result) => {
55
- if (id.toLowerCase() === processId.toLowerCase()) resolve();
56
- });
57
- });
58
-
59
- // 4. Read and display the tally. result[] is one bigint per ballot field.
60
- const info = await sdk.getProcess(processId);
61
- console.log(`\nResults for: ${info.title}`);
62
- info.questions[0].choices.forEach((choice, i) => {
63
- console.log(` ${choice.title}: ${info.result[i]?.toString() ?? "0"}`);
64
- });
65
- }
66
-
67
- main().then(
68
- () => process.exit(0),
69
- (err) => {
70
- console.error(err);
71
- process.exit(1);
72
- },
73
- );
@@ -1,111 +0,0 @@
1
- /**
2
- * recipes/token-census.ts
3
- *
4
- * Create a process whose electorate is an on-chain token / contract census
5
- * (e.g. ERC20 / ERC721 holders), via OnchainCensus.
6
- *
7
- * Unlike a Merkle census, an OnchainCensus is NOT published — it points at an
8
- * existing contract plus an indexer/subgraph URI the sequencer reads holders
9
- * from. Because of that:
10
- * - maxVoters is REQUIRED at process creation
11
- * - after creation, the sequencer needs a moment to import voter weights;
12
- * poll getAddressWeight until your voters appear
13
- *
14
- * This recipe assumes the token/census contract and its indexer already exist.
15
- * (Standing up the indexer for a freshly deployed contract is environment-
16
- * specific — see the SDK's examples/script/src/onchain.ts.)
17
- *
18
- * Usage:
19
- * tsx token-census.ts
20
- */
21
-
22
- import { JsonRpcProvider, Wallet } from "ethers";
23
- import { DavinciSDK, OnchainCensus, TxStatus } from "@vocdoni/davinci-sdk";
24
-
25
- const { SEQUENCER_API_URL, CENSUS_API_URL, RPC_URL, PRIVATE_KEY } = process.env as Record<string, string>;
26
-
27
- // The token/census contract and the indexer endpoint that serves its holders.
28
- const TOKEN_CONTRACT = process.env.TOKEN_CONTRACT!; // 0x… ERC20/721 or census contract
29
- // Indexer URI. OnchainCensus accepts a graphql:// or https:// endpoint the
30
- // sequencer queries for membership/weights, e.g.:
31
- // graphql://indexer.example/<chainId>/<contractAddress>/graphql
32
- const CENSUS_URI = process.env.ONCHAIN_CENSUS_URI!;
33
- const MAX_VOTERS = Number(process.env.ONCHAIN_MAX_VOTERS ?? "10000");
34
-
35
- async function main() {
36
- const sdk = new DavinciSDK({
37
- signer: new Wallet(PRIVATE_KEY, new JsonRpcProvider(RPC_URL)),
38
- sequencerUrl: SEQUENCER_API_URL,
39
- censusUrl: CENSUS_API_URL,
40
- });
41
- await sdk.init();
42
-
43
- // 1. On-chain census — references existing chain data; nothing to publish.
44
- const census = new OnchainCensus(TOKEN_CONTRACT, CENSUS_URI);
45
-
46
- // 2. Create the process. maxVoters is REQUIRED for on-chain censuses.
47
- const { processId } = await sdk.createProcess({
48
- title: "Token-holder governance",
49
- description: "One question, weighted by token balance",
50
- census,
51
- maxVoters: MAX_VOTERS, // REQUIRED
52
- ballot: {
53
- numFields: 4, // 4 one-hot options
54
- minValue: "0",
55
- // headroom for weighted voting: a holder puts their weight in the chosen field
56
- maxValue: "1000000",
57
- uniqueValues: false,
58
- costExponent: 1,
59
- minValueSum: "0",
60
- maxValueSum: "1000000",
61
- },
62
- timing: { startDate: new Date(Date.now() + 60_000), duration: 3600 * 24 },
63
- questions: [
64
- {
65
- title: "Which proposal?",
66
- choices: [
67
- { title: "A", value: 0 },
68
- { title: "B", value: 1 },
69
- { title: "C", value: 2 },
70
- { title: "D", value: 3 },
71
- ],
72
- },
73
- ],
74
- });
75
- console.log("Process created:", processId);
76
-
77
- // 3. Wait for the process to accept votes AND for the sequencer to import
78
- // on-chain weights (token censuses are imported asynchronously).
79
- for (let i = 0; i < 60; i++) {
80
- try {
81
- const p = await sdk.api.sequencer.getProcess(processId);
82
- if (p.isAcceptingVotes) {
83
- console.log("Process is accepting votes");
84
- break;
85
- }
86
- } catch (e: any) {
87
- if (e.code !== 40007) throw e;
88
- }
89
- await new Promise((r) => setTimeout(r, 10_000));
90
- }
91
-
92
- // Example: check a specific holder's imported weight before they vote.
93
- const holder = process.env.HOLDER_ADDRESS;
94
- if (holder) {
95
- const weight = await sdk.getAddressWeight(processId, holder);
96
- console.log(`${holder} weight = ${weight}`); // "0" until imported / if not a holder
97
- }
98
-
99
- // Voters then vote exactly as in cast-vote.ts. For weighted voting, put the
100
- // voter's weight (from getAddressWeight) into the chosen one-hot field:
101
- // const w = Number(await voter.getAddressWeight(processId, addr));
102
- // await voter.submitVote({ processId, choices: [0, w, 0, 0] }); // weight on option 1
103
- }
104
-
105
- main().then(
106
- () => process.exit(0),
107
- (err) => {
108
- console.error(err);
109
- process.exit(1);
110
- },
111
- );
@@ -1,125 +0,0 @@
1
- # `references/ballot-modes.md` — Configuring voting systems via the ballot mode
2
-
3
- Companion to the [[davinci-sdk]] skill. Davinci uses **one parametric ballot circuit** for every voting system. A ballot is a fixed-length array of integers (`choices`), and a small set of parameters — the **ballot mode** — constrains what's valid. Approval, ranking, quadratic, multiple-choice, budget, and plain single-choice are all special cases of the same parameters. This file maps each voting system to a concrete `BallotMode`.
4
-
5
- ## The parameters (recap from `references/process.md`)
6
-
7
- ```ts
8
- interface BallotMode {
9
- numFields: number; // number of fields in the ballot (= choices.length)
10
- minValue: string; // min value any field may take
11
- maxValue: string; // max value any field may take
12
- uniqueValues: boolean; // if true, all field values must be distinct
13
- costExponent: number; // exponent e in the cost sum below
14
- minValueSum: string; // floor on Σ vᵢ^e
15
- maxValueSum: string; // ceiling on Σ vᵢ^e
16
- groupSize?: number; // optional; advanced grouping
17
- }
18
- ```
19
-
20
- A ballot `v = [v₁ … v_numFields]` is **valid** iff:
21
-
22
- - `minValue ≤ vᵢ ≤ maxValue` for every field, and
23
- - if `uniqueValues`, all `vᵢ` are distinct, and
24
- - `minValueSum ≤ Σ vᵢ^costExponent ≤ maxValueSum`.
25
-
26
- Invalid ballots are rejected by the circuit and never reach the tally. Results are accumulated field-by-field: `result[i]` is the weighted sum of `vᵢ` across all voters. (Bounds are strings; remember `choices` are `number`s within `[minValue, maxValue]`.)
27
-
28
- ## Encoding questions as fields
29
-
30
- There are two idioms:
31
-
32
- 1. **One-hot options** (single/multiple/approval): one field per *option*; the value marks selection (`1`) or magnitude (weight / credits). Tally `result[i]` = total received by option *i*. This is what the SDK's examples use.
33
- 2. **Positional** (ranking): one field per *rank slot* or per *option*, the value is the rank.
34
-
35
- For multi-question elections, concatenate the fields of each question and set `numFields` to the total.
36
-
37
- ## Recipes per voting system
38
-
39
- ### Single-choice, N options (one-hot)
40
-
41
- Exactly one option gets `1`, the rest `0`.
42
-
43
- ```ts
44
- ballot = { numFields: N, minValue: "0", maxValue: "1",
45
- uniqueValues: false, costExponent: 1, minValueSum: "1", maxValueSum: "1" };
46
- // pick option j: choices = one-hot(N, j) e.g. N=4, j=2 → [0,0,1,0]
47
- ```
48
-
49
- `maxValueSum: "1"` forces exactly one selection. Use `minValueSum:"0"` to allow abstaining (all zeros).
50
-
51
- ### Approval voting (pick any subset of N)
52
-
53
- Each option is binary; approve as many as you like.
54
-
55
- ```ts
56
- ballot = { numFields: N, minValue: "0", maxValue: "1",
57
- uniqueValues: false, costExponent: 1, minValueSum: "0", maxValueSum: String(N) };
58
- // approve options 0 and 2 of 4: choices = [1,0,1,0]
59
- ```
60
-
61
- Cap approvals with a smaller `maxValueSum` (e.g. "pick up to 3" → `maxValueSum: "3"`).
62
-
63
- ### Multiple-choice (pick between min and max of N)
64
-
65
- ```ts
66
- ballot = { numFields: N, minValue: "0", maxValue: "1", uniqueValues: false,
67
- costExponent: 1, minValueSum: String(min), maxValueSum: String(max) };
68
- ```
69
-
70
- ### Ranked voting (rank N options 1..N)
71
-
72
- Fields hold a permutation of `1..N`; `uniqueValues` forbids ties.
73
-
74
- ```ts
75
- ballot = { numFields: N, minValue: "1", maxValue: String(N), uniqueValues: true,
76
- costExponent: 1, minValueSum: String(N*(N+1)/2), maxValueSum: String(N*(N+1)/2) };
77
- // rank: option0=2nd, option1=1st, option2=3rd → choices = [2,1,3]
78
- ```
79
-
80
- The sum of `1..N` is fixed (`N(N+1)/2`), so pinning `min/maxValueSum` to it rejects partial rankings.
81
-
82
- ### Quadratic voting (allocate credits, quadratic cost)
83
-
84
- `costExponent: 2` makes a field of value `v` cost `v²`; `maxValueSum` is the credit budget.
85
-
86
- ```ts
87
- ballot = { numFields: N, minValue: "0", maxValue: String(maxCreditsPerOption),
88
- uniqueValues: false, costExponent: 2, minValueSum: "0", maxValueSum: String(budget) };
89
- // spend on options: choices = [2,0,1,0] costs 2²+0+1²+0 = 5 credits
90
- ```
91
-
92
- ### Budget voting (allocate a budget linearly)
93
-
94
- Like quadratic but `costExponent: 1` — the budget is the sum of allocations.
95
-
96
- ```ts
97
- ballot = { numFields: N, minValue: "0", maxValue: String(maxPerOption),
98
- uniqueValues: false, costExponent: 1, minValueSum: "0", maxValueSum: String(budget) };
99
- ```
100
-
101
- ## Weighted voting
102
-
103
- When the census assigns per-voter weights, the voter's weight scales their contribution. The SDK examples model this by putting the **weight** (not `1`) into the chosen one-hot field, and sizing the bounds accordingly:
104
-
105
- ```ts
106
- const maxValue = String(maxOption * maxWeight); // headroom for weight-scaled values
107
- ballot = { numFields: N, minValue: "0", maxValue, uniqueValues: false,
108
- costExponent: 1, minValueSum: "0", maxValueSum: maxValue };
109
- // a weight-5 voter picking option 1: choices = [0,5,0,0]
110
- ```
111
-
112
- The census provides the weight (`sdk.getAddressWeight`); the ballot/verifier circuits enforce that the value used matches the voter's authenticated weight. Size `maxValue`/`maxValueSum` to the largest weight you expect or the circuit will reject high-weight ballots.
113
-
114
- ## Practical defaults
115
-
116
- - Start from single-choice or approval; reach for quadratic/ranked only when the user explicitly asks.
117
- - `numFields` must equal `choices.length` at vote time — keep them in lockstep.
118
- - Bounds are **strings**; `costExponent`/`numFields` are **numbers**.
119
- - The tally `result[i]` is per **field**. For one-hot encodings that's per option; map back to your `questions[].choices` by index.
120
-
121
- ## Cross-references
122
-
123
- - `references/process.md` — where `ballot` lives in `ProcessConfig`; reading `result`.
124
- - `references/voting.md` — the `choices` array and range validation.
125
- - `references/protocol.md` — the formal ballot-protocol definition this is drawn from.
@@ -1,168 +0,0 @@
1
- # `references/census.md` — Censuses (who may vote)
2
-
3
- Companion to the [[davinci-sdk]] skill. A **census** defines the eligible voters and their weights. You pick a census *class*, hand it to `createProcess`, and the facade publishes/normalizes it. This file covers the five census classes, the `CensusOrigin` enum, the all-important `maxVoters` rule, the low-level census REST service, and CSP voting.
4
-
5
- ## `CensusOrigin`
6
-
7
- ```ts
8
- enum CensusOrigin {
9
- OffchainStatic = 1, // fixed off-chain Merkle tree
10
- OffchainDynamic = 2, // off-chain Merkle tree you can append to during voting
11
- Onchain = 3, // on-chain contract (ERC20/721 token holders, etc.)
12
- CSP = 4, // credential service provider (blind-signature style)
13
- }
14
- ```
15
-
16
- ## The five census classes
17
-
18
- All extend an abstract `Census`. Merkle-based ones (`OffchainCensus`, `OffchainDynamicCensus`) collect participants locally and must be **published**; the rest reference an already-existing source and are ready on construction.
19
-
20
- ### `OffchainCensus` — static Merkle tree (the common case)
21
-
22
- ```ts
23
- import { OffchainCensus } from "@vocdoni/davinci-sdk";
24
-
25
- const census = new OffchainCensus();
26
- census.add("0xAbc…"); // single address, weight = 1
27
- census.add(["0xAaa…", "0xBbb…"]); // many addresses, weight = 1
28
- census.add({ key: "0xCcc…", weight: 5 }); // weighted (string | number | bigint)
29
- census.add([{ key: "0xDdd…", weight: "100" }, { key: "0xEee…", weight: 10n }]);
30
- ```
31
-
32
- Read/inspect:
33
-
34
- ```ts
35
- census.remove("0xAbc…");
36
- census.getWeight("0xCcc…"); // "5" | undefined
37
- census.addresses; // string[]
38
- census.participants; // { key: string; weight: string }[]
39
- census.isPublished; // false until createProcess publishes it
40
- census.censusRoot; // null until published
41
- census.censusURI; // null until published
42
- ```
43
-
44
- `createProcess` auto-publishes it (requires `censusUrl` on the SDK). After creation, `census.isPublished === true` and `censusRoot`/`censusURI` are populated. `maxVoters` defaults to the participant count.
45
-
46
- ### `OffchainDynamicCensus` — appendable Merkle tree
47
-
48
- Same API as `OffchainCensus`, but the census may grow during the voting period (new roots get published; never remove voters or change weights — that would enable double voting). Use when eligibility is still being added after the process starts.
49
-
50
- ### `CspCensus` — credential service provider
51
-
52
- ```ts
53
- import { CspCensus } from "@vocdoni/davinci-sdk";
54
- const census = new CspCensus(cspPublicKey /* = censusRoot */, "https://csp-server.example");
55
- ```
56
-
57
- Voter eligibility is certified by a CSP signature instead of a Merkle proof. No local participant list, no publishing. **`maxVoters` is required** at process creation, and **voting requires a CSP proof provider** (see "CSP voting" below).
58
-
59
- ### `OnchainCensus` — token holders / on-chain source
60
-
61
- ```ts
62
- import { OnchainCensus } from "@vocdoni/davinci-sdk";
63
- const census = new OnchainCensus(
64
- "0xTokenOrCensusContract…", // contract address (ERC20/721/custom)
65
- "graphql://indexer.example/137/0xToken…/graphql" // indexer/subgraph URI to read holders
66
- );
67
- census.contractAddress; // getter
68
- ```
69
-
70
- Uses existing on-chain data; nothing to publish. `censusRoot` is set to the 32-byte zero value and the contract address is passed through to the chain. **`maxVoters` is required.** The sequencer imports voter weights from the indexer after creation — expect a short delay before voters appear (poll `sdk.api.sequencer.getAddressWeight`). See `recipes/token-census.ts`.
71
-
72
- ### `PublishedCensus` — reuse an already-published census
73
-
74
- ```ts
75
- import { PublishedCensus, CensusOrigin } from "@vocdoni/davinci-sdk";
76
- const census = new PublishedCensus(CensusOrigin.OffchainStatic, "0xroot…", "https://…/census");
77
- ```
78
-
79
- Wraps a census published in a prior session. Read-only; **`maxVoters` is required**.
80
-
81
- ## `maxVoters` requirement summary
82
-
83
- | Class | Publishing | `maxVoters` at `createProcess` |
84
- | ------------------------ | ---------- | ------------------------------ |
85
- | `OffchainCensus` | auto | optional (defaults to count) |
86
- | `OffchainDynamicCensus` | auto | optional (defaults to count) |
87
- | `OnchainCensus` | none | **required** |
88
- | `CspCensus` | none | **required** |
89
- | `PublishedCensus` | none | **required** |
90
- | manual `{type,root,size,uri}` | none | **required** |
91
-
92
- ## Manual census config (advanced)
93
-
94
- Skip the classes entirely:
95
-
96
- ```ts
97
- await sdk.createProcess({
98
- census: { type: CensusOrigin.OffchainStatic, root: "0xroot…", size: 100, uri: "https://…" },
99
- maxVoters: 100,
100
- // …
101
- });
102
- ```
103
-
104
- ## Low-level census service: `sdk.api.census`
105
-
106
- For building/inspecting censuses outside `createProcess`'s auto-publish. This is `VocdoniCensusService` (needs `censusUrl`). Key methods:
107
-
108
- ```ts
109
- sdk.api.census.createCensus(): Promise<string> // → working censusId
110
- sdk.api.census.addParticipants(censusId, participants): Promise<void> // [{ key, weight }]
111
- sdk.api.census.publishCensus(censusId): Promise<PublishCensusResponse> // { root, uri, size, … }
112
- sdk.api.census.getCensusRoot(censusId): Promise<string>
113
- sdk.api.census.getCensusSize(censusIdOrRoot): Promise<number> // auto-detects id vs root
114
- sdk.api.census.getCensusProof(censusRoot, key): Promise<CensusProof> // membership proof
115
- sdk.api.census.deleteCensus(censusId): Promise<void>
116
- ```
117
-
118
- ```ts
119
- // Build, publish, then create a process against the published root:
120
- const censusId = await sdk.api.census.createCensus();
121
- await sdk.api.census.addParticipants(censusId, [{ key: addr, weight: "1" }]);
122
- const { root, uri, size } = await sdk.api.census.publishCensus(censusId);
123
- await sdk.createProcess({ census: { type: CensusOrigin.OffchainStatic, root, size, uri },
124
- maxVoters: size, /* … */ });
125
- ```
126
-
127
- ## How voting fetches the census proof
128
-
129
- You usually don't touch this — `submitVote` does it. For reference:
130
-
131
- - **Merkle censuses** (Offchain*/Onchain): the SDK fetches just the voter's **weight** from the sequencer (`getAddressWeight`); the full Merkle proof isn't needed in the vote payload.
132
- - **CSP census**: the SDK calls your **CSP proof provider** (there is no default), which must return a `CSPCensusProof`.
133
-
134
- ### CSP voting (`censusProviders.csp`)
135
-
136
- A voter on a CSP census must supply a `csp` provider in the SDK config:
137
-
138
- ```ts
139
- import { DavinciSDK, CensusOrigin } from "@vocdoni/davinci-sdk";
140
-
141
- const voter = new DavinciSDK({
142
- signer: new Wallet(voterPk),
143
- sequencerUrl,
144
- censusProviders: {
145
- csp: async ({ processId, address }) => {
146
- // Obtain a CSP credential. The bundled DavinciCSP helper can sign for testing:
147
- const csp = await sdk.getCSP(); // any initialised SDK instance
148
- const out = await csp.cspSign(CensusOrigin.CSP, CSP_PRIVATE_KEY, processId, address, weight);
149
- return {
150
- censusOrigin: CensusOrigin.CSP,
151
- root: out.root, address: out.address, weight,
152
- processId: out.processId, publicKey: out.publicKey,
153
- signature: out.signature, voterIndex: out.index,
154
- };
155
- },
156
- },
157
- });
158
- await voter.init();
159
- await voter.submitVote({ processId, choices });
160
- ```
161
-
162
- `CSPCensusProof` shape: `{ root, address, weight, censusOrigin: CSP, processId, publicKey, signature, voterIndex? }`. In production the provider would call your real CSP server rather than signing locally. `sdk.getCSP()` returns a `DavinciCSP` helper with `cspSign(...)` and `cspCensusRoot(censusOrigin, privKey)` (used to derive the root you pass to `new CspCensus(root, uri)`).
163
-
164
- ## Cross-references
165
-
166
- - `references/process.md` — passing the census to `createProcess` and the `maxVoters` rule.
167
- - `references/voting.md` — the vote flow that consumes census proofs.
168
- - `recipes/token-census.ts` — full `OnchainCensus` flow.