services
Get a key

library / Blockchain ideas / BI0035

Blockhash raffle draw

A raffle where the winners come from the hash of a mainnet block that did not exist when entries closed. You announce a slot, wait for it to finalize, and anyone can rerun the draw. Runnable main.ts included.

By Carbium · Games · BI0035 · updated 2026-11-22

01

Who uses it

A giveaway, a community prize draw, a hackathon door prize and a game that picks a loot winner each round share one problem: whoever runs the draw can be accused of picking the result. A random call on your own server proves nothing to the entrants. A block hash gives everyone the same input, and neither the organizer nor any entrant could choose it when the entry list closed. Only the leader of that slot sees the hash before everyone else, which is one more reason to keep the prize small.

The method fits a small prize where entrants should be able to check the result themselves. A team can run the file with no arguments to draw from five sample names, which shows the whole loop before an entrant list exists.

02

How the draw works

Fix the entry list and publish it. Announce a target slot that is still in the future, for example 25 slots ahead, which is about 5 seconds at 200 ms a slot. Once that slot has finalized, take its block hash and rank the entries.

Ranking is one hash per entry. The file computes sha256("<raffleId>|<blockhash>|<entry>") for every entry, with no spaces around the pipes, sorts the hex digests ascending, and the first N are the winners. Index arithmetic and modulo never enter, so the order of the entry list changes nothing and no entry gets an edge. A third party reruns the formula with the published list and the block hash and lands on the same winners.

The target slot can come back with no block, because its leader never produced one. The rule is the first produced block at or after the target, and the file applies it: when the read says the slot was skipped, it moves to the next slot. Say this rule when you announce the draw, so a skipped slot cannot turn into an argument.

$The read names finalized because a block read at confirmed can still lose its fork, and a draw taken from it could name different winners when someone checks later. Solana commitment levels covers the three levels.
03

The build

  • Publish the entries, the raffle id, the number of winners and the skipped-slot rule. The file takes entries as arguments, as in node main.ts <ENTRY> <ENTRY>, and reads RAFFLE_ID and WINNERS from the environment. WINNERS must be a positive whole number or the run exits with a message.
  • Pick the target. With TARGET_SLOT set, the file uses it. Otherwise it reads getSlot at finalized and adds LEAD_SLOTS (25 unless set, also a positive whole number). The target is printed so you can publish it.
  • Poll getSlot once a second until the finalized slot reaches the target.
  • Read getBlock for the target slot at finalized with transactionDetails: "none" and rewards off, so the answer carries the block hash and little else. The call also sets maxSupportedTransactionVersion: 1: mainnet carries v1 transactions, and a block read that leaves the value out can answer -32015.
  • If the slot was skipped, move to the next slot. On any other error, print it and retry the same slot, because moving on would change the winner. Ten failures end the run.
  • Rank the entries by their hash and print the winners next to the slot and the block hash.
  • A verifier reruns the same file with the published TARGET_SLOT, RAFFLE_ID and entries, and gets the same winners.

For a demo the file runs the whole sequence in one go. In production, split it: publish the entries and the target slot, then run the draw with TARGET_SLOT set to it after the slot has finalized. An entry that arrives once the target block exists is void, since its author could have seen the hash.

main.ts
// BI0035 · Blockhash raffle draw// https://carbium.sh/library/blockchainideas/blockhash-raffle-draw// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createDefaultRpcTransport, createSolanaRpcFromTransport, isSolanaError, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED } from "@solana/kit";import { createHash } from "node:crypto";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const entries = process.argv.length > 2 ? process.argv.slice(2) : ["ada", "ben", "chi", "dev", "eli"];const raffleId = process.env.RAFFLE_ID ?? "raffle-1";const wanted = Number(process.env.WINNERS ?? 1);if (!Number.isInteger(wanted) || wanted < 1) {  console.error("Set WINNERS to a positive whole number.");  process.exit(1);}const winners = Math.min(wanted, entries.length);const leadSlots = Number(process.env.LEAD_SLOTS ?? 25); // about 5 s at 200 ms a slotif (!Number.isInteger(leadSlots) || leadSlots < 1) {  console.error("Set LEAD_SLOTS to a positive whole number.");  process.exit(1);}const fixedTarget = process.env.TARGET_SLOT; // the published slot, for the production split and a verifier's rerunif (fixedTarget !== undefined && !/^\d+$/.test(fixedTarget)) {  console.error("Set TARGET_SLOT to a whole slot number.");  process.exit(1);}const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));const why = (e: unknown) => (e instanceof Error ? e.message : String(e));// finalized by name: a draw must survive a dropped fork.const finalizedSlot = () => rpc.getSlot({ commitment: "finalized" }).send();// First produced block at or after the target slot.async function blockHashFrom(start: bigint): Promise<{ slot: bigint; hash: string }> {  let slot = start;  let failures = 0;  while (failures < 10) {    try {      while ((await finalizedSlot()) < slot) await sleep(1000);      const block = await rpc        .getBlock(slot, { commitment: "finalized", transactionDetails: "none", rewards: false, maxSupportedTransactionVersion: 1 })        .send();      if (block) return { slot, hash: block.blockhash };      console.log(`slot ${slot} has no block, next`);      slot++;    } catch (e) {      if (isSolanaError(e, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED)) {        console.log(`slot ${slot} was skipped, next`);        slot++;      } else {        failures++; // never move on: a different slot would change the winner        console.error(`read failed (${failures}/10), retrying slot ${slot}: ${why(e)}`);        await sleep(1000);      }    }  }  throw new Error("too many failed reads");}try {  const target = fixedTarget !== undefined ? BigInt(fixedTarget) : (await finalizedSlot()) + BigInt(leadSlots);  console.log(`raffle ${raffleId}: ${entries.length} entries, ${winners} winner(s), target slot ${target}`);  const { slot, hash } = await blockHashFrom(target);  const ranked = entries    .map((entry) => ({ entry, score: createHash("sha256").update(`${raffleId}|${hash}|${entry}`).digest("hex") }))    .sort((a, b) => (a.score < b.score ? -1 : 1));  console.log(`drawn from slot ${slot} blockhash ${hash}`);  ranked.forEach((r, i) => console.log(`${i < winners ? "WIN " : "    "} ${i + 1} ${r.score.slice(0, 12)} ${r.entry}`));} catch (e) {  console.error("draw failed:", why(e));  process.exit(1);}

run: CARBIUM_KEY=<YOUR_KEY> WINNERS=2 node main.ts ada ben chi dev eli

LEAD_SLOTS sets how far ahead the target sits, so a live audience gets a longer countdown.

04

What it costs

A draw is a handful of calls. getSlot is a cheap cached read at 1 cell, and the file polls it once a second, so a 25 slot lead means about five polls, one read to set the target and one getBlock. That is roughly eight calls in all.

PlanCreditsgetSlot ceiling
Free ($0)500K once, at sign-up5 req/s
Dev ($20)10M per month30 req/s
Business ($250)50M per month100 req/s
Pro ($500)200M per month500 req/s

A one-per-second poll sits well under every ceiling, Free included. Limits are per account, so a raffle running next to other tools on the same keys draws on one shared budget.

$A raffle page that many visitors reload should not call the RPC from each browser. Run the draw once on your server and publish the result and the block hash as static text.
05

What to add next

  • Entries as transactions: have each entrant send a small transfer to a raffle address, then list them with getSignaturesForAddress. Every listed signature carries its slot, so the cutoff is checkable: an entry at or above the target slot is out. That call costs 50 cells, and its pages come from an address index that keeps up to 30 days.
  • A verify page: a static page where anyone pastes the entry list, the raffle id and the block hash and sees the same ranking computed in their browser.
  • Several prizes: raise WINNERS. Ranks 1 to N from one hash give N distinct winners with no second draw.
  • Rounds in a game: derive a target slot per round from the tick and draw the loot winner from that block. Live chain-state game shows how to take a turn clock from slots.
06

Where it ends

  • A block hash is no verifiable random function. The leader of the target slot builds that block, so it can try many orderings of its contents and keep the one whose hash suits it, at almost no cost. It can also withhold the block and push the draw to the next slot. Use the method for small prizes only, and give a larger prize a method with a commitment from the entrants.
  • Nothing enforces the cutoff. The entry list and the target slot hold only as far as your published timeline does, so publish both before the target block exists.
  • The file reads the chain and computes. No program holds the prize, and nothing here signs or sends. Paying the winners is your job.
  • Publish the block hash next to the result. A rerun with TARGET_SLOT works only while the RPC still holds that block in its ledger, so later checks rank from the published hash on the verify page.
07

When it goes wrong

what goes wrongwhat to do
The run ends at once with draw failed and a 401, and no target line prints.The first getSlot call was refused at the door. Check CARBIUM_KEY and attach the whole key: an unknown key gets 401.
The target line prints and then nothing more, and the run never ends.The finalized slot is not moving, so the wait for the target never finishes. Compare the printed target with getSlot at finalized and check the endpoint in CARBIUM_RPC_URL.
The poll gets a 429.The file prints the error and tries again after a second. Lengthen the sleep if it repeats, and check what else on the account shares the budget.
The run ends at once with a message about LEAD_SLOTS or TARGET_SLOT.Set LEAD_SLOTS to a positive whole number, and TARGET_SLOT to the whole slot number you published. The file checks both before it makes any call.
Two runs of the same raffle name different winners.Compare the printed slot and block hash first. If they match, an entry differs by spelling or case, or the raffle id changed. If the slot differs, each run chose its own target: set TARGET_SLOT to the published slot in both.
A late entrant claims a win.Check the entry's slot against the target. An entry in a block at or after the target slot arrived after the hash could be seen and is void.
08

Questions

Why rank by hash instead of taking the hash modulo the entry count?

A modulo depends on the order of the list and carries a small bias. A per-entry hash ranks every entry from the same block hash with no dependence on order, and a verifier needs one line to check it.

Why finalized and not confirmed?

A confirmed block can still lose its fork, and the draw would then name different winners on a later check. The wait for finalized is short.

How far ahead should the target slot be?

Far enough that entries can close before the block exists. A lead of 25 slots is about 5 seconds, which suits a live countdown. For an open entry window, pick a target hours out, publish it, and run the draw with TARGET_SLOT set to it.

Does it run on the Free plan?

Yes. One poll a second is under Free's 5 req/s cheap-read ceiling, and the rest of the run is one read to set the target and one block read.