A monorepo of TypeScript packages that replaces the @vocdoni/sdk with a SaaS-first approach. Everything goes through the Vocdoni SaaS API; the SDK never talks to the blockchain directly.
Packages at a glance
| Package | What it does |
|---|---|
@vocdoni/api-types |
Shared TypeScript interfaces — no runtime code |
@vocdoni/api-client |
HTTP client wrapping the SaaS REST API ⚠️ surface in flux |
@vocdoni/api-voting |
CSP auth, vote envelope, ballot encryption, vote-tx signing |
@vocdoni/api-voting-zk |
ZK/anonymous voting: SIK derivation, Groth16 proofs, circuit fetching |
@vocdoni/react-providers |
Headless React context providers and hooks |
@vocdoni/react-components |
Unstyled React UI components built on react-providers |
Common task → reference
| User wants to… | Read first | Recipe |
|---|---|---|
| Understand the HTTP client, sub-clients, jobs | references/client.md |
— |
| Cast a vote (low-level, no React) | references/voting.md |
recipes/single-choice-vote.ts |
| Cast a multi-choice or approval vote | references/voting.md |
recipes/multichoice-vote.ts |
| Create, cast or tally a ranked question | references/voting.md (ranked section) |
recipes/multichoice-vote.ts (Format C) |
| Cast a vote on an encrypted election | references/voting.md |
recipes/encrypted-vote.ts |
| Set up the CSP auth flow manually | references/client.md + references/voting.md |
recipes/single-choice-vote.ts |
| Cast a vote on an anonymous (blind CSP) census | references/voting.md |
recipes/anonymous-vote.ts |
| Add voting to a React app | references/react.md |
— |
| Manage election lifecycle (pause/end/cancel) | references/react.md + references/client.md |
— |
| Price a process, pay for publish or census growth, manage wallets and spend caps | references/client.md (Pay-per-process billing) |
— |
| ZK/anonymous voting | references/zk-voting.md |
— |
The vote flow in one minute
Every vote follows the same steps regardless of election type. The whole voter
flow is public or auth-token-identified — no bundle, no API key: the process
read (GET /processes/{id}, client.elections.get) is public for published
processes (drafts 404 to anyone but the org's managers), so the voter app
reads chainId and the questions directly:
1. GET /processes/{id} → VotingProcessResponse: chainId (vote signatures
are bound to it), questions[] with per-question
ballotProtocol/encryptionKeys and live results
GET /processes/{id}/questions/{qId} → public single-question read (same data, one question)
GET /processes/{id}/results → public live per-question tallies (optional, for results view)
2. POST /processes/{id}/auth/0 → auth step 0 (identify the voter)
POST /processes/{id}/auth/1 → auth step 1 (confirm 2FA — skip if auth-only census)
3. POST /processes/{id}/check → belongsToProcess + per-question {questionId, upstreamId, canVote, hasVoted, hasSigned?}
(hasVoted = on chain; hasSigned = the CSP authorized it)
4. POST /processes/{id}/sign-batch → CSP signs a fresh ephemeral address per question — ALL
questions in ONE call (client.elections.signBatch; the
single-question POST /processes/{id}/sign still exists)
[repeat steps 5–6 for each votable question]
5. buildVoteTransaction(...) → build + sign the protobuf tx locally
6. POST /vote → relay tx → jobId
GET /jobs/{jobId} → poll until completed → voteID (nullifier)
Anonymous census (process.census.anonymous === true) replaces step 4 with a
two-round blind signature, so the CSP signs a ballot it cannot read:
4a. POST /processes/{id}/blind-point → one blind point (tokenR) + weight per election
4b. (client blinds the CA bundle locally)
4c. POST /processes/{id}/blind-sign → CSP signs the blinded messages
4d. (client unblinds → 96-byte ProofCA signature)
5. buildVoteTransaction({ …, proofType: ProofCA_Type.ECDSA_BLIND_PIDSALTED })
signBlindCspBallots() and ProofCA_Type both come from @vocdoni/api-voting
— import the enum from there, never from @vocdoni/proto directly, or a bundler
inlines protobufjs into your app for one integer. It does 4a–4d in one call; steps
5–6 are unchanged (the relay is proof-type-agnostic). ElectionProvider picks
the branch automatically from census.anonymous — nothing to configure.
Steps 1–4 are handled by @vocdoni/api-client, all on client.elections
(ElectionsClient): get / getResults for the public reads, and the CSP
auth/check/sign routes. (client.processes is a deprecated alias of it.)
Steps 5–6 are handled by @vocdoni/api-voting (VotingClient or buildVoteTransaction directly).
In React, ElectionProvider automates the whole flow — election data, the
voter's CSP auth session (useElectionAuth) and voting (useElection).
(There is no separate ProcessProvider — it was merged into ElectionProvider.)
There is no bundle flow anymore: the legacy /process/bundle/* routes were
removed from the backend along with BundleClient — everything is
process-scoped.
Quick-start (vanilla TS)
import { VocdoniApiClient } from '@vocdoni/api-client'
import { EphemeralSigner, VotingClient } from '@vocdoni/api-voting'
const processId = '<process-mongo-id>'
const client = new VocdoniApiClient({ apiUrl: 'https://saas-api.vocdoni.net' })
const voting = new VotingClient({ client })
// 0. Public process read (published processes need no auth; drafts 404) — the
// chainId vote signatures are bound to comes from here.
const process = await client.elections.get(processId)
const chainId = process.chainId!
// 1. Auth (auth-only census — no 2FA step; else follow with authStep1)
const { authToken } = await client.elections.authStep0(processId, { memberNumber: '42' })
// 2. Check — per-question {questionId, upstreamId, canVote, hasVoted, hasSigned?} in one call.
// hasVoted = on chain; hasSigned = already authorized (a second signature is refused).
const { belongsToProcess, questions } = await client.elections.check(processId, { authToken })
const q = questions.find((s) => s.canVote && !s.hasVoted && !s.hasSigned)
if (!belongsToProcess || !q?.upstreamId) throw new Error('Cannot vote')
// 3. Display data — public single-question read (choices, ballotProtocol, encryptionKeys)
const question = await client.elections.getQuestion(processId, q.questionId)
// 4. CSP sign — electionId is the QUESTION's on-chain id (upstreamId)
const signer = new EphemeralSigner()
const { signature, weight } = await client.elections.sign(processId, {
authToken, electionId: q.upstreamId, payload: signer.address,
})
// 5–6. Build tx, relay, poll for nullifier
const jobId = await voting.vote({
processId: q.upstreamId, chainId, choices: [0],
signer, cspSignature: signature, cspWeight: weight,
})
const job = await client.jobs.waitFor(jobId)
console.log('nullifier:', job.result?.voteID)
Mental model
- The voter's auth token is anchored to the process.
client.electionsauthenticates the voter directly against the voting process; one verifiedauthTokencovers check/sign for every question. - Reads are public, writes are authed, drafts are gated.
client.electionsreads (get,list,getResults) work on a token-less client for published processes — a draft 404s (single read) or is filtered out (list) unless the caller is an org manager/admin or a scoped API key, and the PIIeligibleMemberIdslists are stripped for non-managers. Everything that mutates (create,publish,setQuestionStatus/bulkSetQuestionStatus, census writes) stays API-key/JWT authed. The voter-side CSP surface (auth/check/sign/weight/getQuestion — token-identified) lives on that sameclient.elections. chainIdcomes from the public process read. Vote signatures are chain-id-bound; read the process's ownchainIdoffclient.elections.get(processId). Do NOT useclient.info().chainId— that is the service's current chain id, wrong for processes published before a chain migration.- Results are live and public. Published questions carry a live
results(QuestionResults:voteCount,maxVoters,finalResults, tally matrix) on the single reads and onGET /processes/{id}/results—finalResultsdistinguishes live from final, and asecretUntilTheEndtally matrix stays empty until the keys are revealed. List items never resolve results (poll a single read instead). Open-value memos: if a question has anopenValue: truechoice (singlechoice / multichoice / cumulative), a manager read (or avoting:writekey) of its results also returnsmemos?: string[], the free-text memos of the votes that picked it. Only the read is gated: memos are cleartext on-chain. They are best effort and uncached: absent (never empty) when there are none, on a chain error or while still encrypted. Don't poll a large election hard with manager credentials. - One process, many questions.
GET /processes/{id}returns aVotingProcessResponsewith aquestions[]array. Each question is a separate on-chain Vochain election (question.upstreamIdis its Vochain hex id — also reported publicly by the process check). Voting casts one Vochain transaction per question. - Process status is computed — and a scheduled process is
UPCOMING, notONGOING.computeProcessStatus(questions, { startDate })derives the top-level status from all question statuses. Any questionONGOING→ONGOING; allENDED/RESULTS→ENDED. Statuses:ONGOING,PAUSED,ENDED,CANCELED,UPCOMING,RESULTS,PROCESS_UNKNOWN. The chain has no upcoming state: a published process with a futurestartDatereports its questions as live (READY) yet rejects every vote until the start, so always pass the process'sstartDate— live questions then read asUPCOMINGuntil it passes.isLive(process)/isUpcoming(process)do this for you;useElection().statusdoes too and flips toONGOINGon its own at the start. - Ballot encoding is per-question. Use
encodeQuestionSelections(question, answers)from@vocdoni/ballotto produce each question'snumber[], then passnumber[][]tovote(). It isencodeQuestionBallotplus the one branch that differs per type — a ranked question's collected answer is the voter's ordering, everything else's already is its wire input — so reach forencodeQuestionBallotonly when you already hold wire values. - A ranked question must declare itself; nothing else can tell. A ranked
ballotProtocol(maxCount = numOptions,maxValue = numOptions - 1,uniqueValues: true) is byte-identical to a pick-slot multichoice whose voters fill every slot, and the two are transposes — ranked reads the field index as the option and its value as the rank; pick-slot reads it as a slot holding a chosen option. Create one withmetadata: { type: { name: 'ranked' } }alongside the raw protocol (the backend'stypevocabulary issinglechoice/multichoiceonly, and it stores/echoes the metadata bag verbatim). Without it the question decodes as a multichoice and reports the same number for every option — integrator-sdk#22. Then: ranks go on the wire highest = best — pass the voter's ordering (best first) toencodeQuestionSelections(question, order), which transposes it and encodes in one step;rankedOrderToScoresdoes the transposition alone. A ranking must be complete, every choice needs a distinctvalue,maxValuemust not be 0, and an election-levelrankeddeclaration must have exactly one question — all four are refused at creation and at encode time.decodeQuestionResultsaggregates Borda (Σ count × rank, sovotesis points, not people) and emits no abstain bucket, andreact-componentsrenders a rank widget requiring a complete ranking.declaresRanked(question)reports whether a question is inferred ranked. More generally, the protocol decides the ballot type and a declared name only breaks ties it can't resolve (#58): a name the shape rules out is ignored — arankedname onmaxCount: 1is single-choice, an approval protocol labelledsingle-choice-multiquestionis approval — and only a question with noballotProtocolis typed by name alone. - A question may carry no ballot type at all — infer it with
tryInferQuestionBallotTypein render code.GET /processesalso lists legacy vochain elections as read-only projections (legacy: true), and most of their questions arrive withtype: "", noballotProtocol(despite the declared type) and nometadata.inferQuestionBallotType(question)throws on those by design ("cannot infer ballot type…") — there is nothing to infer from, and guessing would misread the results. Anything that runs during render must usetryInferQuestionBallotType(question)from@vocdoni/ballotinstead, which returnsundefinedfor such a question; treatundefinedas "unknown": no ballot can be cast for it and its results cannot be decoded.questionSelectionRange,questionReservesAbstainanddecodeQuestionResultsstill throw on it, so check first.react-componentsdoes this for you: the type badge and tip render nothing,<ElectionQuestions />shows the choices disabled with anerrors.question_unsupportedmessage and refuses to submit a ballot including it, and<ElectionResults />lists its choices with emptyvotes/percent. - Never set
uniqueChoices/uniqueValueson a namedmultichoicequestion (the dense layout). The namedmultichoicetype derives the dense layout (one 0/1 field per choice), and the scrutinizer applies uniqueness to raw field values — so a dense ballot over more than two choices always repeats a value and is discarded at tally. The election then accepts votes and reports an all-zero result whilevoteCountkeeps rising.client.elections.create/updaterejectstypeSetup.uniqueChoiceson multichoice — as the API itself now does — and rejects an unsatisfiableballotProtocol;encodeQuestionBallotrefuses to encode for such a question, and also refuses a ballot the chain would drop (a value abovemaxValue, a repeated value underuniqueValues— e.g. duplicate ranks). Detect an already-created broken one withunsatisfiableQuestionReason(question)from@vocdoni/ballot. (A rawballotProtocolpick-slot multichoice legitimately carriesuniqueValues: true— that is the index-list layout, distinct from dense.) - A raw
ballotProtocolmust reach every publishedchoice.value. Single-choice is value-addressed: the ballot field and the results column are bothchoice.value, andmaxValueis derived from the highest value (values may be sparse — unused columns just stay empty). A value abovemaxValue(or two choices sharing one value) makes that option uncastable; on a pick-slot multichoice, values that are not exactly0..numChoices-1collide with the abstain sentinels instead. Either way the chain accepts the ballot, counts it invoteCountand drops it at tally, so the option polls zero while the vote looks cast.client.elections.create/updaterefuses such a question outright — the only moment it is still fixable. At encode timeencodeQuestionBallot/validateSelectionsrefuse only the voter picking an out-of-range value (the in-range votes are recorded correctly, so refusing everyone would discard good ballots), but refuse every voter on a pick-slot sentinel collision, which no per-ballot check can detect. Check a question you did not create withuncastableChoicesReason(question)/hasUncastableChoices(question). Position-addressed layouts (approval, dense multichoice, budget, quadratic) are unaffected — therechoice.valueis only a label. - Bearer credentials can be updated explicitly.
client.setAuthToken(token)accepts a string or sync/async getter for subsequent requests;client.setAuthToken()clears the default Authorization header. The constructor snapshots config fields, so use setters or function-valued options instead of mutating the original object. This is separate from the voter's CSP token in request payloads. - The client can override the OTP language. Without an explicit
lang, the voter receives the OTP email/SMS in the organization's default language. Passlangtonew VocdoniApiClient({ apiUrl, lang })— a string, or a getter like() => i18n.languagethat is re-read on every request — or callclient.setLang(...)when the locale changes mid-session. It rides along as alangquery param on every request; leave it unset to use the organization's default language. - The vote tx is signed by an ephemeral key, not the voter's wallet.
EphemeralSignergenerates a fresh secp256k1 keypair per vote; the CSP signs its Ethereum address. This decouples the voter's identity from the on-chain signature. - Pay-per-process billing.
client.elections.getPrice/checkout/getCheckout/cancelCheckout/censusCheckout,client.organizations.getWallet/topUpWallet/updateManaged, andclient.pricing()(public). A publish can be refused with 402 (ApiErrorCode,isApiError);checkoutopens a top-up for the shortfall and the webhook publishes the draft. Details inreferences/client.md. - Gotcha: a draft update overwrites
addOns.elections.updatePUTs the whole draft, so omittingaddOnsclears them: resend them on every update. - Gotcha:
publishAndWaitwaits indefinitely by default. ItstimeoutMsdefaults toInfinity, unlikejobs.waitFor(60 s); passtimeoutMsorsignalto bound it. - Relaying is async.
elections.vote()returns ajobId. Polljobs.waitFor(jobId)to get the vote nullifier (voteID). TheVotingClient.vote()method returns the jobId; the ReactuseElection().vote()awaits the full job for each question. - One nullifier per question, not per process. A voter who answered N questions holds N vote ids. Read them all from
useElection().voteIds(Record<questionId, string>) — the older singlevoteIdis deprecated and only ever shows one. Server-side,elections.signInfo(id, { authToken })returns the same set asconsumed[]. - An anonymous census is unlinkable, not ZK.
census.anonymous: truemakes the CSP blind-sign — it never sees the ephemeral address, so it cannot link voter → vote.EnvelopeType.Anonymousstays false; this is a blind signature, not a zk-SNARK (that is@vocdoni/api-voting-zk, a separate path). Consequence:signInfo().consumed[]carries noaddressand nonullifierfor such a process — both fields are optional now — andcheck()reportshasVoted: falsefor everyone (onlyhasSigned). The only proof a vote is on chain is its nullifier,voteNullifier(signer.address, upstreamId)from@vocdoni/api-voting, checked withclient.elections.verifyVotes([nullifier])(POST /votes/verify, public).ElectionProviderkeeps each confirmed anonymous nullifier in the tab'ssessionStorage, so a reload of the same tab still readshasVoted; a new tab or device reads the question assigned. hasVotedmeans "on chain",hasSignedmeans "the CSP authorized it". A vote can be signed and never land (a relay lost to a proxy 502).ElectionProviderreports a question voted only on on-chain evidence, stores every signed tx in the tab'ssessionStorage(vocdoni.pendingVote.<upstreamId>.<nullifier>) before relaying it, and re-sends that same tx — never a new signature — on the nextvote()or on connect. A backend withouthasSignedkeeps the old behaviour (hasVoted= signed, trusted as on chain).
A note on api-client stability
@vocdoni/api-client is actively evolving. Always read references/client.md for the current class/method names rather than recalling from training data.