@bitsocial/pubsub-voting 0.0.6

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 (119) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +223 -0
  3. package/dist/chain/bucket.d.ts +13 -0
  4. package/dist/chain/bucket.js +24 -0
  5. package/dist/chain/coalescer.d.ts +56 -0
  6. package/dist/chain/coalescer.js +217 -0
  7. package/dist/chain/ticker.d.ts +15 -0
  8. package/dist/chain/ticker.js +25 -0
  9. package/dist/chain/types.d.ts +90 -0
  10. package/dist/chain/types.js +1 -0
  11. package/dist/checkpoint/codec.d.ts +54 -0
  12. package/dist/checkpoint/codec.js +99 -0
  13. package/dist/client/root-puller.d.ts +49 -0
  14. package/dist/client/root-puller.js +140 -0
  15. package/dist/client/voter.d.ts +239 -0
  16. package/dist/client/voter.js +1343 -0
  17. package/dist/crdt/codec.d.ts +41 -0
  18. package/dist/crdt/codec.js +137 -0
  19. package/dist/crdt/crdt.d.ts +22 -0
  20. package/dist/crdt/crdt.js +127 -0
  21. package/dist/crdt/store.d.ts +8 -0
  22. package/dist/crdt/store.js +23 -0
  23. package/dist/crdt/types.d.ts +87 -0
  24. package/dist/crdt/types.js +1 -0
  25. package/dist/encoding/canonical.d.ts +22 -0
  26. package/dist/encoding/canonical.js +26 -0
  27. package/dist/errors.d.ts +81 -0
  28. package/dist/errors.js +126 -0
  29. package/dist/index.d.ts +32 -0
  30. package/dist/index.js +43 -0
  31. package/dist/rules/constant.d.ts +14 -0
  32. package/dist/rules/constant.js +18 -0
  33. package/dist/rules/erc20-balance.d.ts +30 -0
  34. package/dist/rules/erc20-balance.js +44 -0
  35. package/dist/rules/erc721-min-balance.d.ts +18 -0
  36. package/dist/rules/erc721-min-balance.js +100 -0
  37. package/dist/rules/registry.d.ts +42 -0
  38. package/dist/rules/registry.js +61 -0
  39. package/dist/rules/types.d.ts +74 -0
  40. package/dist/rules/types.js +1 -0
  41. package/dist/schema/common.d.ts +25 -0
  42. package/dist/schema/common.js +24 -0
  43. package/dist/schema/criteria.d.ts +78 -0
  44. package/dist/schema/criteria.js +76 -0
  45. package/dist/schema/directory.d.ts +42 -0
  46. package/dist/schema/directory.js +52 -0
  47. package/dist/schema/votes.d.ts +55 -0
  48. package/dist/schema/votes.js +116 -0
  49. package/dist/signer/eip712.d.ts +103 -0
  50. package/dist/signer/eip712.js +85 -0
  51. package/dist/signer/types.d.ts +31 -0
  52. package/dist/signer/types.js +1 -0
  53. package/dist/storage/browser.d.ts +3 -0
  54. package/dist/storage/browser.js +110 -0
  55. package/dist/storage/memory.d.ts +10 -0
  56. package/dist/storage/memory.js +56 -0
  57. package/dist/storage/node.d.ts +5 -0
  58. package/dist/storage/node.js +106 -0
  59. package/dist/storage/types.d.ts +46 -0
  60. package/dist/storage/types.js +1 -0
  61. package/dist/store/indexeddb.d.ts +9 -0
  62. package/dist/store/indexeddb.js +72 -0
  63. package/dist/store/memory.d.ts +15 -0
  64. package/dist/store/memory.js +22 -0
  65. package/dist/store/select.d.ts +15 -0
  66. package/dist/store/select.js +64 -0
  67. package/dist/store/sqlite.d.ts +11 -0
  68. package/dist/store/sqlite.js +68 -0
  69. package/dist/store/types.d.ts +57 -0
  70. package/dist/store/types.js +1 -0
  71. package/dist/tally/tally.d.ts +44 -0
  72. package/dist/tally/tally.js +89 -0
  73. package/dist/tally/types.d.ts +51 -0
  74. package/dist/tally/types.js +13 -0
  75. package/dist/topic.d.ts +20 -0
  76. package/dist/topic.js +28 -0
  77. package/dist/transport/accepted-dedup.d.ts +30 -0
  78. package/dist/transport/accepted-dedup.js +34 -0
  79. package/dist/transport/announce/browser.d.ts +9 -0
  80. package/dist/transport/announce/browser.js +14 -0
  81. package/dist/transport/announce/node.d.ts +38 -0
  82. package/dist/transport/announce/node.js +162 -0
  83. package/dist/transport/announce/types.d.ts +74 -0
  84. package/dist/transport/announce/types.js +16 -0
  85. package/dist/transport/bundle-store.d.ts +11 -0
  86. package/dist/transport/bundle-store.js +34 -0
  87. package/dist/transport/chase.d.ts +125 -0
  88. package/dist/transport/chase.js +182 -0
  89. package/dist/transport/gossip-validator.d.ts +107 -0
  90. package/dist/transport/gossip-validator.js +99 -0
  91. package/dist/transport/helia.d.ts +55 -0
  92. package/dist/transport/helia.js +114 -0
  93. package/dist/transport/integration/harness.d.ts +65 -0
  94. package/dist/transport/integration/harness.js +278 -0
  95. package/dist/transport/messages.d.ts +97 -0
  96. package/dist/transport/messages.js +117 -0
  97. package/dist/transport/rate-limit.d.ts +11 -0
  98. package/dist/transport/rate-limit.js +20 -0
  99. package/dist/transport/transport.d.ts +20 -0
  100. package/dist/transport/transport.js +35 -0
  101. package/dist/transport/types.d.ts +189 -0
  102. package/dist/transport/types.js +1 -0
  103. package/dist/verify/background.d.ts +81 -0
  104. package/dist/verify/background.js +236 -0
  105. package/dist/verify/bundle.d.ts +58 -0
  106. package/dist/verify/bundle.js +84 -0
  107. package/dist/verify/cache.d.ts +48 -0
  108. package/dist/verify/cache.js +62 -0
  109. package/dist/verify/constraints.d.ts +16 -0
  110. package/dist/verify/constraints.js +35 -0
  111. package/dist/verify/gate-result-cache.d.ts +65 -0
  112. package/dist/verify/gate-result-cache.js +91 -0
  113. package/dist/verify/name-resolution-cache.d.ts +59 -0
  114. package/dist/verify/name-resolution-cache.js +64 -0
  115. package/dist/verify/signature.d.ts +9 -0
  116. package/dist/verify/signature.js +55 -0
  117. package/dist/verify/types.d.ts +101 -0
  118. package/dist/verify/types.js +1 -0
  119. package/package.json +78 -0
package/README.md ADDED
@@ -0,0 +1,223 @@
1
+ # @bitsocial/pubsub-voting
2
+
3
+ Trustless, leaderless voting over libp2p pubsub, designed to run on top of a host node's shared libp2p/Helia instance.
4
+
5
+ > **Status: engine, reactive facade, and live-delta transport implemented and unit-tested.** The zod schemas, canonical dag-cbor encoding, topic derivation, the verify pipeline (signature + constraints + on-chain gate + community-name resolution), the LWW winner-set CRDT with its binary bundle codec, the tally, the transport's **validate-before-forward gossip gate** over **inline bundle deltas**, and the **root-record checkpoint sync** (on-demand encode, suppressed 10-minute topic heartbeat, libp2p-fetch pull, divergent roots chased via directed bitswap) are all implemented — so the reactive `PubsubVoter` / `Contest` (`createContest`) / `ContestVote` (`createContestVote`) facade is live. The gate runs the full validity pipeline on the message bytes in an async gossipsub topic validator *before* re-forwarding, so an invalid bundle (bad signature, wallet the gate rejects, squatted name) is never propagated and `reject` scores the sender. Cold-join checkpoint bundles instead admit on the synchronous offline checks and settle their **deferred chain checks in the background, batched via multicall3** — the tally renders immediately with per-row `chainVerified`/`nameResolved` flags and refines as they land, and a node's own checkpoint only ever serves fully verified bundles (see [DESIGN.md, Background chain verification](./DESIGN.md#background-chain-verification)). **Keeping a live vote from decaying is the consuming client's job** — this library publishes each vote once and exposes `republishIntervalBuckets` so the client can schedule its own refreshes (see [DESIGN.md, Republishing is the client's job](./DESIGN.md#republishing-is-the-clients-job-not-this-librarys)). What remains is host-side (pkc-js registering gossipsub + `@libp2p/fetch` on the shared node) — see [ROADMAP.md](./ROADMAP.md), [DESIGN.md](./DESIGN.md), the [Transport gate](./DESIGN.md#transport-gossipsub-topic--validation), and [open questions](./DESIGN.md#open-questions).
6
+
7
+ ## What it is for
8
+
9
+ The first consumer is [5chan](https://github.com/bitsocialnet/5chan), a serverless, adminless imageboard on the Bitsocial protocol. 5chan has a [competitive directory system](https://github.com/bitsocialnet/5chan/blob/master/README.md#competitive-directory-system): many communities compete for each directory slot (for example, multiple "Business & Finance" communities), but only the highest-voted one appears on the homepage. Today those assignments are curated by hand through pull requests to [`5chan-directories.json`](https://github.com/bitsocialnet/lists/blob/master/5chan-directories.json). This library is the planned replacement: directory voting that is decided by holders rather than by maintainers, with no server to trust.
10
+
11
+ The same engine generalizes to the original use case in [pkc-js issue #25](https://github.com/pkcprotocol/pkc-js/issues/25) (a default-communities list voted on over pubsub) and to any future Bitsocial client that needs holder-weighted, censorship-resistant curation.
12
+
13
+ ## Why a separate library (not in pkc-js)
14
+
15
+ [pkc-js](https://github.com/pkcprotocol/pkc-js) (Public Key Communities) is the protocol layer: communities, publications, the challenge exchange. Voting is application/governance layer. Keeping it separate means:
16
+
17
+ - Chain-RPC and governance churn stay out of pkc-js core. pkc-js deliberately touches chains only for name resolution; it has no balance lookups, no chainTicker-to-RPC mapping, and no off-chain vote signing or verification. This library owns all of that.
18
+ - The engine is reusable across clients and contests.
19
+ - The core (`schema/`, `verify/`, `crdt/`, `tally/`) is transport-agnostic and unit-testable without a network. libp2p only appears in `transport/`.
20
+
21
+ This library does not start its own node. It consumes the host's running Helia node directly — no adapter — and drives that node's gossipsub service and blockstore itself. The node must carry a pubsub service at `libp2p.services.pubsub` (a plain Helia node does not — register e.g. `@chainsafe/libp2p-gossipsub`), a usable `blockstore`, and a libp2p fetch service at `libp2p.services.fetch` (register `@libp2p/fetch` — the checkpoint root-record pull rides it); construction throws `MissingPubsubError` / `MissingBlockstoreError` / `MissingFetchError` otherwise. With pkc-js today that node is reached at `pkc.clients.libp2pJsClients[key]._helia`; a version-stable accessor on pkc-js is a planned follow-up (see [DESIGN.md, Deferred pkc-js work](./DESIGN.md#deferred-pkc-js-work)).
22
+
23
+ ## Design at a glance
24
+
25
+ - **Settings live in the topic.** `topic = "bitsocial-votes/" + CID(dag-cbor(criteria))`. Two peers on the same topic provably ran identical rules, so the network validates itself with no intermediary.
26
+ - **Votes are a state-based grow-only CRDT.** A signed `Votes` bundle is a standalone dag-cbor block (no parent links); each wallet gossips its own bundle **inline as a live delta**, validated straight from the message bytes — no fetch toward the publisher. State is a last-write-wins set keyed by wallet, so aggregation is a monotonic union: a peer can omit a vote but can never subtract one that an honest peer serves. Cold start and gap-fill exchange a tiny **root record** (libp2p-fetch pull + a slow topic heartbeat) and pull the checkpoint blocks behind it via directed bitswap from its advertisers.
27
+ - **The gate and weight are data, not code.** A fixed rule registry (mirroring pkc-js's challenge registry) maps a `type` string to a verifier. v1 ships exactly the NFT path — an `erc721-min-balance` gate `rule` (5chan Pass) and `constant` weight (1 pass = 1 vote). Balance-derived (token-weighted) voting is deferred; see [ROADMAP.md](./ROADMAP.md).
28
+
29
+ See [DESIGN.md](./DESIGN.md) for the full rationale, including how this resists vote-dropping and how criteria upgrades fork cleanly.
30
+
31
+ ## Usage
32
+
33
+ The library never starts a node and never takes a host SDK (there is no `pkc` argument). A host passes its own running Helia node in directly and injects its seams into a single `PubsubVoter`:
34
+
35
+ | Seam | Type | Required | Purpose |
36
+ |---|---|---|---|
37
+ | `helia` | `HeliaInstance` | yes | the host's running Helia node; must carry a gossipsub service at `libp2p.services.pubsub` (else `MissingPubsubError`) and a `blockstore` (else `MissingBlockstoreError`) |
38
+ | `chains` | `ChainClientFactory` | yes | builds a viem `PublicClient` per chain; rules read through it for the gate and weight |
39
+ | `signer` | `VoteSigner` | no | the voting wallet's address + EIP-712 ballot signing; omit for a read-only voter |
40
+ | `nameResolvers` | `NameResolver[]` | no | community-name resolvers (same interface and instances as pkc-js's `nameResolvers`, e.g. `@bitsocial/bso-resolver` for `name.bso`); each vote's `community.name` claim is verified through them — inline at the forward-gate for live votes, in the background verifier for cold-join admits — and a bundle whose name resolves to a different `publicKey` than claimed is dropped/evicted |
41
+ | `dataPath` | `string \| false` | no | directory for the voter's persistent caches (gate results + name resolutions), the pkc-js `dataPath` equivalent. Node default: `{cwd}/.bitsocial-pubsub-voting` (better-sqlite3 under `{dataPath}/lru-storage/`); in the browser the path is ignored and the caches live in IndexedDB. Pass `false` for in-memory-only (the pkc-js `noData` equivalent). A restart re-serves settled gate reads and fresh name resolutions from the store instead of the RPC |
42
+ | `httpRouterUrls` | `string[]` | no | Delegated Routing V1 router base URLs to **announce provider records to** (one unsigned `PUT /routing/v1/providers` per router; `Keys` batches every joined contest's criteria CID + current checkpoint root + chunk CIDs — hourly, debounced on root changes, and on address changes). **Seeders only**: absent/empty means never announce (the default — plain clients are not dialable), and the browser build never announces regardless. The node must be publicly dialable, with its dialable addresses in `libp2p` (listen/announce/AutoTLS): private, loopback, and link-local addrs are filtered client-side, and an announce with no surviving address is skipped. *Querying* needs no URLs here — cold-join discovery uses the injected node's `libp2p.contentRouting`, which the host wires its routers into |
43
+
44
+ A contest is addressed by its **full criteria document**, passed to `createContest` / `createContestVote`. The document is strictly validated there (`CriteriaSchema` + the rule registry), and its canonical bytes derive the topic — so the exact document every participant shares is the only contest configuration that exists.
45
+
46
+ ### Construct a voter
47
+
48
+ ```ts
49
+ import { PubsubVoter } from "@bitsocial/pubsub-voting";
50
+
51
+ const voter = new PubsubVoter({
52
+ helia, // the host's Helia node; needs a gossipsub service at libp2p.services.pubsub + a blockstore
53
+ chains: viemChainFactory(), // ({ chain, config }) => viem PublicClient
54
+ signer: mySigner, // optional; omit → read-only voter
55
+ nameResolvers: [bsoResolver], // optional; verifies community-name claims (e.g. @bitsocial/bso-resolver)
56
+ dataPath: "/path/to/data", // optional; persistent-cache directory (default {cwd}/.bitsocial-pubsub-voting; false → in-memory)
57
+ httpRouterUrls: [ // optional, SEEDERS ONLY (publicly dialable node): announce provider
58
+ "https://routing.example" // records (criteria CID + checkpoint root + chunks) so cold joiners
59
+ ] // can discover this node via the routers; clients omit this
60
+ });
61
+ ```
62
+
63
+ Construction throws `MissingPubsubError`, `MissingBlockstoreError`, or `MissingFetchError` if the node lacks a usable pubsub service, blockstore, or libp2p fetch service — the library fails fast rather than letting a later `publish`/`subscribe`/`fetch` fail obscurely. ("Bitswap" is not a separately checkable property — it is a block broker wired beneath `blockstore` — so the validated guarantee is a well-formed blockstore, the surface bitswap retrieves through. The fetch service carries the checkpoint root-record pull; the library registers its own responder on it.)
64
+
65
+ ### Read a tally reactively (no signer needed)
66
+
67
+ `createContest` mints a per-contest read object; `update()` starts syncing and it emits `update` (carrying a fresh `tally`) and `error`, just like a plebbit-js `subplebbit`:
68
+
69
+ ```ts
70
+ const contest = await voter.createContest({ criteria }); // criteria: the contest's full document (strictly validated here)
71
+ contest.on("update", () => render(contest.tally)); // tally rides the object; recomputed before each emit
72
+ contest.on("error", (err) => showConnectivityWarning(err)); // tally chain read failed, or the background verifier's RPC/resolver is down (retrying)
73
+ await contest.update(); // join the topic, cold-start, begin emitting
74
+ // const fresh = await contest.getTally(); // or force a fresh read, bypassing the cache
75
+ // await contest.stop(); // leave the topic
76
+ ```
77
+
78
+ Each ranking row carries one flag **per deferred verification operation** (mirroring pkc-js's
79
+ `nameResolved`), and every background settlement re-fires `update` — so a leaderboard can render
80
+ provisional rows immediately and refine them in place:
81
+
82
+ ```ts
83
+ contest.on("update", () => {
84
+ for (const row of contest.tally?.ranking ?? []) {
85
+ // row.community: { name?: string, publicKey: string } — identity is ALWAYS publicKey.
86
+ // Show the name only once it has been checked against the registry.
87
+ const label = row.community.name && row.nameResolved ? row.community.name : row.community.publicKey;
88
+ // row.chainVerified: true once EVERY contributing vote's on-chain gate read confirmed.
89
+ // false means "still being read in the background", never "failed" — a vote that fails
90
+ // a deferred check is evicted and the row recounted instead.
91
+ renderRow(label, row.weight, row.chainVerified ? "verified" : "verifying…");
92
+ }
93
+ });
94
+ ```
95
+
96
+ A cold join **renders fast and refines**: checkpoint bundles are admitted after the synchronous offline checks (signature + constraints), so the first tally arrives with `chainVerified: false` rows, and the background verifier then batches the deferred gate reads (one multicall per bucket) and name resolutions — each settlement re-fires `update` with the flags flipped. See [DESIGN.md, Background chain verification](./DESIGN.md#background-chain-verification).
97
+
98
+ Repeated `createContest` calls with byte-identical criteria return the same `Contest` (engines are keyed by topic, the criteria CID).
99
+
100
+ ### Publish or withdraw a vote (needs a signer)
101
+
102
+ `createContestVote` mints a publishable ballot; `publish()` signs and broadcasts it once and emits `publishingstatechange`, like a plebbit-js publication:
103
+
104
+ ```ts
105
+ const vote = await voter.createContestVote({ criteria, votes: [{ community: { publicKey: "12D3KooW..." }, vote: 1 }] });
106
+ vote.on("publishingstatechange", (state) => console.log(state)); // stopped → signing → publishing → succeeded (or failed)
107
+ const { bundle, recipientCount } = await vote.publish(); // the signed VotesBundle + how many peers gossipsub sent it directly to
108
+
109
+ // Withdraw (active): publish an empty ballot; it supersedes the prior vote under LWW.
110
+ await (await voter.createContestVote({ criteria, votes: [] })).publish();
111
+ ```
112
+
113
+ A community's identity is its `publicKey`. The optional `name` is the community's resolvable domain (e.g. `memes.bso`) — unique per community, never a free label: the schema requires a TLD, the name is resolved through the injected `nameResolvers` (inline at the forward-gate for live votes, in the background verifier for cold-join admits), and any bundle whose name resolves to a different `publicKey` than claimed is dropped/evicted. Bundles must also name pairwise-distinct `community.publicKey`s. See [DESIGN.md, Votes wire](./DESIGN.md#votes-wire).
114
+
115
+ `recipientCount` is the peer-reach hint gossipsub reports: how many peers it sent the vote *directly* to at publish time (first-hop fan-out, filtered for send failures) — **not** total network reach, and **not** an acceptance confirmation, since each recipient still runs the forward-gate before re-forwarding. Treat it as a coarse "did this reach anyone?" signal. Note that gossipsub *rejects* the publish with `NoPeersSubscribedToTopic` when it would reach zero peers (common right after joining, before the mesh grafts), unless the host enables `allowPublishToZeroTopicPeers` — so a resolved `recipientCount === 0` only occurs under that host setting; otherwise a no-reach publish surfaces as a thrown error (and a `failed` state).
116
+
117
+ `publish()` on a voter built without a `signer` throws `ReadOnlyError` (and emits an `error`).
118
+
119
+ ### Republishing is the client's job
120
+
121
+ A vote is not permanent: a bundle is valid only for `voteExpiryBuckets` after its `blockNumber`, so a live vote must be re-published before it decays. **This library does not do that automatically** — it publishes each vote once and the consuming client decides when (or whether) to refresh. To refresh, just `createContestVote(...).publish()` again; a new bundle at the current bucket supersedes the old one. To stop, simply stop refreshing and let the vote lapse. The library gives you what you need to schedule it — all pure, no chain reads:
122
+
123
+ ```ts
124
+ import { republishIntervalBuckets } from "@bitsocial/pubsub-voting";
125
+
126
+ const cadence = republishIntervalBuckets(criteria); // ceil(voteExpiryBuckets / 2) — the recommended cadence, in buckets
127
+ // A vote sampled at bucket b (bundle.blockNumber / criteria.blocksPerBucket) expires once the
128
+ // current bucket exceeds b + criteria.voteExpiryBuckets; refresh before then.
129
+ ```
130
+
131
+ See [DESIGN.md, Republishing is the client's job](./DESIGN.md#republishing-is-the-clients-job-not-this-librarys) for why an always-on re-signer was deliberately kept out of a library that runs on the host's shared node.
132
+
133
+ ### Many contests (a 5chan-style directory)
134
+
135
+ One criteria document is one contest (one topic). A directory is conveniently authored as a single manifest of shared `defaults` plus one entry per slot — as in [5chan-directory-criteria.jsonc](./5chan-directory-criteria.jsonc) and [examples/5chan.ts](./examples/5chan.ts) — and `deriveDirectoryCriteria` derives the finished documents (`{ ...defaults, ...entry }`, shallow — an override replaces that whole field) and validates each one. What participants must share **byte-identically** is the derived documents (the topic is their CID), which is why every consumer of the same directory should derive through this one helper rather than re-implement the merge. The manifest is JSONC by convention; strip comments before parsing:
136
+
137
+ ```ts
138
+ import { deriveDirectoryCriteria } from "@bitsocial/pubsub-voting";
139
+ import stripJsonComments from "strip-json-comments";
140
+
141
+ const manifest = JSON.parse(stripJsonComments(manifestJsonc)) as unknown;
142
+ const allCriteria = deriveDirectoryCriteria(manifest); // → Criteria[], throws on invalid entries or duplicate contestIds
143
+
144
+ const contests = await Promise.all(allCriteria.map((criteria) => voter.createContest({ criteria }))); // → Contest[]
145
+ for (const contest of contests) await contest.update(); // a full host joins + serves the whole directory
146
+ ```
147
+
148
+ There is no separate seeder API: a node that joins a topic (via `update()` or `publish()`) automatically serves that contest's checkpoint root record over libp2p-fetch — the responder registers itself on the first joined topic and unregisters when the last is left. A seeder is just a client that joins everything.
149
+
150
+ ### Lifecycle (`stop` / `destroy`)
151
+
152
+ `stop()` leaves every joined topic but keeps the voter **reusable** — each `Contest` can `update()` again and you can `createContest` afterward. `destroy()` is **terminal** (like pkc-js): it leaves every topic, unregisters the fetch responder, and marks the voter and its contests dead — any later `createContest`/`createContestVote`, or a pre-existing `Contest.update()`/`ContestVote.publish()`, throws `VoterDestroyedError`. Construct a new `PubsubVoter` to participate again. (There is no store to dispose — republishing is the client's concern.)
153
+
154
+ ```ts
155
+ const voter = new PubsubVoter({ helia, chains, signer });
156
+ // … create + update contests, app runs …
157
+ await voter.destroy(); // terminal: leave all topics, unregister the responder, forbid reuse
158
+ ```
159
+
160
+ ### Pure helpers (no node, no network)
161
+
162
+ ```ts
163
+ import { topicFor, deriveDirectoryCriteria } from "@bitsocial/pubsub-voting";
164
+
165
+ const topic = await topicFor(criteria); // "bitsocial-votes/" + CID(dag-cbor(criteria))
166
+ const allCriteria = deriveDirectoryCriteria(json); // directory manifest → validated Criteria[] (see above)
167
+ ```
168
+
169
+ Full, type-checked call patterns for a pkc-js host, a plebbit/seedit host, and a read-only consumer are in [examples/](./examples/).
170
+
171
+ ### Custom rules
172
+
173
+ The gate and weight are a single flat registry of rules, one `type` per file, mirroring the pkc-js challenge registry. Each rule owns its option schema and is evaluated at the bundle's bucket block. Chain-reading rules get `ctx.chain` — the viem `PublicClient` for their `options.chain` — and write their own reads (`readContract`, `getBalance`, ...), pinning each call to the sampled block with `blockNumber: BigInt(ctx.blockNumber)`. There is **one kind**: `evaluate → { score: bigint }`, a non-negative score where `0n` means "does not qualify" (a result object, not a bare `bigint`, so slot-specific fields can be added later). The criteria has two *slots* drawing from the one registry — the **rule** slot treats the score as a gate (`> 0n` admits), the **weight** slot as the vote's magnitude. A wallet's vote counts as `rule.score > 0n ? weight.score : 0n`. A rule that needs a threshold returns `0n` below it (so `erc721-min-balance`'s optional `min` gates), which lets the same rule serve either slot.
174
+
175
+ Built-ins: `erc721-min-balance` (v1) and `constant` (v1). A host adds or shadows rules by `type` via the `rules` option — this is how clients like 5chan or seedit register custom rules without forking the library:
176
+
177
+ ```ts
178
+ import { PubsubVoter, type Rule } from "@bitsocial/pubsub-voting";
179
+ import { z } from "zod";
180
+
181
+ const seeditModAllowlist: Rule<{ type: "seedit-mod-allowlist"; allow: string[] }> = {
182
+ type: "seedit-mod-allowlist",
183
+ optionsSchema: z.object({ type: z.literal("seedit-mod-allowlist"), allow: z.array(z.string()) }),
184
+ async evaluate({ options, walletAddress }) {
185
+ return { score: options.allow.includes(walletAddress) ? 1n : 0n }; // gate: 1n admits, 0n rejects
186
+ }
187
+ };
188
+
189
+ const voter = new PubsubVoter({
190
+ helia, chains,
191
+ rules: { "seedit-mod-allowlist": seeditModAllowlist } // flat map; shadows/extends built-ins by `type`
192
+ });
193
+ ```
194
+
195
+ A custom `type` becomes part of `dag-cbor(criteria)`, so it is provably pinned to the topic it runs on, and a client that does not implement a `type` named in `criteria.requires.rules` throws `UnknownRuleError` and recuses itself rather than miscounting.
196
+
197
+ ### Weighted voting (deferred)
198
+
199
+ v1 ships `constant` weight (one Pass, one vote) **on purpose** — it resists whale dominance and downvote weaponization. Balance-derived, token-weighted voting (Pass gate + BSO weight via `erc20-balance`) is a designed-but-unshipped capability: the rule path and result shape leave room for it with no engine change, but it is not in the v1 built-ins and carries open governance/abuse and lazy-tally questions. See [ROADMAP.md](./ROADMAP.md) and [DESIGN.md, Future improvements](./DESIGN.md#future-improvements).
200
+
201
+ ## Layout
202
+
203
+ ```
204
+ src/
205
+ schema/ zod schemas (criteria, votes, shared wire primitives) + inferred types
206
+ encoding/ canonical dag-cbor encoding [implemented]
207
+ topic.ts topic = "bitsocial-votes/" + CID(dag-cbor) [implemented]
208
+ signer/ VoteSigner seam + EIP-712 ballot typed data [implemented]
209
+ client/ reactive facade: PubsubVoter + Contest (createContest) + ContestVote (createContestVote) [implemented]
210
+ errors.ts ReadOnly/MissingPubsub/MissingBlockstore/MissingFetch/... [implemented]
211
+ rules/ one file per `type` + registry/resolver [implemented]
212
+ chain/ ChainClient = viem PublicClient + bucket math [implemented]
213
+ verify/ signature + constraints + full BundleVerifier + verdict cache [implemented]
214
+ crdt/ state-based LWW winner-set: union, binary bundle codec, in-memory store [implemented]
215
+ checkpoint/ deterministic checkpoint codec (root manifest + size-capped chunks) [implemented]
216
+ transport/ async validate-before-forward gossip gate + message codec (inline bundle / root record) + root chase + transport [implemented]
217
+ tally/ deterministic aggregation over pre-validated bundles [implemented]
218
+ index.ts public entry: re-exports + facade + design types
219
+ ```
220
+
221
+ ## License
222
+
223
+ GPL-3.0-or-later, matching 5chan.
@@ -0,0 +1,13 @@
1
+ import type { BucketMath } from "./types.js";
2
+ /**
3
+ * Bucket math for one criteria's `blocksPerBucket`.
4
+ *
5
+ * bucketForBlock(block) = Math.floor(block / blocksPerBucket)
6
+ * sampleBlockForBucket(bucket) = bucket * blocksPerBucket (the bucket boundary block)
7
+ *
8
+ * Every verifier prices balances at one sample block per bucket so votes cannot
9
+ * flip-flop mid-bucket and every client agrees. v1 uses the bucket boundary (the head
10
+ * rounded down to `blocksPerBucket`); the boundary lags the head by up to a full bucket,
11
+ * which also places it past any realistic reorg depth (see DESIGN.md "Tally", "CRDT").
12
+ */
13
+ export declare function makeBucketMath(blocksPerBucket: number): BucketMath;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Bucket math for one criteria's `blocksPerBucket`.
3
+ *
4
+ * bucketForBlock(block) = Math.floor(block / blocksPerBucket)
5
+ * sampleBlockForBucket(bucket) = bucket * blocksPerBucket (the bucket boundary block)
6
+ *
7
+ * Every verifier prices balances at one sample block per bucket so votes cannot
8
+ * flip-flop mid-bucket and every client agrees. v1 uses the bucket boundary (the head
9
+ * rounded down to `blocksPerBucket`); the boundary lags the head by up to a full bucket,
10
+ * which also places it past any realistic reorg depth (see DESIGN.md "Tally", "CRDT").
11
+ */
12
+ export function makeBucketMath(blocksPerBucket) {
13
+ if (!Number.isInteger(blocksPerBucket) || blocksPerBucket <= 0) {
14
+ throw new RangeError(`blocksPerBucket must be a positive integer, got ${blocksPerBucket}`);
15
+ }
16
+ return {
17
+ bucketForBlock(blockNumber) {
18
+ return Math.floor(blockNumber / blocksPerBucket);
19
+ },
20
+ sampleBlockForBucket(bucket) {
21
+ return bucket * blocksPerBucket;
22
+ }
23
+ };
24
+ }
@@ -0,0 +1,56 @@
1
+ import type { ChainClient, ChainClientFactory } from "./types.js";
2
+ /**
3
+ * Chain-read coalescing — a DataLoader for pinned-block contract reads.
4
+ *
5
+ * Rules read the chain through the full viem surface (`readContract`, `multicall`, ...), and
6
+ * verification runs in parallel: a directory join verifies dozens of contests at once, the
7
+ * gossip forward-gate verifies each incoming vote individually, and the background verifier
8
+ * batches per bucket. Left alone, that parallelism turns into a burst of concurrent HTTP posts
9
+ * that free public RPC endpoints throttle (measured against `mainnet.base.org`: 38 concurrent
10
+ * `aggregate3` posts → 33× HTTP 429 `-32016 over rate limit`). Per-call politeness inside one
11
+ * rule invocation cannot fix this — the burst forms ACROSS calls — so the voter wraps each
12
+ * chain client ONCE ({@link coalescingChainFactory}) and every consumer shares the wrapper:
13
+ *
14
+ * - `readContract` calls pinned to an explicit `blockNumber` are collected for a short
15
+ * window ({@link COALESCE_WINDOW_MS} — noise next to a WAN RTT), deduped on
16
+ * `(block, contract, calldata)`, grouped per block (an `eth_call` reads ONE block, so
17
+ * different bucket sample blocks can never share a multicall), and flushed as multicall3
18
+ * `aggregate3` chunks of {@link CHAIN_READS_PER_MULTICALL} reads.
19
+ * - Explicit pinned-block `multicall` calls (e.g. a rule's own `evaluateMany` batching) are
20
+ * DECOMPOSED into that same pool, so parallel contests' per-contest batches merge into
21
+ * shared round trips too (measured: without this, a 10-board directory join fired 10
22
+ * separate small multicalls plus head reads and the sustained stream still tripped the
23
+ * endpoint's rate limit). Unpinned/exotic multicalls pass through under the same budget.
24
+ * - At most {@link CHAIN_MULTICALL_CONCURRENCY} round trips are in flight per underlying
25
+ * client, across everything; a failed coalesced chunk retries once
26
+ * ({@link CHAIN_CHUNK_RETRY_DELAY_MS}) without re-reading completed chunks.
27
+ *
28
+ * Caveat (shared with any multicall batching): a coalesced read executes as an inner CALL from
29
+ * the multicall3 contract, so `msg.sender` differs from a direct `eth_call`. That is irrelevant
30
+ * for `balanceOf`-style views — and reads that must not batch keep their semantics by omitting
31
+ * `blockNumber` or passing extra call options, which routes them through the raw client.
32
+ * Clients without a known multicall3 deployment are returned unwrapped.
33
+ */
34
+ /** `balanceOf`-sized reads per multicall3 `aggregate3` round trip (~45 KB calldata, ~2–5M gas). */
35
+ export declare const CHAIN_READS_PER_MULTICALL = 200;
36
+ /** Multicall round trips in flight at once per chain client — polite to free public endpoints. */
37
+ export declare const CHAIN_MULTICALL_CONCURRENCY = 2;
38
+ /** One retry per failed coalesced chunk, after this pause. */
39
+ export declare const CHAIN_CHUNK_RETRY_DELAY_MS = 500;
40
+ export interface CoalescerOptions {
41
+ readsPerCall?: number;
42
+ concurrency?: number;
43
+ windowMs?: number;
44
+ }
45
+ /**
46
+ * Wrap one chain client with the shared read coalescer + in-flight budget. Idempotent per
47
+ * client only via {@link coalescingChainFactory} — call sites should not wrap twice.
48
+ */
49
+ export declare function coalescingChainClient(client: ChainClient, options?: CoalescerOptions): ChainClient;
50
+ /**
51
+ * Wrap a host's `ChainClientFactory` so every client it hands out is coalesced, memoized on the
52
+ * UNDERLYING client instance: a host factory that returns one shared client per chain (the
53
+ * normal shape — and what makes cross-contest coalescing possible at all) gets exactly one
54
+ * coalescer per chain, shared by every contest, the gossip gate, and the background verifier.
55
+ */
56
+ export declare function coalescingChainFactory(factory: ChainClientFactory, options?: CoalescerOptions): ChainClientFactory;
@@ -0,0 +1,217 @@
1
+ import { encodeFunctionData } from "viem";
2
+ /**
3
+ * Chain-read coalescing — a DataLoader for pinned-block contract reads.
4
+ *
5
+ * Rules read the chain through the full viem surface (`readContract`, `multicall`, ...), and
6
+ * verification runs in parallel: a directory join verifies dozens of contests at once, the
7
+ * gossip forward-gate verifies each incoming vote individually, and the background verifier
8
+ * batches per bucket. Left alone, that parallelism turns into a burst of concurrent HTTP posts
9
+ * that free public RPC endpoints throttle (measured against `mainnet.base.org`: 38 concurrent
10
+ * `aggregate3` posts → 33× HTTP 429 `-32016 over rate limit`). Per-call politeness inside one
11
+ * rule invocation cannot fix this — the burst forms ACROSS calls — so the voter wraps each
12
+ * chain client ONCE ({@link coalescingChainFactory}) and every consumer shares the wrapper:
13
+ *
14
+ * - `readContract` calls pinned to an explicit `blockNumber` are collected for a short
15
+ * window ({@link COALESCE_WINDOW_MS} — noise next to a WAN RTT), deduped on
16
+ * `(block, contract, calldata)`, grouped per block (an `eth_call` reads ONE block, so
17
+ * different bucket sample blocks can never share a multicall), and flushed as multicall3
18
+ * `aggregate3` chunks of {@link CHAIN_READS_PER_MULTICALL} reads.
19
+ * - Explicit pinned-block `multicall` calls (e.g. a rule's own `evaluateMany` batching) are
20
+ * DECOMPOSED into that same pool, so parallel contests' per-contest batches merge into
21
+ * shared round trips too (measured: without this, a 10-board directory join fired 10
22
+ * separate small multicalls plus head reads and the sustained stream still tripped the
23
+ * endpoint's rate limit). Unpinned/exotic multicalls pass through under the same budget.
24
+ * - At most {@link CHAIN_MULTICALL_CONCURRENCY} round trips are in flight per underlying
25
+ * client, across everything; a failed coalesced chunk retries once
26
+ * ({@link CHAIN_CHUNK_RETRY_DELAY_MS}) without re-reading completed chunks.
27
+ *
28
+ * Caveat (shared with any multicall batching): a coalesced read executes as an inner CALL from
29
+ * the multicall3 contract, so `msg.sender` differs from a direct `eth_call`. That is irrelevant
30
+ * for `balanceOf`-style views — and reads that must not batch keep their semantics by omitting
31
+ * `blockNumber` or passing extra call options, which routes them through the raw client.
32
+ * Clients without a known multicall3 deployment are returned unwrapped.
33
+ */
34
+ /** `balanceOf`-sized reads per multicall3 `aggregate3` round trip (~45 KB calldata, ~2–5M gas). */
35
+ export const CHAIN_READS_PER_MULTICALL = 200;
36
+ /** Multicall round trips in flight at once per chain client — polite to free public endpoints. */
37
+ export const CHAIN_MULTICALL_CONCURRENCY = 2;
38
+ /** One retry per failed coalesced chunk, after this pause. */
39
+ export const CHAIN_CHUNK_RETRY_DELAY_MS = 500;
40
+ /** How long the first read of a batch waits for company before its chunk flushes. */
41
+ const COALESCE_WINDOW_MS = 25;
42
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
43
+ /**
44
+ * Wrap one chain client with the shared read coalescer + in-flight budget. Idempotent per
45
+ * client only via {@link coalescingChainFactory} — call sites should not wrap twice.
46
+ */
47
+ export function coalescingChainClient(client, options = {}) {
48
+ // Without a known multicall3 deployment there is nothing to coalesce INTO — pass through.
49
+ if (typeof client.multicall !== "function" || !client.chain?.contracts?.multicall3)
50
+ return client;
51
+ const readsPerCall = options.readsPerCall ?? CHAIN_READS_PER_MULTICALL;
52
+ const concurrency = options.concurrency ?? CHAIN_MULTICALL_CONCURRENCY;
53
+ const windowMs = options.windowMs ?? COALESCE_WINDOW_MS;
54
+ // --- the shared in-flight budget (coalesced chunks AND explicit multicalls) ---
55
+ let active = 0;
56
+ const queue = [];
57
+ const acquire = () => new Promise((resolve) => {
58
+ const attempt = () => {
59
+ if (active < concurrency) {
60
+ active++;
61
+ resolve();
62
+ }
63
+ else {
64
+ queue.push(attempt);
65
+ }
66
+ };
67
+ attempt();
68
+ });
69
+ const release = () => {
70
+ active--;
71
+ queue.shift()?.();
72
+ };
73
+ // --- pending pinned reads, grouped per block; deduped until their read settles ---
74
+ const groups = new Map();
75
+ const inFlight = new Map();
76
+ const runChunk = async (reads, blockNumber) => {
77
+ await acquire();
78
+ try {
79
+ const call = () => client.multicall({
80
+ contracts: reads.map((read) => read.contract),
81
+ allowFailure: true,
82
+ batchSize: 0,
83
+ blockNumber
84
+ });
85
+ let results;
86
+ try {
87
+ results = await call();
88
+ }
89
+ catch {
90
+ await delay(CHAIN_CHUNK_RETRY_DELAY_MS);
91
+ results = await call();
92
+ }
93
+ for (let i = 0; i < reads.length; i++) {
94
+ const outcome = results[i];
95
+ if (outcome?.status === "success")
96
+ reads[i].resolve(outcome.result);
97
+ else
98
+ reads[i].reject(outcome?.error ?? new Error("multicall returned no result for this read"));
99
+ }
100
+ }
101
+ catch (err) {
102
+ for (const read of reads)
103
+ read.reject(err);
104
+ }
105
+ finally {
106
+ release();
107
+ for (const read of reads)
108
+ inFlight.delete(read.key);
109
+ }
110
+ };
111
+ const flushGroup = (blockKey) => {
112
+ const group = groups.get(blockKey);
113
+ if (!group)
114
+ return;
115
+ clearTimeout(group.timer);
116
+ groups.delete(blockKey);
117
+ for (let at = 0; at < group.reads.length; at += readsPerCall) {
118
+ void runChunk(group.reads.slice(at, at + readsPerCall), group.blockNumber);
119
+ }
120
+ };
121
+ const rawReadContract = client.readContract.bind(client);
122
+ /** Add one pinned read to its block's pending group (deduped); returns its shared promise. */
123
+ const enqueueRead = (contract, blockNumber) => {
124
+ let calldata;
125
+ try {
126
+ calldata = encodeFunctionData({ abi: contract.abi, functionName: contract.functionName, args: contract.args });
127
+ }
128
+ catch {
129
+ // Un-encodable entry (exotic abi shape) — read it directly, keeping pinned semantics.
130
+ return rawReadContract({ ...contract, blockNumber });
131
+ }
132
+ const key = `${blockNumber}:${contract.address.toLowerCase()}:${calldata}`;
133
+ const existing = inFlight.get(key);
134
+ if (existing)
135
+ return existing.promise;
136
+ let resolve;
137
+ let reject;
138
+ const promise = new Promise((res, rej) => {
139
+ resolve = res;
140
+ reject = rej;
141
+ });
142
+ const read = {
143
+ contract: { address: contract.address, abi: contract.abi, functionName: contract.functionName, args: contract.args ?? [] },
144
+ key,
145
+ promise,
146
+ resolve,
147
+ reject
148
+ };
149
+ inFlight.set(key, read);
150
+ const blockKey = blockNumber.toString();
151
+ let group = groups.get(blockKey);
152
+ if (!group) {
153
+ group = { blockNumber, reads: [], timer: setTimeout(() => flushGroup(blockKey), windowMs) };
154
+ groups.set(blockKey, group);
155
+ }
156
+ group.reads.push(read);
157
+ if (group.reads.length >= readsPerCall)
158
+ flushGroup(blockKey);
159
+ return promise;
160
+ };
161
+ const readContract = (async (params) => {
162
+ const { address, abi, functionName, args, blockNumber, ...rest } = params;
163
+ // Coalesce only the plain pinned-block read shape; anything else (head reads, blockTag,
164
+ // account/state overrides, ...) keeps direct-call semantics through the raw client.
165
+ if (typeof blockNumber !== "bigint" || Object.keys(rest).length > 0 || !address || !abi || !functionName) {
166
+ return rawReadContract(params);
167
+ }
168
+ return enqueueRead({ address, abi, functionName, args }, blockNumber);
169
+ });
170
+ const rawMulticall = client.multicall.bind(client);
171
+ const multicall = (async (params) => {
172
+ // A pinned multicall DECOMPOSES into the shared pool: parallel contests' per-contest
173
+ // batches (each rule's evaluateMany) merge into the same aggregate3 round trips as
174
+ // coalesced single reads, and duplicate reads (one wallet voting on many boards at one
175
+ // sample block) collapse. `batchSize` is dropped on decomposition (the pool re-chunks at
176
+ // `readsPerCall` anyway); any OTHER extra option (`stateOverride`, `multicallAddress`,
177
+ // `deployless`, ...) changes viem's execution semantics, so — like unpinned calls —
178
+ // those shapes pass through raw under the budget.
179
+ const { contracts, allowFailure = true, batchSize: _batchSize, blockNumber, ...rest } = params;
180
+ if (typeof blockNumber !== "bigint" || !Array.isArray(contracts) || Object.keys(rest).length > 0) {
181
+ await acquire();
182
+ try {
183
+ return await rawMulticall(params);
184
+ }
185
+ finally {
186
+ release();
187
+ }
188
+ }
189
+ const settled = await Promise.allSettled(contracts.map((contract) => enqueueRead(contract, blockNumber)));
190
+ if (!allowFailure) {
191
+ const failed = settled.find((s) => s.status === "rejected");
192
+ if (failed)
193
+ throw failed.reason;
194
+ return settled.map((s) => s.value);
195
+ }
196
+ return settled.map((s) => s.status === "fulfilled" ? { status: "success", result: s.value } : { status: "failure", error: s.reason, result: undefined });
197
+ });
198
+ return { ...client, readContract, multicall };
199
+ }
200
+ /**
201
+ * Wrap a host's `ChainClientFactory` so every client it hands out is coalesced, memoized on the
202
+ * UNDERLYING client instance: a host factory that returns one shared client per chain (the
203
+ * normal shape — and what makes cross-contest coalescing possible at all) gets exactly one
204
+ * coalescer per chain, shared by every contest, the gossip gate, and the background verifier.
205
+ */
206
+ export function coalescingChainFactory(factory, options) {
207
+ const wrapped = new WeakMap();
208
+ return (args) => {
209
+ const client = factory(args);
210
+ let coalesced = wrapped.get(client);
211
+ if (!coalesced) {
212
+ coalesced = coalescingChainClient(client, options);
213
+ wrapped.set(client, coalesced);
214
+ }
215
+ return coalesced;
216
+ };
217
+ }
@@ -0,0 +1,15 @@
1
+ import type { Criteria, RuleRef } from "../schema/criteria.js";
2
+ /**
3
+ * Resolve which chain a rule reads. A rule's parsed options may name a
4
+ * `chain` ticker (e.g. `erc721-min-balance` -> "base"); a chainless rule (e.g.
5
+ * `constant`) names none, so callers fall back to the first configured chain. Shared by the
6
+ * verifier, the tally, and the facade so the fallback rule stays identical everywhere.
7
+ */
8
+ /** The `chain` ticker named in a rule's parsed options, or `undefined` if none. */
9
+ export declare function chainTickerOf(options: unknown): string | undefined;
10
+ /**
11
+ * The chain ticker a rule ref uses: its own `chain` option, else the first chain in
12
+ * `requires.chains`. Throws if neither exists (a chainless rule with no configured
13
+ * chains cannot be read).
14
+ */
15
+ export declare function tickerForRef(criteria: Criteria, ref: RuleRef, options: unknown): string;
@@ -0,0 +1,25 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Resolve which chain a rule reads. A rule's parsed options may name a
4
+ * `chain` ticker (e.g. `erc721-min-balance` -> "base"); a chainless rule (e.g.
5
+ * `constant`) names none, so callers fall back to the first configured chain. Shared by the
6
+ * verifier, the tally, and the facade so the fallback rule stays identical everywhere.
7
+ */
8
+ /** The `chain` ticker named in a rule's parsed options, or `undefined` if none. */
9
+ export function chainTickerOf(options) {
10
+ const parsed = z.object({ chain: z.string().min(1) }).safeParse(options);
11
+ return parsed.success ? parsed.data.chain : undefined;
12
+ }
13
+ /**
14
+ * The chain ticker a rule ref uses: its own `chain` option, else the first chain in
15
+ * `requires.chains`. Throws if neither exists (a chainless rule with no configured
16
+ * chains cannot be read).
17
+ */
18
+ export function tickerForRef(criteria, ref, options) {
19
+ const ticker = chainTickerOf(options) ?? Object.keys(criteria.requires.chains)[0];
20
+ if (!ticker) {
21
+ throw new Error(`criteria rule "${ref.type}" names no chain and requires.chains is empty; ` +
22
+ `cannot resolve a chain client to read it`);
23
+ }
24
+ return ticker;
25
+ }