SuperAPI AI Directory

vocdoni-integrator-sdk

Agents & models

View repository

Updated 11-04 16:17

About this skill

Vocdoni Integrator SDK

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.elections authenticates the voter directly against the voting process; one verified authToken covers check/sign for every question.
  • Reads are public, writes are authed, drafts are gated. client.elections reads (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 PII eligibleMemberIds lists 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 same client.elections.
  • chainId comes from the public process read. Vote signatures are chain-id-bound; read the process's own chainId off client.elections.get(processId). Do NOT use client.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 on GET /processes/{id}/results — finalResults distinguishes live from final, and a secretUntilTheEnd tally 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 an openValue: true choice (singlechoice / multichoice / cumulative), a manager read (or a voting:write key) of its results also returns memos?: 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 a VotingProcessResponse with a questions[] array. Each question is a separate on-chain Vochain election (question.upstreamId is 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, not ONGOING. computeProcessStatus(questions, { startDate }) derives the top-level status from all question statuses. Any question ONGOING → ONGOING; all ENDED/RESULTS → ENDED. Statuses: ONGOING, PAUSED, ENDED, CANCELED, UPCOMING, RESULTS, PROCESS_UNKNOWN. The chain has no upcoming state: a published process with a future startDate reports its questions as live (READY) yet rejects every vote until the start, so always pass the process's startDate — live questions then read as UPCOMING until it passes. isLive(process) / isUpcoming(process) do this for you; useElection().status does too and flips to ONGOING on its own at the start.
  • Ballot encoding is per-question. Use encodeQuestionSelections(question, answers) from @vocdoni/ballot to produce each question's number[], then pass number[][] to vote(). It is encodeQuestionBallot plus 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 for encodeQuestionBallot only 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 with metadata: { type: { name: 'ranked' } } alongside the raw protocol (the backend's type vocabulary is singlechoice/multichoice only, 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) to encodeQuestionSelections(question, order), which transposes it and encodes in one step; rankedOrderToScores does the transposition alone. A ranking must be complete, every choice needs a distinct value, maxValue must not be 0, and an election-level ranked declaration must have exactly one question — all four are refused at creation and at encode time. decodeQuestionResults aggregates Borda (Σ count × rank, so votes is points, not people) and emits no abstain bucket, and react-components renders 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 — a ranked name on maxCount: 1 is single-choice, an approval protocol labelled single-choice-multiquestion is approval — and only a question with no ballotProtocol is typed by name alone.
  • A question may carry no ballot type at all — infer it with tryInferQuestionBallotType in render code. GET /processes also lists legacy vochain elections as read-only projections (legacy: true), and most of their questions arrive with type: "", no ballotProtocol (despite the declared type) and no metadata. 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 use tryInferQuestionBallotType(question) from @vocdoni/ballot instead, which returns undefined for such a question; treat undefined as "unknown": no ballot can be cast for it and its results cannot be decoded. questionSelectionRange, questionReservesAbstain and decodeQuestionResults still throw on it, so check first. react-components does this for you: the type badge and tip render nothing, <ElectionQuestions /> shows the choices disabled with an errors.question_unsupported message and refuses to submit a ballot including it, and <ElectionResults /> lists its choices with empty votes/percent.
  • Never set uniqueChoices / uniqueValues on a named multichoice question (the dense layout). The named multichoice type 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 while voteCount keeps rising. client.elections.create/update rejects typeSetup.uniqueChoices on multichoice — as the API itself now does — and rejects an unsatisfiable ballotProtocol; encodeQuestionBallot refuses to encode for such a question, and also refuses a ballot the chain would drop (a value above maxValue, a repeated value under uniqueValues — e.g. duplicate ranks). Detect an already-created broken one with unsatisfiableQuestionReason(question) from @vocdoni/ballot. (A raw ballotProtocol pick-slot multichoice legitimately carries uniqueValues: true — that is the index-list layout, distinct from dense.)
  • A raw ballotProtocol must reach every published choice.value. Single-choice is value-addressed: the ballot field and the results column are both choice.value, and maxValue is derived from the highest value (values may be sparse — unused columns just stay empty). A value above maxValue (or two choices sharing one value) makes that option uncastable; on a pick-slot multichoice, values that are not exactly 0..numChoices-1 collide with the abstain sentinels instead. Either way the chain accepts the ballot, counts it in voteCount and drops it at tally, so the option polls zero while the vote looks cast. client.elections.create/update refuses such a question outright — the only moment it is still fixable. At encode time encodeQuestionBallot / validateSelections refuse 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 with uncastableChoicesReason(question) / hasUncastableChoices(question). Position-addressed layouts (approval, dense multichoice, budget, quadratic) are unaffected — there choice.value is 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. Pass lang to new VocdoniApiClient({ apiUrl, lang }) — a string, or a getter like () => i18n.language that is re-read on every request — or call client.setLang(...) when the locale changes mid-session. It rides along as a lang query 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. EphemeralSigner generates 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, and client.pricing() (public). A publish can be refused with 402 (ApiErrorCode, isApiError); checkout opens a top-up for the shortfall and the webhook publishes the draft. Details in references/client.md.
  • Gotcha: a draft update overwrites addOns. elections.update PUTs the whole draft, so omitting addOns clears them: resend them on every update.
  • Gotcha: publishAndWait waits indefinitely by default. Its timeoutMs defaults to Infinity, unlike jobs.waitFor (60 s); pass timeoutMs or signal to bound it.
  • Relaying is async. elections.vote() returns a jobId. Poll jobs.waitFor(jobId) to get the vote nullifier (voteID). The VotingClient.vote() method returns the jobId; the React useElection().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 single voteId is deprecated and only ever shows one. Server-side, elections.signInfo(id, { authToken }) returns the same set as consumed[].
  • An anonymous census is unlinkable, not ZK. census.anonymous: true makes the CSP blind-sign — it never sees the ephemeral address, so it cannot link voter → vote. EnvelopeType.Anonymous stays false; this is a blind signature, not a zk-SNARK (that is @vocdoni/api-voting-zk, a separate path). Consequence: signInfo().consumed[] carries no address and no nullifier for such a process — both fields are optional now — and check() reports hasVoted: false for everyone (only hasSigned). The only proof a vote is on chain is its nullifier, voteNullifier(signer.address, upstreamId) from @vocdoni/api-voting, checked with client.elections.verifyVotes([nullifier]) (POST /votes/verify, public). ElectionProvider keeps each confirmed anonymous nullifier in the tab's sessionStorage, so a reload of the same tab still reads hasVoted; a new tab or device reads the question as signed.
  • hasVoted means "on chain", hasSigned means "the CSP authorized it". A vote can be signed and never land (a relay lost to a proxy 502). ElectionProvider reports a question voted only on on-chain evidence, stores every signed tx in the tab's sessionStorage (vocdoni.pendingVote.<upstreamId>.<nullifier>) before relaying it, and re-sends that same tx — never a new signature — on the next vote() or on connect. A backend without hasSigned keeps 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.