Transactions
Deposit, transfer privately, call external contracts, and unshield with the Opertus SDK.
The examples on this page use the client, wallet, and domain from
getting started. Each transaction is
tied to one chain and one pool, which is what domain describes.
| Operation | SDK method | Private notes | Public effect |
|---|---|---|---|
| Deposit | deposit | Creates one note | Moves a public asset into the pool |
| Private transfer | consolidate | Spends 1, 2, 4, or 8 notes; creates three | None |
| Unshield | withdraw | Spends 1, 2, 4, or 8 notes; creates three | Sends the net amount to a public address |
| Composed call | withdraw with data | Same, plus up to four return notes | Routes the net amount through one public call |
Every method returns a viem-compatible call. You sign and send it with your own wallet client:
const call = client.deposit({ recipient, amount, token });
await walletClient.writeContract(call);Sync first
Spending needs the pool's current tree and the list of spent nullifiers.
getLogs builds both:
const { tree, payloads, spentNullifiers } = await client.getLogs({
fromBlock: poolDeployBlock,
blockRange: 10_000n,
});The SDK reconstructs pool state from NoteCommitted, ReturnShielded, and
NullifierSpent events. The pool has one Poseidon LeanIMT for its whole life,
at most 32 levels deep. The SDK sorts commitments by their emitted leaf index
and appends them in order; a missing index throws instead of producing a wrong
root. A node without a right child moves up unhashed, so there are no zero
hashes.
Every note lives in the same tree, so any notes of one token can be spent together. Historical roots stay valid; each nullifier is accepted only once.
After building the tree, the SDK asks the pool whether the root is known at the
last block synced. If not, a log was dropped, and getLogs throws
Sync incomplete rather than hand back a tree that cannot prove.
The pool does not reject a commitment that is already in the tree. A copy
shares the first note's nullifier, so only one can be spent. The SDK keeps the
first leaf and flags later copies duplicate.
Sync incrementally
Public RPCs usually cap the block range of one eth_getLogs request, so sync in
chunks, save where you stopped, and extend the previous result next time:
const first = await client.getLogs({ fromBlock: poolDeployBlock, blockRange: 10_000n });
saveCursor(first.lastBlock);
// Later: fetch only new blocks and extend the same tree in place.
const next = await client.getLogs({
fromBlock: first.lastBlock + 1n,
blockRange: 10_000n,
previous: first,
});Start from the pool's deployment block rather than 0n. Pass previous so the
new events extend the earlier tree; a tree built only from recent events has
a different root and throws on the first leaf index it does not expect. If you
store the tree yourself, store every leaf and its index,
not only the root. Near the chain head, re-sync a few blocks behind lastBlock
or wait for finality, so a reorg doesn't leave a commitment in your local tree
that the pool no longer has.
Restore on a new device
A wallet's whole history is on chain. With only the seed, sync from the deploy block and rebuild it:
const sync = await client.getLogs({ fromBlock: poolDeployBlock, blockRange: 10_000n });
const items = sync.payloads.filter((p) => !p.metadata.duplicate);
const received = await Scanner.scan(wallet.exportViewingKey(), items, domain);
const sent = Scanner.scanOutgoing(wallet, items, domain);
const { clones } = await client.discoverClones(BigInt(wallet.getSpendingKey()), { tokens });Each record carries its block and transaction. spentNullifiers says where each
note was spent, unshields lists public withdrawals, and cloneCalls lists the
calls your clones made.
Pick notes to spend
Scan with your view key, drop spent notes, derive the one-time spend secret for
each note, and let NoteSelector choose:
import { NoteSelector } from '@opertus/core';
import { Scanner } from '@opertus/wallet';
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!,
);
}
const selection = NoteSelector.select(unspent, requestedAmount, BigInt(token), true);Deposit
import { OpertusBuilder } from '@opertus/core';
import { Sender } from '@opertus/wallet';
const amount = 1_000_000n;
const noteValue = OpertusBuilder.predictShieldNote(amount, 0n, await client.getDepositFeeBps());
const recipient = await Sender.prepareSend(wallet.getMetaAddress(), BigInt(token), noteValue, domain);
const call = client.deposit({ recipient, amount, token });The note holds what arrives after the pool's deposit fee, so prepare it for
the predicted net value. For an ERC-20, approve the pool for amount first.
For ETH, pass the exported ETH address; the call includes value: amount.
Deposits don't need a proof.
A deposit is a public token transfer followed by one commitment insertion. The pool measures what actually arrived, computes its deposit fee, and requires:
arrived amount - deposit fee = note valueThis keeps accounting correct for fee-on-transfer tokens: pass the token's own
transfer fee as the second argument to predictShieldNote. If the measured net
differs from the prepared note, the call reverts and nothing is inserted. A
note value is nonzero and less than 2^120.
Private transfer
const send = (to: string, value: bigint, memo?: Uint8Array) =>
Sender.prepareSend(to, BigInt(token), value, domain, { memo, sender: wallet });
const call = await client.consolidate({
tree,
selectedNotes: selection.selectedNotes,
token,
circuitSize: selection.circuitSize,
outputs: {
recipient: await send(recipientMetaAddress, requestedAmount, new TextEncoder().encode('rent')),
change: await send(wallet.getMetaAddress(), selection.changeAmount),
fee: await send(relayerMetaAddress, selection.feeAmount),
},
});Passing sender: wallet derives each note's keys from your outgoing key and
adds an encrypted outgoing record to each note paid to someone else, so your
wallet can rebuild what it sent, and to whom, from the seed. The memo is up to
32 bytes and only the recipient and you can read it.
To prove one payment, to a landlord or an auditor, give them a receipt instead of your viewing key:
import { createReceipt, encodeReceipt } from '@opertus/wallet';
const receipt = encodeReceipt(createReceipt(wallet, sentItem, domain, { proveRecipient: true }));The receipt opens that note and nothing else. See selective disclosure.
A transfer always creates three notes: the payment, your change, and a fee note
for whoever submits it. If nobody is paid, send a zero-value fee note to
yourself. The three values add up to the selected notes; the client checks
this before proving. To have someone else submit the call, see
relayers.
The proof sets publicAmount and cloneSalt to zero. The pool verifies the
known root and proof, marks every input nullifier spent, inserts all three
commitments, and records the final root. No token balance moves.
A zero-value output is still a real committed note with fresh opening data
and ciphertext. Sender.prepareSend makes each one unique, so commitments
never collide.
Unshield to a public address
const call = await client.withdraw({
tree,
selectedNotes: selection.selectedNotes,
token,
circuitSize: selection.circuitSize,
amount: requestedAmount,
recipient: publicRecipient,
outputs: {
change: await send(wallet.getMetaAddress(), selection.changeAmount),
extra: await send(wallet.getMetaAddress(), 0n),
fee: await send(relayerMetaAddress, selection.feeAmount),
},
});amount is the gross leaving the pool. The pool takes its unshield fee and
sends the rest to recipient. The client reads the live fee rate for you. If
the rate changes before your transaction lands, rebuild it.
A plain unshield uses empty calldata, an empty return list, and salt zero. The circuit conserves the gross amount against the inputs and outputs; the pool calculates the protocol fee and sends the net to the target.
The fee isn't a caller-supplied field. It's computed from the live rate and included in the unshield hash that the proof binds, which is why a rate change needs a new proof.
Compose an external call
Pass data to route the net amount through one public contract call, and list
any tokens the call sends back so they return to the pool as private notes:
import { packEncryptedNote, type ReturnNote } from '@opertus/core';
const back = await Sender.prepareReturn(wallet.getMetaAddress(), BigInt(outToken), domain, { sender: wallet });
const returning: ReturnNote[] = [
{
token: outToken,
minValue: minOut,
ownerPubKey: back.note.payload.ownerPubKey!,
randomness: back.note.payload.randomness,
blind: back.note.payload.blind!,
note: packEncryptedNote(back.payload, 'return'),
},
];
const call = await client.withdraw({
tree,
selectedNotes: selection.selectedNotes,
token,
circuitSize: selection.circuitSize,
amount: requestedAmount,
recipient: routerAddress,
data: routerCalldata,
returning,
outputs: {
change: await send(wallet.getMetaAddress(), selection.changeAmount),
extra: await send(wallet.getMetaAddress(), 0n),
fee: await send(relayerMetaAddress, selection.feeAmount),
},
});The target and calldata are public, like any onchain call. You can list up to
four return tokens, each with a minValue below which the call reverts.
The pool sends the net straight to the clone, the clone makes the call, and the
pool measures the balance increase for each listed token. It creates a return
note for what actually arrived, subject to minValue and the protocol's
accounting cap. A fee-on-transfer return token therefore produces a note for the
amount received. Each token can appear once, and assets that aren't listed stay
on the clone.
A fee-on-transfer token cannot be the token you spend into a call: the clone
receives less than the net and the call reverts with CloneUnderpaid. Unshield
it to a public address instead.
Choose the call address
By default the call goes through a shared caller contract (salt zero). If the
downstream protocol needs a stable caller address for you, for example to keep
a position, pass spendScalar. The client derives a persistent CREATE2 address
and proves the salt:
clone salt = Poseidon(spend scalar, diversifier)Without a diversifier, the client uses discoverClones(spendScalar).nextDiversifier,
a fresh clone. Pass the diversifier to reuse a clone or to sweep it. Using
diversifiers in order lets a restored wallet find every clone: discovery stops
after 20 unused ones in a row.
Confirm the result
After the transaction is included, sync again. Your input nullifiers appear in
spentNullifiers, the new notes appear in payloads, and an unshield appears
in unshields. A sweep emits no Unshielded; its return notes are its record. Recipients find
their notes the same way, by scanning; there's no public balance to check.
If something doesn't line up, troubleshooting walks through the common cases, and architecture describes the full settlement sequence.