ZELRA

Documentation

Build with ZELRA

Issue credentials, make proofs in the browser, and let a contract act on a condition it never sees the inputs of.

Overview

ZELRA lets a holder prove that a value an issuer attested about them is at least a threshold, that the credential has not expired, and that it belongs to a set the application trusts, without revealing the value, the credential or who they are. The proof is Groth16 on BN254: about 0.5 s to make in a browser, 256 bytes, about 240k gas to verify.

Holder derives a key→Issuer writes a leaf and an encrypted memo→Holder proves in the browser→Your contract calls consume or attest

Three ways in, depending on who you are:

An issuer

Open a set, compute leaves from ZELRA IDs, encrypt memos, call issue or issueMany. See Issuing.

A consumer contract

Pick the set you trust, choose a threshold and a context, call Zelra.consume or attest. See Consuming.

A client

Rebuild the set's tree from events, compute the inputs, run snarkjs, send the proof. See Proving.

Concepts

TermMeaning
SetAn append-only Poseidon Merkle tree of depth 20 (1,048,576 leaves) owned by one issuer. It has a name, a schema (what the value means) and a unit.
CredentialA leaf Poseidon(idc, value, expiry, salt) plus a memo that tells the holder what it contains. The salt is random per credential, so nobody can guess a leaf from a ZELRA ID.
Identity commitmentidc = Poseidon(secret). Never appears on the chain in the clear.
ConsumerAny contract that calls Zelra. Its address, with a context, defines a scope.
Scopekeccak256(abi.encode(chainId, consumer, context)) mod p. Nullifiers live in a scope, so they also differ from chain to chain.
NullifierPoseidon(secret, scope). The same holder leaves the same tag in the same scope and unrelated tags in different scopes.
SignalA public value bound into the proof: the caller or a recipient. The consumer decides what it means.
provedAtThe chain time the proof speaks for. Contracts accept it for one hour, and the circuit requires the credential to outlive that whole hour.
ThresholdThe bar, below 264. Chosen by the consumer; the circuit proves value ≥ threshold.

Identity and credentials

Keys

Everything a holder needs is derived from one EIP-712 signature, bound to the chain, that the wallet shows for what it is. The wallet must sign deterministically (RFC 6979; MetaMask, Rabby and hardware wallets do). Smart-contract wallets are not supported yet.

// p = BN254 scalar field, n = secp256k1 order
domain  = { name: "ZELRA", version: "1", chainId }
type    = Identity(string purpose, string warning)
message = { purpose: "Derive my ZELRA identity key",
            warning: "This signature IS your ZELRA key. Sign it only on zelra.network. …" }
sig     = signTypedData(domain, type, message)
rs      = canonical r ‖ s of sig (low s, 64 bytes)   // same key whatever encoding the wallet returns
secret  = keccak256(rs) mod p                       // never leaves the browser
idc     = Poseidon(secret)                          // identity commitment
encPriv = keccak256(rs ‖ "zelra/enc") mod n           // secp256k1 key for memos
encPub  = compressed public key of encPriv (33 bytes)

Because the chain id is in the domain, one wallet has one identity per chain. Anyone who obtains the signature holds the key, which is why the message says so in the wallet's own prompt.

ZELRA ID

What a holder gives an issuer. 69 bytes in base64url (alphabet A-Z a-z 0-9 - _, no padding) behind the prefix zelra1:.

bytes 0..31idc, big-endian
bytes 32..64encPub, compressed secp256k1 point
bytes 65..68first 4 bytes of keccak256(idc ‖ encPub)

Memo format

The credential, encrypted to the holder, stored in the Issued event next to the leaf. Ephemeral ECDH on secp256k1, AES-256-GCM over a fixed 60-byte plaintext, so the length of a memo says nothing about the value. Version 2, 122 bytes in all.

memo  = 0x02 ‖ ephPub(33) ‖ iv(12) ‖ AES-256-GCM(plain)(60) ‖ tag(16)
key   = keccak256(ECDH_x(ephPriv, encPub) ‖ "zelra/memo/v2")      // ECDH_x: the 32-byte x coordinate
plain = value(8) ‖ expiry(8) ‖ setId(4) ‖ issuedAt(8) ‖ salt(32)        // big-endian unsigned integers

A holder keeps a memo only if it decrypts and Poseidon(idc, value, expiry, salt) equals the leaf it was issued with, so whatever the app shows is provable. value is below 264; expiry and issuedAt are Unix seconds; salt is a field element.

Issuing credentials

  1. Open a set once: createSet(name, schema, unit), for example ("Private collateral · USD", "collateral_usd", "USD"). The caller becomes the issuer. Consumers will reference the returned setId.
  2. Receive the holder's ZELRA ID, decode it, verify the checksum, take idc and encPub.
  3. Choose a value and an expiry, and draw a fresh random salt (31 random bytes, so always below the field). The expiry is the only way to withdraw an attestation later: sets are append-only. Collateral attestations should be short-lived and re-issued. A credential that expires within the hour cannot be proven at all.
  4. Compute the leaf Poseidon(idc, value, expiry, salt) (four inputs, circomlib Poseidon, as in poseidon-lite) and seal the memo as above. Never reuse a salt.
  5. Call issue(setId, leaf, memo), or issueMany(setId, leaves[], memos[]) for up to 64 at once. One issue is about 500k gas (20 Poseidon hashes on-chain); a batch costs about 2k + 20 hashes for k leaves.
// issuer side, viem + poseidon-lite
import { poseidon4 } from 'poseidon-lite';
const { idc, encPub } = decodeId(holderZelraId);
const expiry = issuedAt + 90 * 86400;                          // 90 days
const salt = BigInt(bytesToHex(crypto.getRandomValues(new Uint8Array(31))));
const leaf = poseidon4([idc, value, BigInt(expiry), salt]);
const memo = await sealMemo(encPub, { value, expiry, setId, issuedAt, salt });
await zelra.write.issue([setId, leaf, memo]);

Rotate the issuer key in two steps: proposeIssuer(setId, newKey), then acceptIssuer(setId) from the new key. Proposing the zero address withdraws an offer.

Making a proof

The prover needs the credential (from the memo), the holder's secret, and the Merkle path of the leaf in the set's current tree. The tree is rebuilt on the client from the set's Issued events, in index order, with zero leaf 0 and zeros[i+1] = Poseidon(zeros[i], zeros[i]). The root must equal currentRoot(setId) or a root replaced less than an hour ago (isKnownRoot).

Public signals

Six, in this order. Private inputs: secret, value, expiry, salt, pathElements[20], pathIndices[20]. The circuit checks value ≥ threshold and expiry > provedAt + 3600, all range-checked so nothing wraps around the field.

#SignalWhere it comes from
0rootThe tree you rebuilt; check it with isKnownRoot before proving
1thresholdWhat the consumer will pass: the drop's threshold, requiredCollateral(limit), your own constant
2provedAtThe latest block's timestamp. The contract rejects values in the future or older than one hour
3scopeZelra.scopeOf(consumer, context): the chain, the consumer's address and its context
4nullifierHashPoseidon(secret, scope)
5signalHashThe signal as a field element: uint256(uint160(address)) for the caller or the recipient

In JavaScript

import * as snarkjs from 'snarkjs';
import { poseidon2 } from 'poseidon-lite';

const scope = await zelra.read.scopeOf([consumer, context]);
const provedAt = (await client.getBlock()).timestamp;
const { root, pathElements, pathIndices } = tree.path(cred.index);
const input = {
  root, threshold, provedAt, scope,
  nullifierHash: poseidon2([key.secret, scope]),
  signalHash: BigInt(signalAddress),
  secret: key.secret, value: cred.value, expiry: BigInt(cred.expiry), salt: cred.salt, pathElements, pathIndices,
};
const { proof } = await snarkjs.groth16.fullProve(stringify(input), '/zk/condition.wasm', '/zk/condition.zkey');

// what the contracts take: note the swapped G2 coordinates
const solidity = {
  a: [proof.pi_a[0], proof.pi_a[1]],
  b: [[proof.pi_b[0][1], proof.pi_b[0][0]], [proof.pi_b[1][1], proof.pi_b[1][0]]],
  c: [proof.pi_c[0], proof.pi_c[1]],
};

The artifacts are served by the site: /zk/condition.wasm (2 MB), /zk/condition.zkey (5.6 MB), /zk/condition.vkey.json. Fetch them once and keep them in memory; the app preloads them while the visitor looks around. stringify turns every bigint into a decimal string, which is what snarkjs expects.

Proof JSON

The app's Download proof writes this shape. It carries everything a verifier call needs.

{
  "protocol": "groth16", "curve": "bn128",
  "chainId": 4663, "zelra": "0x…", "setId": 1,
  "publicSignals": { "root": "…", "threshold": "150000", "provedAt": "…", "scope": "…", "nullifierHash": "…", "signal": "…" },
  "proof": { the snarkjs proof object },
  "solidity": { "a": [..], "b": [[..],[..]], "c": [..] }
}

Consuming proofs

A consumer calls one of three functions on Zelra. All of them check the set, the root, the threshold range, the freshness of provedAt and the proof itself; consume and attest derive the scope from msg.sender, so only the contract the proof was made for can use it.

FunctionUse it when
verify(setId, root, threshold, provedAt, scope, nullifierHash, signal, proof) → boolYou want a yes or no without side effects: a view, callable off-chain, passing the scope explicitly.
consume(setId, context, root, threshold, provedAt, nullifierHash, signal, proof)Each identity may do the thing once per context: claims, votes, allow-lists, sign-ups. Reverts if the nullifier was spent.
attest(setId, context, root, threshold, provedAt, nullifierHash, signal, proof)You keep your own policy on repeat proofs: a credit line the same identity may renew, a tier that can be re-checked. Records the proof, spends nothing.

Bind the signal to what matters: msg.sender when the caller is the beneficiary, a recipient address when anyone may submit on the holder's behalf. Pick the context deliberately: 0 means one use per holder across your whole contract; a campaign or drop id means one use per holder per campaign.

A consumer contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

interface IZelra {
    struct Proof { uint256[2] a; uint256[2][2] b; uint256[2] c; }
    function consume(uint256 setId, uint256 context, uint256 root, uint256 threshold, uint256 provedAt,
                     uint256 nullifierHash, uint256 signal, Proof calldata proof) external returns (bool);
}

/// Admits each holder of a credential ≥ 700 in the trusted set, once.
contract Gate {
    IZelra public immutable zelra;
    uint256 public immutable setId;      // the set you trust, fixed at deployment
    uint256 public constant THRESHOLD = 700;
    uint256 public constant CONTEXT = 1;  // one admission per holder for this context
    mapping(address => bool) public admitted;

    constructor(IZelra zelra_, uint256 setId_) { zelra = zelra_; setId = setId_; }

    function enter(uint256 root, uint256 provedAt, uint256 nullifierHash, IZelra.Proof calldata proof) external {
        // reverts on a stale root, an old or future provedAt, a spent nullifier, or a bad proof
        zelra.consume(setId, CONTEXT, root, THRESHOLD, provedAt, nullifierHash, uint256(uint160(msg.sender)), proof);
        admitted[msg.sender] = true;
    }
}

On the client, this contract's proofs are made with scope = scopeOf(address(gate), 1), threshold = 700 and signal = the caller's address. Errors thrown by Zelra bubble up through your contract unchanged; include its ABI's errors when decoding reverts.

Errors

ErrorWhy
UnknownSet(setId)No such set on this chain
UnknownRoot(setId, root)Not the current root and not replaced within the last hour: rebuild the tree and prove again
ThresholdOutOfRange(threshold)Thresholds must fit in 64 bits
ProofExpired(provedAt)More than one hour old
ProofFromTheFuture(provedAt)Later than the block's timestamp
NullifierUsed(nullifierHash)consume only: this identity already used a credential in this scope
InvalidProof()The proof does not verify for these public inputs: wrong scope, signal, threshold, root, or a tampered proof
NotIssuer, NotPendingIssuerIssuer-only functions called by someone else
InvalidLeaf, EmptyBatch, BatchTooLarge, LengthMismatch, SetFullIssuance input checks

Contract reference

Zelra

LEVELS = 20Tree depth: 1,048,576 credentials per set
MAX_PROOF_AGE = 1 hoursHow long after provedAt a proof is accepted
ROOT_GRACE = 1 hoursHow long a replaced root stays valid
MAX_BATCH = 64Upper bound of issueMany
MAX_THRESHOLD = 2^64 - 1Values and thresholds are 64-bit
createSet(name, schema, unit) → setIdAnyone. The caller becomes the issuer.
proposeIssuer(setId, to) / acceptIssuer(setId)Two-step handover. pendingIssuerOf(setId) shows an open offer.
issue(setId, leaf, memo) → indexIssuer only. Emits Issued(setId, index, leaf, memo).
issueMany(setId, leaves[], memos[]) → firstIssuer only, up to 64 leaves, one new root.
verify(…) → boolView; the scope is passed explicitly.
consume(…) / attest(…) → boolScope derived from msg.sender and context; both emit ProofVerified(setId, consumer, context, nullifierHash, threshold, signal).
scopeOf(consumer, context) → uint256View. keccak256(abi.encode(block.chainid, consumer, context)) mod p.
isKnownRoot(setId, root), currentRoot(setId)Root checks for clients.
nullifierUsed(nullifierHash) → boolSpent by consume, in any scope.
getSet(setId), getSets(from, count), setsOf(issuer), issuerOf(setId), setCount, proofCountViews. SetView: id, issuer, pendingIssuer, size, proofs, createdAt, updatedAt, root, name, schema, unit.
zeros(level)Root of the empty subtree at a level, for clients that rebuild trees.

ZelraCredit

An ERC-4626 pool (zcUSD shares over a 6-decimal dollar) lending against private collateral in one trusted set. Uses attest with context 0; one credential identity backs one account forever.

RATIO_BPS = 15000Collateral ≥ 1.5 × limit
APR_BPS = 8008% a year nominal, through a global index that compounds whenever anyone interacts (at most e0.08 − 1 ≈ 8.33% effective)
ORIGINATION_BPS = 100.1% of every draw, added to the debt and paid to the pool, so a same-block borrow and repay is not free liquidity
TERM = 30 days, GRACE = 14 daysLine term; grace after it before a default can be marked
MIN_DEFAULT = $1, DUST = $0.01Smallest debt that can be defaulted; residue forgiven on closeLine
DEFAULT_BOUNTY_BPS = 10, MAX_BOUNTY = $100What the marker of a default is paid from the pool's cash
requiredCollateral(limit) → uint256The threshold the proof must carry: ceil(limit × 1.5 / unitScale)
openLine(limit, root, provedAt, nullifierHash, proof)Open, raise or renew. Signal = msg.sender; provedAt must be newer than the account's previous proof. Reverts CredentialInUse, AccountBoundToOtherCredential, LineDefaulted, StaleProof, LimitBelowDebt.
borrow(amount)Draw up to the limit (fee included) and the pool's cash, until the line expires. Emits Borrowed(borrower, amount, fee, debt).
repay(borrower, amount) → paid, closeLine()Anyone may repay for anyone; type(uint256).max repays everything. Close a repaid line; a residue below DUST is forgiven.
markDefault(borrower)Anyone, after expiry + GRACE with at least MIN_DEFAULT unpaid. Writes the debt off, bars the account, pays the caller the bounty. Emits Defaulted(borrower, writtenOff, marker, bounty).
deposit / withdraw / redeem / maxWithdraw / maxRedeemERC-4626; withdrawals capped by the pool's cash. Six-decimal share offset.
lineOf(borrower), pool(), borrowers(from, count), debtOf, totalDebt, currentIndexViews

ZelraDrop

Sponsor-funded allocations for holders whose credential in a set clears a threshold. Uses consume with context = drop id; one claim per identity per drop.

create(name, token, setId, expectedIssuer, threshold, perClaim, maxClaims, deadline) → dropIdFails with WrongIssuer unless the set is issued by expectedIssuer, so a lookalike set with the same name cannot be funded by mistake. Pulls perClaim × maxClaims and checks it arrived in full (TokenTookFee otherwise).
claim(dropId, recipient, root, provedAt, nullifierHash, proof)Anyone may submit; signal = recipient. Emits Claimed.
setRefundTo(dropId, to)Sponsor only, any time before closing: where the refund goes instead of the sponsor (a blacklisted or lost address). refundTo(dropId) reads it.
close(dropId)Sponsor only, after the deadline or once every claim is taken; refunds the rest. Emits DropClosed(dropId, to, refund).
getDrop(dropId), getDrops(from, count), dropCount(), claimed(nullifierHash)Views

ZelraSetup

A deployment helper with no functions and no power. Its constructor opens the collateral and score sets, deploys ZelraCredit bound to the collateral set and a ZelraDrop, and offers both sets to the issuer, all in one transaction. The pool therefore trusts the exact set id that transaction received; nobody can slip in a createSet of their own between the two. The issuer takes the sets with acceptIssuer. Read the addresses from credit(), drop(), collateralSet() and scoreSet().

Relay API

The relay submits drop claims so the holder's wallet never appears next to the recipient. It simulates first, pays the gas, refuses a nullifier it submitted in the last few minutes, rate-limits per client and globally, and only talks to deployments it knows. It cannot redirect a claim and never receives the holder's wallet or secret. It does see the client's IP next to the recipient: holders who care should come through a VPN or Tor.

GET /{ address, chains: [{ chainId, name, drop, balance }] }: the relay's address and funding per chain
POST /claimBody { chainId, dropId, recipient, root, provedAt, nullifierHash, proof: { a, b, c } }, numbers as decimal strings. Returns { hash } or { error }.

The app uses the relay configured at build time (VITE_RELAY_URL); without one, the holder's wallet submits the claim and the app says that the link will be visible.

Deployments

NetworkStatus
Robinhood Chain (4663)Deployed 6 October 2026 at block 81058454: Zelra 0x9ab6A0e2252f95C9A746FBC51c5fd3522a315914, ZelraSetup 0x61F2D05ce12B55c4e00d7218861DB83D3BbaF104, ZelraCredit 0x434a0074F5E957AE67Cc99E5EfE728f6771221a4, ZelraDrop 0xF6a5193473839AEc29D3938e7e12a3BCA6314C57, verifier 0x55c1CF542FE5bef0aD45257D1838C533C3C00aba, USDC (bridged) 0x80e0e24718dbFcad49ECAA6F1e6C89A190586cA8. Sets 1 (collateral) and 2 (score). The verifier still comes from a single-contributor phase-2 setup: the contracts will be redeployed after the multi-party ceremony, and they have not been audited externally. Use small amounts. Sources verified on Sourcify. Explorer: Blockscout.
Local Anvil (31337)Deterministic on a fresh anvil with npm run deploy:local: Zelra 0x9fE4…a6e0, ZelraSetup 0xDc64…F6C9, ZelraCredit 0x856e…eae5, ZelraDrop 0xb027…9cC3, verifier 0xe7f1…0512, mock USD 0xCf7E…0Fc9. Sets 1 (collateral) and 2 (score).

The application reads addresses from a per-chain deployment record; on a chain without one every screen says "not deployed yet".

Tooling

npm run dev                       # site at :5191, app at :5191/app/ (Robinhood Testnet and a local Anvil are listed next to Robinhood Chain)
npm run build                     # tsc + vite build → dist/
npm run contracts:test            # 78 Foundry tests with real Groth16 proofs, invariant suites included
FORK=1 npm run contracts:test:fork # against forked Robinhood Chain state (real bridged USDC)
npm run contracts:build && npm run sync    # ABIs and bytecode → src/app/generated
npm run circuit -- <ppot15.ptau>  # compile the circuit, dev phase-2 setup, verifier.sol
npm run ceremony -- <init|contribute|verify|finalize|status>   # multi-party phase-2 setup
npm run fixtures                  # the proofs the tests load
npm run chain                     # anvil; then PRIVATE_KEY=<key 0> npm run deploy:local
npm run deploy:contracts -- <robinhood-testnet|robinhood> [--yes] [--dry-run]
npm run relay                     # the drop-claim relay (live at https://zelra.network/relay/)
npm run whitepaper:pdf            # print the built whitepaper to public/whitepaper/

The circuit is circuits/condition.circom (circom 2.1, circomlib Poseidon). Phase one of its setup is the PSE Perpetual Powers of Tau (215, 80 contributions); phase two is a single development contribution until npm run ceremony has been run with several participants.

Security notes