Skip to content
On this page

integration

Concrete snippets for gating your community, DAO, forum, or app on an OC Vote poll. Every example uses @orangecheck/vote-core (opens in a new tab) + @orangecheck/vote-cli (opens in a new tab) + the curl-friendly /api/tally endpoint.

fork-ready templatesLink to this section

Three copy-forkable integrations live at orangecheck/oc-vote-examples (opens in a new tab):

  • Discord bot (opens in a new tab) — /poll <id> + /poll-watch <id> slash commands that render tallies as embeds with bar charts. Stateless. ~200 lines of discord.js.
  • GitHub Action gate (opens in a new tab) — uses: orangecheck/oc-vote-examples/github-action-gate@main. Gates a job on a poll's tally via a configurable jq expression. Outputs state + passed + tally-json.
  • Shell recipes (opens in a new tab) — one-liner deploy-gates, create/vote/reveal flows, cron pollers, discovery — pure bash + npx @orangecheck/vote-cli.

Fork, swap the placeholder poll id / Discord token / whatever, ship. Nothing in those templates is load-bearing for the protocol; they're UI patterns on top of the same /api/tally endpoint this page describes.

check a tally result server-sideLink to this section

You've shipped a poll. You want your backend (Discord bot, forum moderator, DAO executor) to read the tally and act.

TypeScript
// anywhere in Node 20+
const pollId =
    '9825268c74a3a15baefe8f9705f774cc7bb97205922fc828df3b377e0e158a18';
const res = await fetch(`https://vote.ochk.io/api/tally?poll=${pollId}`);
if (!res.ok) throw new Error(`tally: HTTP ${res.status}`); // 400 bad id, 404 not found
const tally = (await res.json()) as {
    state: string;
    tallies?: Record<string, number>;
};

if (tally.state !== 'tallied' || !tally.tallies)
    throw new Error('poll not ready');
const top = Object.entries(tally.tallies).sort((a, b) => b[1] - a[1])[0];
// top = [optionId, weight], e.g. ['yes', 12311]

The endpoint verifies every BIP-322 signature before returning. A counted answer is kept for up to 60 seconds and voters' coins for up to two minutes, so a spend can show about three minutes late; counted_at says when the coins were read. For higher-value decisions, verify independently with the CLI — see below.

independent verification (the right way for high-value decisions)Link to this section

Shell
npx -y @orangecheck/vote-cli tally <poll_id> --json

The package's command is oc-vote: after npm i -g @orangecheck/vote-cli, oc-vote tally <poll_id> --json is the same.

The CLI also casts a ballot: oc-vote vote --poll <poll_id> --voter <address> --option <id>. From vote-cli 0.7.6 it exits 0 only once 2 relays serve the signed ballot back, and 2 while it isn't in yet. In an anchored poll the ballot's stamp has to be in too, since a final count needs it, and from vote-cli 0.7.7 a stamp that could not be made at all also exits 2. Neither version is on npm yet. A version before 0.7.6 can exit 0 with the ballot missing, and one before 0.7.7 with its stamp missing, so a script on one should read the printed lines, not only the exit status.

The CLI pulls the poll + ballots from Nostr (--relay to pick relays), verifies every BIP-322 signature with @orangecheck/bip322, reads the UTXOs confirmed by the snapshot block from an Esplora API (--mempool-base, default mempool.space), and runs the pure tally function. Like /api/tally, it counts coins that are still unspent, so a coin spent after the snapshot drops out. If the JSON snapshot_block, turnout and tallies match vote.ochk.io's /api/tally, both implementations agree. If they don't — trust the CLI.

Pipe it into anything:

Shell
# CI-style gate
RESULT=$(npx -y @orangecheck/vote-cli tally "$POLL_ID" --json | jq -r '.tallies.yes > .tallies.no')
[[ "$RESULT" == "true" ]] && ./deploy.sh

embed the tally as a Nostr-native signalLink to this section

Because polls and ballots live on Nostr (kinds 30080 / 30081 / 30082), any Nostr client can subscribe to a poll's ballots without touching vote.ochk.io at all. Filter:

JSON
{ "kinds": [30081], "#t": ["<poll_id>"] }

Filter on #t: relays index single-letter tags only, and most reject a filter on a longer name such as #poll_id.

Parse each event's content as a Ballot and feed them to tally(), which checks each ballot's BIP-322 signature over its ballotId() against voter and drops the ones that fail.

tally it yourselfLink to this section

Everything vote.ochk.io does, in one script: the poll and its ballots from the default relays, the snapshot block, UTXOs from mempool.space, and the pure function. Run on the poll above, it prints the same snapshot_block, turnout and tallies as /api/tally and the CLI.

npm install @orangecheck/vote-core @orangecheck/nostr-core @orangecheck/bip322
TypeScript
import type { Ballot, Poll, Utxo } from '@orangecheck/vote-core';

import { verifySignature } from '@orangecheck/bip322';
import { queryEvents } from '@orangecheck/nostr-core';
import {
    mempoolBlockTimeSource,
    pollId,
    resolvePollSnapshot,
    tally,
} from '@orangecheck/vote-core';

const id = '9825268c74a3a15baefe8f9705f774cc7bb97205922fc828df3b377e0e158a18';
const parse = <T>(content: string): T | null => {
    try {
        return JSON.parse(content) as T;
    } catch {
        return null;
    }
};

// 1. The poll (the event whose content hashes to the id) and its ballots.
const { events: pollEvents } = await queryEvents({
    kinds: [30080],
    '#t': [id],
});
const poll = pollEvents
    .map((e) => parse<Poll>(e.content))
    .find((p) => p && pollId(p) === id);
if (!poll) throw new Error('poll not found on any relay that answered');
const { events: ballotEvents } = await queryEvents({
    kinds: [30081],
    '#t': [id],
});
const ballots = ballotEvents
    .map((e) => parse<Ballot>(e.content))
    .filter((b): b is Ballot => b !== null);

// 2. The snapshot block: the poll's own height, or the block at its deadline.
const snap = await resolvePollSnapshot(poll, mempoolBlockTimeSource());
if (!snap.ok) throw new Error(`${snap.code}: ${snap.reason}`);

// 3. UTXOs from mempool.space: coins unspent now and confirmed by the snapshot.
//    Coins spent after the snapshot are missed; your own node can count them.
const utxosAt = async (address: string, height: number): Promise<Utxo[]> => {
    const res = await fetch(
        `https://mempool.space/api/address/${address}/utxo`
    );
    const utxos = (await res.json()) as {
        value: number;
        status: { confirmed: boolean; block_height?: number };
    }[];
    return utxos
        .filter((u) => u.status.confirmed && u.status.block_height! <= height)
        .map((u) => ({
            value: u.value,
            confirmed_height: u.status.block_height!,
        }));
};

const result = await tally({
    poll,
    ballots,
    snapshotBlock: snap.height,
    utxosAt,
    verify: ({ address, message, signature }) =>
        verifySignature(address, message, signature),
});
console.log(JSON.stringify(result));

For an anchored poll (deadline on or after 2026-11-15T00:00:00Z), also pass tipHeight, closeHeight and anchorHeight: see the tally algorithm.

queryEvents reports which relays answered in relayStatus; a relay that did not answer is not evidence that a ballot is missing. A tally counts only when four of the five relays (the read floor) answered in full, each read paged with until until a page comes back shorter than the limit, and none was cut off; the sample above reads one page. Below the floor a clock-dated poll gets no count, and an anchored poll's tally is at most provisional (SPEC §6.5).

publish a poll and a ballot from codeLink to this section

The poll and each ballot are signed with the creator's and voter's own keys (BIP-322), then carried in Nostr events signed by any fresh key. The t tags are what readers query, so copy them exactly: the full shapes are on the spec page.

npm install @orangecheck/vote-core @orangecheck/nostr-core @orangecheck/bip322 @noble/curves @noble/hashes
TypeScript
import type { NostrEvent } from '@orangecheck/nostr-core';
import type { Ballot, Poll } from '@orangecheck/vote-core';

import { schnorr, secp256k1 } from '@noble/curves/secp256k1.js';
import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js';
import { addressFromPrivateKey, signMessage } from '@orangecheck/bip322';
import {
    getEventHash,
    publishEvent,
    publishOutcome,
} from '@orangecheck/nostr-core';
import { ballotId, canonicalBytes, pollId } from '@orangecheck/vote-core';

const iso = (ms: number) =>
    new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');

// A Nostr event under a fresh key: the BIP-322 signature in `content` is the proof.
function nostrEvent(
    kind: number,
    tags: string[][],
    content: string
): NostrEvent {
    const sk = secp256k1.utils.randomSecretKey();
    const pubkey = bytesToHex(schnorr.getPublicKey(sk));
    const unsigned = {
        kind,
        tags,
        content,
        pubkey,
        created_at: Math.floor(Date.now() / 1000),
    };
    const id = getEventHash(unsigned);
    return {
        ...unsigned,
        id,
        sig: bytesToHex(schnorr.sign(hexToBytes(id), sk)),
    };
}

// 1. The poll, signed by its creator.
const creatorKey = process.env.CREATOR_KEY!; // WIF of the creator's address
const creator = addressFromPrivateKey(creatorKey, 'p2wpkh');
const poll: Poll = {
    v: 0,
    kind: 'oc-vote/poll',
    creator,
    question: 'Ship the release on Friday?',
    options: [
        { id: 'yes', label: 'Yes' },
        { id: 'no', label: 'No' },
    ],
    deadline: iso(Date.now() + 7 * 86_400_000),
    snapshot_block: 'deadline',
    weight_mode: 'sats',
    weight_params: null,
    min_sats: 10_000,
    min_days: 0,
    mode: 'public',
    reveal_pk: null,
    tiebreak: 'latest',
    notes: null,
    created_at: iso(Date.now()),
    sig: { alg: 'bip322', pubkey: creator, value: '' },
};
const id = pollId(poll);
poll.sig.value = signMessage(creator, id, creatorKey);

const pollEvent = nostrEvent(
    30080,
    [
        ['d', `oc-vote:poll:${id}`],
        ['t', id],
        ['t', 'oc-vote-poll'],
        ['t', creator],
        ['poll_id', id],
        ['creator', creator],
        ['deadline', poll.deadline],
        ['snapshot', String(poll.snapshot_block)],
        ['mode', poll.mode],
    ],
    canonicalBytes(poll)
);
console.log('poll:', publishOutcome(await publishEvent(pollEvent)));

// 2. A ballot, signed by a voter.
const voterKey = process.env.VOTER_KEY!;
const voter = addressFromPrivateKey(voterKey, 'p2wpkh');
const ballot: Ballot = {
    v: 0,
    kind: 'oc-vote/ballot',
    poll_id: id,
    voter,
    option: 'yes',
    attestation_id: null,
    secret: null,
    created_at: iso(Date.now()),
    sig: { alg: 'bip322', pubkey: voter, value: '' },
};
const bid = ballotId(ballot);
ballot.sig.value = signMessage(voter, bid, voterKey);

const ballotEvent = nostrEvent(
    30081,
    [
        ['d', `oc-vote:ballot:${id}:${voter}`],
        ['t', id],
        ['t', 'oc-vote-ballot'],
        ['t', voter],
        ['poll_id', id],
        ['voter', voter],
        ['ballot_id', bid],
    ],
    canonicalBytes(ballot)
);
console.log('ballot:', publishOutcome(await publishEvent(ballotEvent)));
console.log(`https://vote.ochk.io/p/${id}`);

publishEvent sends to the default relays and reports each one; publishOutcome says whether none, some (partial) or all accepted. A relay's OK is not proof it stored the event: read it back with queryEvents, asking each relay on its own, and tell anyone the poll is live only once two of them serve back a copy that verifies (SPEC §3.4). A wallet can sign in place of a key you hold: signMessage takes the 64-hex id, as getSigner does in a browser.

gate a Discord botLink to this section

TypeScript
declare function reply(text: string): Promise<unknown>; // your bot's
declare function grantRole(user: string): Promise<void>; // your bot's

// Called from your bot's command handler.
async function onPollCommand(pollId: string, user: string) {
    const res = await fetch(`https://vote.ochk.io/api/tally?poll=${pollId}`);
    const result = (await res.json()) as {
        state: string;
        tallies?: Record<string, number>;
    };
    if (result.state !== 'tallied' || !result.tallies)
        return reply('poll still open');
    const passed = (result.tallies.yes ?? 0) > (result.tallies.no ?? 0);
    if (passed) await grantRole(user);
}

For long-running votes, poll /api/tally every 5 minutes; for settled decisions, run one CLI verification once the tally is final.

gate a forum / submission queueLink to this section

  • Post creation requires signing the submission against the poster's Bitcoin address (BIP-322).
  • Before admitting the post, verify the poster's OC Vote threshold: either by running a fresh OC Vote tally against a currently-running "membership" poll, or by checking a specific ballot event.

weight a DAO executorLink to this section

DAO governance frameworks can treat an OC Vote tally as the oracle for an on-chain execution. Pattern:

  1. A DAO contract waits for a specific poll_id's tally to be final.
  2. A signer (any honest observer) submits the tally + a proof (all ballot events + UTXO snapshot root) to the contract.
  3. The contract verifies the tally by running the pure function in-contract OR by checking that N independent signers agree on the result.

OC Vote does not prescribe the on-chain half — you write that half in whatever chain's language suits you. The contribution is: a reproducible, sybil-resistant, offline-verifiable result that any honest observer produces byte-identically.

ballot-cast-on-behalf flowsLink to this section

The protocol does not currently specify delegation (see oc-vote-protocol/SPEC.md §13 "Future work"). For now, voters sign their own ballots. If you need proxy voting, have the proxy address itself be credibly bonded and have delegators publish a separate signed "I delegate to bc1q..." message that your client interprets.

self-host the tallierLink to this section

If you care about the tallier's availability:

Shell
git clone https://github.com/orangecheck/oc-vote-protocol
npm i @orangecheck/vote-core @orangecheck/vote-cli
# self-host the Nostr relay set if you want end-to-end independence

The tally function has zero external dependencies beyond: a Bitcoin node (or any explorer), a Nostr relay set (or raw event JSON), and BIP-322 verification. vote.ochk.io is convenience; correctness is the library.