ZkSniper contract reference
Source: contracts/src/games/ZkSniper.sol, interfaces/IZkSniper.sol,
interfaces/IHonkVerifier.sol · License: MIT · Ownable2Step, Pausable, transient
ReentrancyGuard (OpenZeppelin v5.4) · Solidity 0.8.26.
The contract is not deployed on any network and has had no external audit. This page documents the source in the repository; when the page and the source disagree, the source wins. For the rules in plain language, read How ZK-Sniper works.
Purpose
One contract holds every round. Money is native BNB. A round is a hider's collateral plus the
fees of the snipers' shots. The contract never custodies anything else: the pool of each live
round plus deferred payout credits is tracked in totalEscrowed, which equals the contract's
balance (there is no receive or fallback; BNB force-sent by selfdestruct or as a block
reward is unaccounted and unrecoverable).
The proof system lives in a separate, immutable verifier contract the game calls through
IHonkVerifier.verify(bytes proof, bytes32[] publicInputs). It is the zero-knowledge flavour of
UltraHonk, deployed together with a linked library. See the circuit reference. The
constructor requires the verifier address to hold code.
Time is counted in blocks. BSC blocks come about every 0.45 s (the repository's measurement, since the Fermi hard fork), so 267 blocks is about 2 minutes and 100 blocks about 45 seconds.
State machine
The round has three statuses. Pending shots are not a round status any more: any number of squares can be pending while the round is Open.
Each square has its own small state inside an Open round:
A cleared square still counts as guessed and cannot be shot again.
| Status | Meaning |
|---|---|
None | The id was never created (getRound reverts RoundNotFound for ids not yet issued) |
Open | Accepting shots; any number may be pending, each with its own sniper and deadline |
Ended | Settled; terminal. The outcome says how |
| Outcome | Set when |
|---|---|
None | The round has not ended |
Hit | answerShot verified a hit proof |
Timeout | claimTimeout settled an unanswered shot |
Escaped | claimEscape paid the hider |
Round ids start at 0 and count up: round i exists for i < nextRoundId.
Round and pending shots
struct Round {
address hider;
uint96 baseFee;
uint256 positionHash; // Poseidon(x, y, salt), a BN254 field element
uint256 pool; // live pool; 0 once ended
uint256 collateral; // the hider's deposit (the opening pool)
uint64 guessedBitmap; // bit y * 8 + x set once the square was fired at
uint64 pendingBitmap; // bit set while that square awaits an answer
uint64 extractionEndBlock; // set once by initiateExtraction; 0 = never
uint32 answerWindowBlocks; // snapshot taken at createRound
uint32 extractionWindowBlocks; // snapshot taken at createRound
uint8 shotsTaken; // incremented when a shot is FIRED
uint8 pendingCount; // popcount of pendingBitmap
RoundStatus status;
Outcome outcome;
}
struct PendingShot { // one per (roundId, square), square = y * 8 + x
address sniper;
uint64 deadlineBlock;
}
answerWindowBlocksandextractionWindowBlocksare copied from the owner's settings when the round is created. The owner's setters only affect rounds created afterwards.pendingBitmapandpendingCountread 0 once the round is Ended: a hit or a timeout voids every other pending shot.- The
Roundstruct has nowinnerfield. The winner is in theRoundHit/RoundTimedOutevent, andgetShotkeeps the winning square's record (pending == false). - Records of squares that did not win are deleted. A proven miss deletes its square's record,
and settlement by a hit or a timeout deletes the record of every other pending (voided) square
with a bounded loop over
pendingBitmap(at most 63 deletions, measured at about 114k gas warm for 62 deletions in one test transaction; cold-slot cost on chain is an estimate of about 310k). After a round ends,getShotreturns a non-zerosniperfor the winning square only; every other square reads(address(0), 0, false). A client that needs to know who won should read theRoundHit/RoundTimedOutevent, not scangetShot.
Functions
Round lifecycle
| Function | Caller | Needs | Effect |
|---|---|---|---|
createRound(uint256 positionHash, uint96 baseFee) payable returns (uint256 roundId) | an approved hider, or anyone while openCreation is true | not paused; openCreation or approvedHider[msg.sender] (else HiderNotApproved(msg.sender)); positionHash below the BN254 scalar field; hash never used; minBaseFee <= baseFee <= maxBaseFee; msg.value >= baseFee * 64 | The whole msg.value becomes collateral and the opening pool. Marks the hash used for ever. Copies the current answer and extraction windows into the round. Emits RoundCreated. The creation gate is read here and nowhere else |
fireShot(uint256 roundId, uint8 x, uint8 y) payable | anyone except the hider's address | not paused; status Open; on-grid; square unshot; not after extractionEndBlock; msg.value >= shotCost | Charges exactly shotCost. Marks the square in guessedBitmap and pendingBitmap, shotsTaken++, pendingCount++, pool += cost, records PendingShot{sniper, block.number + round.answerWindowBlocks}. Refunds msg.value - cost to the caller (deferred credit if the push fails). Emits ShotFired |
answerShot(uint256 roundId, uint8 x, uint8 y, bool isHit, bytes proof) | anyone (the proof authorizes) | status Open; square pending; block.number <= that square's deadline; the verifier accepts the proof for publicInputsFor(roundId, x, y, isHit) | Any verifier revert or false becomes InvalidProof. Miss: that square's pending state is cleared, pendingCount--, round stays Open (ShotMissed). Hit: round ends, pool to that square's sniper less rake, other pending shots void (RoundHit). Works while paused |
claimTimeout(uint256 roundId, uint8 x, uint8 y) | anyone | status Open; square pending; block.number > that square's deadline | Round ends as Timeout; pool to that square's sniper less rake; other pending shots void (RoundTimedOut). Works during an extraction and while paused |
initiateExtraction(uint256 roundId) | hider | status Open; never initiated | extractionEndBlock = block.number + round.extractionWindowBlocks. Allowed with shots pending and while paused. Emits ExtractionInitiated |
claimEscape(uint256 roundId) | hider | status Open; extraction initiated; block.number > extractionEndBlock; pendingCount == 0 | Round ends as Escaped; pays pool - rake, with rake = (pool - collateral) * 1000 / 10_000 (RoundEscaped). Works while paused |
sponsorRound(uint256 roundId) payable | anyone | not paused; status Open; msg.value > 0 | pool += msg.value. Emits RoundSponsored |
withdraw() | any account with a credit | credit > 0 | Sends the caller's deferred credit to the caller |
withdrawTo(address to) | any account with a credit | credit > 0; to != 0 | Same, to to (for a receiver that cannot accept the transfer itself) |
Every function that moves funds or round state (createRound, fireShot, answerShot,
claimTimeout, initiateExtraction, claimEscape, sponsorRound, withdraw, withdrawTo) is
nonReentrant. The owner functions and the two-step ownership transfer are intentionally not
guarded: they move no funds, and a payout receiver only gets 50,000 gas, so it cannot act as the
owner. Settlement does all accounting (status, outcome,
pool to zero, totalEscrowed, pending state) before any external call (checks, effects,
interactions).
Check order
The first failing check decides the error:
createRound: not paused (EnforcedPause), then the creation gate (HiderNotApproved), then the commitment, base-fee and collateral checks.answerShot: round exists (RoundNotFound), statusOpen(InvalidStatus), on-grid (OutOfGrid), square pending (NoPendingShot), before the deadline (AnswerWindowClosed), then the verifier (InvalidProof).claimTimeout: round exists,Open, on-grid, pending, then deadline passed (AnswerWindowOpen).claimEscape: hider (NotHider),Open, extraction started (ExtractionNotInitiated), countdown over (ExtractionNotOver), then nothing pending (ShotPending).
Timing rules at a glance
| Moment | Allowed | Not allowed |
|---|---|---|
Up to and including a square's deadlineBlock | answerShot for that square | claimTimeout for it |
After a square's deadlineBlock | claimTimeout for it | answerShot for it (AnswerWindowClosed) |
Up to and including extractionEndBlock | fireShot | claimEscape (ExtractionNotOver) |
After extractionEndBlock | claimEscape (if nothing is pending) | fireShot (ExtractionWindowClosed) |
Several expired shots
Because any expired square can be claimed and the first claim ends the round, the first
claimTimeout caller chooses which expired sniper is paid when more than one shot is past its
deadline. The contract does not rank them. A timeout on one square also voids shots on other
squares that are still inside their answer window; since all shots in a round share the same
window length, the shot fired earliest expires first. See
Security model for what that means when the
hider controls a second address.
Pricing
function shotCost(uint256 roundId) external view returns (uint256) {
remaining = 64 - shotsTaken;
if (remaining == 0) revert NoSquaresRemaining();
if (remaining <= 2) return pool / 2; // final duel
return (uint256(baseFee) * 64) / remaining; // floor
}
The pool figure used in the duel is the current pool: collateral, earlier shot fees and any
sponsorships. shotsTaken counts fired shots, so every pending shot already raises the price of
the next one. A miss proof for the hider's own square cannot exist, so the shot that lands on it
ends in a hit or a timeout. The 64th shot is therefore a certain hit only when all 63 other
squares were answered misses; while other shots are pending, the hider's square may be among
them.
msg.value may exceed the quote: only shotCost is kept and the rest is refunded. A pad
protects against a price rise smaller than the pad, such as a small concurrent pool change. It
does not protect against a large one: a big sponsorRound, or another shot that takes remaining
from 3 to 2 (the price jumps to half the pool), can raise the price by more than any pad, and the
shot then reverts with InsufficientFee and charges nothing.
Settlement and payouts
| Outcome | Rake | Winner receives | Treasury receives |
|---|---|---|---|
| Hit or Timeout | pool * 1000 / 10_000 (the whole pool, which includes every fee still in it) | pool - rake to the sniper of the winning square | rake |
| Escaped | (pool - collateral) * 1000 / 10_000 | pool - rake to the hider | rake |
All payments, including the refund of an overpaid shot, go through one internal push: a call with a
50,000 gas allowance. A receiver that reverts, runs out of that gas or cannot accept BNB is
credited in pendingWithdrawals instead (PayoutDeferred), so a hostile winner or treasury can
never block settlement. The push is attempted only if at least MIN_GAS_BEFORE_PUSH (90,000) gas
remains; otherwise the call reverts with InsufficientGas, so a caller cannot starve a receiver
into a deferral. Resubmit with more gas. totalEscrowed stays exact through every refund,
payout and deferral.
Views
| Function | Returns |
|---|---|
getRound(roundId) | The full Round (reverts RoundNotFound) |
getShot(roundId, x, y) | (address sniper, uint64 deadlineBlock, bool pending) for the square. Non-zero sniper only while the shot is pending, and, after a round ends, for the winning square alone: misses and voided squares read (address(0), 0, false). Reverts RoundNotFound / OutOfGrid |
shotCost(roundId) | Exact fee for the next shot |
remainingSquares(roundId) | 64 - shotsTaken |
isGuessed(roundId, x, y) | Whether the square was fired at (reverts OutOfGrid) |
canClaimTimeout(roundId, x, y) | Whether claimTimeout for that square would succeed now. false for an unknown round or off-grid square |
canClaimEscape(roundId) | Whether claimEscape would pass its round checks now: Open, extraction started, countdown over, nothing pending (the caller must also be the hider) |
publicInputsFor(roundId, x, y, isHit) | bytes32[4] [positionHash, x, y, isHit] for that pending square (reverts NoPendingShot unless it is pending) |
nextRoundId() | The id the next round will get; also the number of rounds created |
positionHashUsed(hash) | Whether a commitment was already used |
pendingWithdrawals(account) | Deferred credit |
totalEscrowed() | Live pools plus deferred credits |
treasury(), minBaseFee(), maxBaseFee(), verifier() | Configuration |
openCreation(), approvedHider(address) | The creation gate: whether anyone may call createRound, and whether a given address may when the gate is closed |
answerWindowBlocks(), extractionWindowBlocks() | The windows copied into rounds created from now on (a round's own values are in getRound) |
paused(), owner(), pendingOwner() | Pause and ownership state |
Events
| Event | Arguments (indexed marked) |
|---|---|
RoundCreated | roundId, hider, positionHash, baseFee, collateral |
ShotFired | roundId, sniper, x, y, fee (the exact cost charged, not msg.value), answerDeadlineBlock |
ShotMissed | roundId, sniper, x, y |
RoundHit | roundId, sniper, x, y, payout, rake |
RoundTimedOut | roundId, sniper, x, y, payout, rake |
ExtractionInitiated | roundId*, extractionEndBlock |
RoundEscaped | roundId, hider, payout, rake |
RoundSponsored | roundId, sponsor, amount, pool (the new total) |
PayoutDeferred | account*, amount (also emitted when a fireShot refund is deferred) |
Withdrawn | account, to, amount |
TreasurySet | treasury* |
BaseFeeBoundsSet | minBaseFee, maxBaseFee |
OpenCreationSet | open (also emitted once by the constructor) |
ApprovedHiderSet | hider*, approved |
AnswerWindowBlocksSet | blocks_ |
ExtractionWindowBlocksSet | blocks_ |
There is no refund event: an overpayment refund is a plain transfer, visible as a difference
between msg.value and fee, or as PayoutDeferred if it was deferred. payout and rake in the
settlement events are the amounts owed; a payout that failed to push is also reported in
PayoutDeferred and credited for withdraw. OwnershipTransferStarted, OwnershipTransferred,
Paused and Unpaused are inherited.
Errors
All errors are custom errors. A verifier that reverts (with its own error, or by running out of
the gas it was given) or returns false is reported as InvalidProof. A verifier that succeeds
but returns malformed data (not exactly one ABI bool) fails the return-data decode outside the
try/catch and reverts with empty data instead. The real bb-generated verifier never does this,
and the deploy script checks the committed fixture proofs against the deployed verifier.
| Error | Raised when |
|---|---|
ZeroAddress() | A required address is zero (or the game itself, for the treasury); also setApprovedHider(address(0), ...) |
VerifierNotContract(verifier) | The constructor's verifier address has no code |
RoundNotFound(roundId) | The id was never issued |
NotHider() | initiateExtraction / claimEscape by someone other than the hider |
HiderCannotShoot() | The hider's own address calls fireShot |
HiderNotApproved(hider) | createRound while openCreation is false and hider is not an approvedHider |
InvalidPositionHash() | positionHash is not below the BN254 scalar field |
PositionHashUsed(positionHash) | A round with this commitment already exists |
BaseFeeOutOfBounds(baseFee, min, max) | baseFee is outside the configured bounds |
InsufficientCollateral(sent, required) | msg.value < baseFee * 64 |
InvalidStatus(status) | The round's status does not allow the call |
OutOfGrid(x, y) | A coordinate is 8 or more |
AlreadyGuessed(x, y) | The square was already fired at |
InsufficientFee(sent, required) | msg.value is below the shot cost (replaces the old WrongFee; overpayment is refunded) |
ExtractionWindowClosed() | fireShot after extractionEndBlock |
NoPendingShot(x, y) | answerShot, claimTimeout or publicInputsFor on a square with no pending shot (never fired, already answered, or voided) |
AnswerWindowClosed() | answerShot after the square's deadline |
AnswerWindowOpen() | claimTimeout before the square's deadline has passed |
InvalidProof() | The verifier returned false or reverted, for any reason |
NoSquaresRemaining() | shotCost when all 64 squares were fired at |
ExtractionAlreadyInitiated() | A second initiateExtraction |
ExtractionNotInitiated() | claimEscape with no extraction started |
ExtractionNotOver() | claimEscape before the countdown ended |
ShotPending() | claimEscape while at least one shot awaits its answer |
ZeroAmount() | sponsorRound with no value |
NothingToWithdraw() | withdraw with no credit |
NativeTransferFailed() | The withdraw transfer failed (the credit stays in place because the call reverts) |
InsufficientGas() | Not enough gas left to give a payout receiver its full allowance |
WindowOutOfBounds(blocks, min, max) | A window setter or constructor value is outside its range |
InvalidBaseFeeBounds() | The base-fee bounds are inconsistent (zero minimum, or minimum above maximum) |
RenounceDisabled() | renounceOwnership is always disabled |
Pausable adds EnforcedPause / ExpectedPause, Ownable2Step the usual
OwnableUnauthorizedAccount / OwnableInvalidOwner, and the reentrancy guard
ReentrancyGuardReentrantCall.
Constants
| Constant | Value | Meaning |
|---|---|---|
GRID | 8 | Board edge |
SQUARES | 64 | Squares |
RAKE_BPS | 1000 | 10%. A compile-time constant: there is no setter |
BPS | 10_000 | Basis-point denominator |
SNARK_SCALAR_FIELD | 21888242871839275222246405745257275088548364400416034343698204186575808495617 | BN254 scalar field; commitments must be below it |
MIN_ANSWER_WINDOW_BLOCKS / DEFAULT_ANSWER_WINDOW_BLOCKS / MAX_ANSWER_WINDOW_BLOCKS | 67 / 267 / 28_800 | Answer window bounds and the recommended default (about 30 seconds, 2 minutes and 3.6 hours at 0.45 s per block). Earlier drafts used 1,800 / 3,600 (about 13.5 and 27 minutes) because a hider was expected to prove each shot by hand; answers are now automatic and normally land in seconds, so the window is only a failure backstop. WindowOutOfBounds(blocks, min, max) reports the bounds |
MIN_EXTRACTION_WINDOW_BLOCKS / DEFAULT_EXTRACTION_WINDOW_BLOCKS / MAX_EXTRACTION_WINDOW_BLOCKS | 20 / 100 / 28_800 | Extraction window bounds and the recommended default (about 9 seconds, 45 seconds and 3.6 hours) |
PAYOUT_GAS | 50_000 | Gas allowance of a push payout |
MIN_GAS_BEFORE_PUSH | 90_000 | Gas that must remain before a push is attempted |
The DEFAULT_* values are advisory constants for the deploy scripts; the constructor still takes
explicit window arguments. The old MIN_WINDOW_BLOCKS / MAX_WINDOW_BLOCKS no longer exist.
Configuration
Set at construction (and by the owner setters below):
constructor(
address initialOwner,
IHonkVerifier verifier_, // immutable; must hold code
address treasury_,
uint96 minBaseFee_,
uint96 maxBaseFee_,
uint32 answerWindow, // blocks, 67 to 28,800
uint32 extractionWindow, // blocks, 20 to 28,800
bool openCreation_ // true: anyone may create rounds; false: approved hiders only
)
The deploy scripts default to a base-fee range of 0.0001 to 1 BNB (so collateral between
0.0064 and 64 BNB), an answer window of 267 blocks (about 2 minutes) and an extraction window of 100 blocks,
all overridable in the optional games.zkSniper block of contracts/config/<chainId>.json. The
treasury defaults to the team fee recipient of the zk-pad deployment. Two keys control the creation
gate: games.zkSniper.openCreation (default true on chains 31337 and 97; required, no default,
on every other chain, 56 included) and games.zkSniper.approvedHiders (a list of addresses, applied with
setApprovedHider by the deployer before the ownership hand-over). See
House rounds. After deployment ownership
is offered to roles.owner (two-step: the new owner must accept). The verifier is deployed with a
linked library through one shared helper, ZkSniperVerifierLinker; see the
circuit reference. See
deployment.
Admin powers
The owner (a single address with a two-step transfer) can do exactly this:
| Can | Takes effect for | Notes |
|---|---|---|
setTreasury(address) | The rake of every settlement after the call | Non-zero, not the game itself. This is a real power: it redirects future rake, including rake of rounds that are already running |
setBaseFeeBounds(min, max) | New rounds only | min > 0, min <= max |
setOpenCreation(bool) | createRound calls after the call | Opens creation to everyone, or closes it to approved hiders only. Entry-only: no running round is affected. Works while paused. Emits OpenCreationSet |
setApprovedHider(address, bool) | createRound calls after the call | Adds or removes one address from the creation allowlist. Entry-only. Reverts ZeroAddress for the zero address. Works while paused. Emits ApprovedHiderSet |
setAnswerWindowBlocks(blocks) | Rounds created after the call | Between 67 and 28,800. Existing rounds keep their snapshot. A window near the 67-block minimum (about 30 seconds) leaves an answerer very little room to fail over, so a hider should read answerWindowBlocks in getRound |
setExtractionWindowBlocks(blocks) | Rounds created after the call | Between 20 and 28,800. Existing rounds keep their snapshot |
pause() / unpause() | Entries | See below |
transferOwnership / acceptOwnership | Two-step transfer. renounceOwnership always reverts with RenounceDisabled |
What pause stops: createRound, fireShot and sponsorRound. Nothing else.
What the creation gate stops: createRound by an address that is not approved while
openCreation is false. Nothing else: it is never read by any other function.
What pause never stops: initiateExtraction, claimEscape, answerShot, claimTimeout,
withdraw and withdrawTo. A hider can therefore always start and finish an exit, and a pending
shot, a running countdown or a deferred credit can always be settled and paid out, even if the
owner never unpauses. One consequence: a paused game takes no new shots, so snipers cannot fire
during the pause, but rounds already in flight run to their end.
Admin-trust assumption: pause during an extraction. Extraction countdowns and answer deadlines
are fixed block numbers that keep running while the game is paused, and fireShot is the only
function that lets a sniper act during a countdown. An owner (or a timelock) that pauses right
after a hider calls initiateExtraction therefore removes the snipers' last-chance shots, and the
hider escapes without facing them. The owner cannot take funds this way, and a pause is also
ordinary incident response, so the chain cannot tell the two apart. The contract does not extend a
countdown for the pause; this is documented, not mitigated. The owner is expected to be a multisig
behind a timelock, which today it is not (see
trust assumptions).
What the owner can NOT do:
- Move, freeze or redirect any pool, collateral, sponsorship or deferred credit. There is no admin withdrawal, sweep or rescue function.
- Change the verifier. It is
immutable. A new circuit means a new verifier and a new game contract. - Change the rake rate, the grid size, the pricing formula or the deferred-payout rules (all constants or code).
- Settle a round, declare a hit, or answer a shot.
- Upgrade the contract. There is no proxy.
- Change the windows of a round that already exists, or shorten or lengthen a running clock.
- Renounce ownership.
The rest of zk-pad's admin picture, including that the other contracts are owned by a single account today, is on Trust assumptions and admin powers.
Reading a round from the SDK
@zk-pad/sdk exports the ABI (zkSniperAbi, honkVerifierAbi), the pure math that mirrors the
contract (sniperShotCost, sniperRake, sniperHitPayout, sniperEscapePayout,
sniperPricingMatrix, sniperSquareIndex and friends) and call helpers for the per-square
functions. Use them to quote a shot instead of re-deriving the formula, and to send answers with a
gas limit:
SNIPER_ANSWER_GAS_LIMIT(3.5M gas) is the limit everyanswerShotis simulated and sent with. A valid answer needs about 2.35M for the verifier, while a tampered proof can burn everything it is given.encodeSniperAnswerShot,encodeSniperClaimTimeout,sniperAnswerShotRequestandsimulateSniperAnswerbuild the(roundId, x, y, ...)calls;readSniperPendingShotsreads the pending squares of a round.
import { sniperPricingMatrix } from '@zk-pad/sdk';
const rows = sniperPricingMatrix(10n ** 16n); // base fee 0.01 BNB, fresh round
rows[0].cost; // 10000000000000000n (0.01 BNB)
rows[62].duel; // true