@opertus/core
Pool synchronization, note selection, proof generation, and transaction call building.
This package reads pool events, reconstructs the pool's Merkle tree, builds circuit inputs, generates Groth16 proofs, and returns viem-compatible contract call objects. It does not sign or broadcast transactions. For background, see the protocol architecture and the threat model.
The examples on this page share one setup:
import { createPublicClient, http, type Address } from 'viem';
import { OpertusClient, createProver } from '@opertus/core';
import { KeyManager, Scanner, Sender } from '@opertus/wallet';
declare const rpcUrl: string;
declare const poolAddress: Address;
declare const token: Address;
declare const buildDir: string; // circuit WASM and zkey artifacts
declare const mnemonic: string;
const publicClient = createPublicClient({ transport: http(rpcUrl) });
const client = new OpertusClient({ publicClient, poolAddress, prover: createProver(buildDir) });
const wallet = KeyManager.fromMnemonic(mnemonic);
const me = wallet.getMetaAddress();
const domain = {
chainId: BigInt(await publicClient.getChainId()),
poolAddress: BigInt(poolAddress),
};Synchronize a pool
const sync = await client.getLogs({ fromBlock: poolDeployBlock, blockRange: 10_000n });
const { tree, payloads, spentNullifiers } = sync;A wallet restored on a new device runs the same sync from the deploy block and
gets the same history: every log carries its block and transaction, and the
outgoing records in payloads rebuild what the wallet sent. After syncing,
getLogs checks the rebuilt root with isKnownRoot at lastBlock and throws
Sync incomplete if the pool never recorded it, which means a log was dropped.
OpertusClientConfig
Prop
Type
getLogs
Prop
Type
SyncResult
Prop
Type
See sync incrementally for persisting a cursor between runs.
The pool accepts a commitment that is already in the tree. Both copies share a
nullifier, so only one can be spent. getLogs keeps the first leaf and sets
metadata.duplicate on later copies; consolidate and withdraw refuse a
note flagged that way.
Discover clones
const { clones, nextDiversifier } = await client.discoverClones(spendScalar, { tokens: [token] });discoverClones tries diversifiers from 0, reads executor.cloneOf for each
salt, and counts a clone as used once it has code. It stops after 20 unused
diversifiers in a row. Each clone comes back with its salt and the balance of
each token you pass. nextDiversifier is the first one after the last used
clone. Use clones in order so a restore finds them all.
Read one note log
const logged = await client.getNoteLog({ transactionHash, logIndex });
const chainId = await client.getChainId();
// On an RPC that caps eth_getLogs block ranges:
const capped = await client.getNoteLog({ transactionHash, logIndex }, { fromBlock: deployBlock, blockRange: 10_000n });getNoteLog fetches the transaction receipt and returns the NoteCommitted or
ReturnShielded log at logIndex in the same { payload, metadata, commitment }
shape as a getLogs payload. It throws when the transaction reverted, the log
is missing, another contract emitted it, it is another event, or its packed note
is malformed. It sets metadata.duplicate when the pool logged the same
commitment earlier, at a lower leaf index; a duplicate shares the first copy's
nullifier, so count it once. Receipt verification uses it: see
receipts.
To find an earlier copy, getNoteLog queries the pool's logs for that commitment from
fromBlock (default 0n) up to the note's block, in a single request per event unless
blockRange is set. Providers that cap eth_getLogs ranges need both options: start at the
pool's deploy block, since a later fromBlock can miss the first copy. A note at leaf
index 0 cannot have an earlier copy and costs no extra queries.
Scan and prepare inputs
Scan the payloads with the view key, drop spent notes, and derive the one-time spend secret for each note you intend to spend:
const found = await Scanner.scan(wallet.exportViewingKey(), payloads, domain);
const unspent = found
.map((record) => ({ ...record, commitment: record.note.getCommitment() }))
.filter((record) => !spentNullifiers.has(record.note.getNullifier()));
for (const record of unspent) {
record.note.payload.ownerSecret = wallet.computeStealthSecret(
record.spendEphemeralPubKey,
record.note.payload.ownerPubKey!,
);
}Select inputs
import { NoteSelector } from '@opertus/core';
const selection = NoteSelector.select(unspent, requestedAmount, BigInt(token), true);NoteSelector.select
Prop
Type
SelectionResult
Prop
Type
The optional fee is a 0.5% relayer fee and is distinct from protocol fees. This percentage is SDK policy, not a contract or circuit rule. See relayers before using it as a production quote. The method throws for non-positive amounts, insufficient funds, or a selection requiring more than eight notes.
Proving
import { createProver } from '@opertus/core';
const prover = createProver(buildDir); // all four widths
const smallProver = createProver(buildDir, [1, 2]); // only 1- and 2-input proofscreateProver returns a ZKProver that holds one ProofGenerator per circuit
width and reads each width's artifacts the first time a proof of that width is
requested. It reads artifacts from the filesystem, so it runs in Node. Call
prover.terminate() to release the loaded buffers.
Prop
Type
Each width reads these artifacts under buildDir:
| Artifact | Path under buildDir |
|---|---|
| Circuit WASM | transfer_{n}x3_js/transfer_{n}x3.wasm |
| Proving key | keys/transfer_{n}x3_final.zkey |
ProofGenerator is also exported for callers that manage widths themselves. One
instance loads one circuit with init(circuitName); later init calls are
ignored, and generate throws before initialization.
Match proving and verification artifacts
Use proving artifacts that correspond to the reviewed circuits, and confirm that the deployed verifier contracts match those artifacts for the target deployment. See deployment integrity.
Build pool calls
All three methods return viem-compatible contract call objects; they do not
sign or broadcast. Every output is a { note, payload } pair from
Sender.prepareSend, and every spend takes exactly three of them. Before
proving, the client checks that:
- every output exists and is for the spent token;
- every selected note has
ownerSecret,nk, andblindingset; - the number of selected notes fits
circuitSize; - input values equal output values plus the public amount.
Each failed check throws a specific error; see the SDK rejects the call before proving for the messages and their causes.
| Method | Return timing | Uses a proof | Outputs | Contract effect |
|---|---|---|---|---|
deposit | Synchronous | No | recipient | Moves a public asset into one private note |
consolidate | Asynchronous | Yes | recipient, change, fee | Privately spends inputs into three output notes |
withdraw | Asynchronous | Yes | change, extra, fee | Spends inputs, creates three outputs, and unshields or executes one public call |
The relayer fee is always the third output, fee. Pass a zero-value note there
when nobody is paid.
import { OpertusBuilder } from '@opertus/core';
const amount = 1_000_000n;
const noteValue = OpertusBuilder.predictShieldNote(amount, 0n, await client.getDepositFeeBps());
const recipient = await Sender.prepareSend(me, BigInt(token), noteValue, domain);
const call = client.deposit({ recipient, amount, token });
await walletClient.writeContract(call);DepositConfig
Prop
Type
deposit(config) returns synchronously. For ETH, use the exported ETH zero
address; the returned call includes value: amount.
Prop
Type
ConsolidateConfig
Prop
Type
consolidate(config): Promise<PoolCall> proves a private transfer and returns
a transfer call.
WithdrawConfig
Prop
Type
withdraw(config): Promise<PoolCall> proves an unshield and returns an
unshield call. Leave unshieldFeeBps unset unless you have just read it
yourself; the proof fails if it differs from the pool's rate at settlement.
By default cloneSalt is zero and a positive amount is required. Supplying
spendScalar with nonempty data, or with a diversifier, replaces
cloneSalt with cloneSaltOf(spendScalar, diversifier); this permits a
zero-amount clone call. Without a diversifier, a call takes the next fresh
clone. A sweep has empty data, so it must name its diversifier.
A fee-on-transfer token cannot be sent through a clone: the clone receives less
than the net and the call reverts with CloneUnderpaid. Withdraw such tokens
with empty data and salt 0.
Outputs and return notes are packed with their memo and outgoing record, if the
payload has them, so pass { sender: wallet } to Sender.prepareSend and
prepareReturn for every note you build.
PreparedOutput and InputNote
Core describes wallet objects structurally, so it does not depend on
@opertus/wallet. A Sender.prepareSend result is a PreparedOutput, and a
Scanner.scan record with commitment and ownerSecret set is an
InputNote.
Prop
Type
Fee getters
Prop
Type
Low-level exports
The root package also exports OpertusBuilder, ProofGenerator,
NoteMerkleTree, MERKLE_TREE_DEPTH, buildTransferInputs, ABI and hash helpers, transaction
types, formatProof, Width, EMPTY_ENCRYPTED_NOTE, EMPTY_RETURNS, and
proof/witness types.
packEncryptedNote(payload, kind) turns a Sender.prepareSend or prepareReturn
payload into the pool's packed note bytes (EncryptedNote is that Hex),
including its outgoing record; pass 'return' for a prepareReturn payload.
unpackEncryptedNote(bytes, kind) splits event bytes back into scanner fields;
kind is 'note' for NoteCommitted (208-byte ciphertext) or 'return' for
ReturnShielded (176 bytes). The length must be exactly the 91-byte header plus
that ciphertext, or that plus the 116-byte outgoing record, which comes back as
outgoing. Any other length throws, and getLogs keeps such a note as a leaf
without a payload. See
the byte layout. These are lower-level protocol surfaces; prefer
OpertusClient unless you need to assemble and validate every field yourself.