Opertus

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.

OperationSDK methodPrivate notesPublic effect
DepositdepositCreates one noteMoves a public asset into the pool
Private transferconsolidateSpends 1, 2, 4, or 8 notes; creates threeNone
UnshieldwithdrawSpends 1, 2, 4, or 8 notes; creates threeSends the net amount to a public address
Composed callwithdraw with dataSame, plus up to four return notesRoutes 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,
});

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.

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.

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.

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.

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.

On this page