Skip to content

Syncing ​

A wallet holds no state until it scans the pool. Syncing reads the pool's events from the wallet's last checkpoint to the chain head and builds up its note set, which balances and history are then computed from.

Running a sync ​

sync() scans from the wallet's last synced block to the chain head and reports the window it covered:

ts
const { fromBlock, syncedThrough, scanned } = await wallet.sync();
  • fromBlock — where this scan resumed from (the last checkpoint + 1).
  • syncedThrough — the block the wallet has now scanned through.
  • scanned — false when the head had not advanced past the checkpoint, i.e. there was no work to do.

Checkpoints and resume ​

Scan state persists through the storage adapter. A wallet loads its saved state when you create it, so balances(), history(), and planning work straight away after a reload, before any sync. A later sync() resumes from the last checkpoint rather than rescanning from the pool's deploy block, so repeat syncs only cover new blocks. Saving is incremental too: a sync writes the newest part of the merkle tree and the wallet's notes, not the whole state. A wallet keeps only its own spends, not every nullifier and unshield in the pool.

The merkle trees belong to the SDK instance, not to each wallet. One sync reads the pool once and hands the verified events to every wallet that is up to date, and syncs on one instance run one at a time. A wallet that is behind — new, or created after the instance has synced — first catches up: it reads the events from its creationBlock (or from where its notes stopped) and checks each commitment against the trees the instance already verified. Several wallets on one instance therefore cost one scan of the pool, not one each.

Each sync builds its result on a copy of the wallet's state and switches over only once the result is verified and saved. Reads made while a sync is running — balances(), history(), planTransfer — see the last completed sync, never a half-applied one, and a sync that fails leaves the checkpoint where it was.

syncStatus() is a cheap read of that state — the persisted checkpoint and whether a sync is currently in flight. It does no network calls and changes nothing:

ts
const { syncedThrough, syncing } = await wallet.syncStatus();

sdk.sync.status() is the same for the instance: the block its trees are synced through, and whether any wallet's sync is running.

Ephemeral wallets are the exception: they are in-memory only and do not persist a checkpoint (see Wallets).

Staying synced automatically ​

Rather than call sync() on your own timer, watch() keeps the wallet current for you. It runs sync() immediately, then every intervalMs (default 10s), and returns a function that stops it:

ts
const unwatch = wallet.watch();
// …later
unwatch();

Pass options to tune it:

ts
const unwatch = wallet.watch({
  intervalMs: 5_000,        // override the default cadence
  immediate: false,         // wait one interval before the first sync (e.g. you just synced)
  onError: (err) => console.warn('auto-sync', err),
});

watch() only schedules the same verified sync() — it adds no trust surface. A failed sync does not stop the loop: it is reported through onError and the scan:error event, and the next attempt backs off exponentially (capped at 30s) until one succeeds. Auto-sync coalesces with any manual sync() or post-transaction refresh, so overlapping calls are safe. A wallet can only have one watcher at a time — calling watch() again while watching throws; stop the current one first. The default cadence is pool.autoSyncIntervalMs. Watchers are also stopped when the SDK is closed.

Reorg safety ​

Two optional fields on the pool config guard against chain reorganizations. Both default to 0:

ts
pool: {
  // …
  confirmationDepth: 12,  // stay 12 blocks behind the head when scanning
  finalityThreshold: 12,  // count commitments as spendable only after 12 confirmations
}
  • confirmationDepth controls what gets scanned. A sync scans to head − confirmationDepth, and only commitments up to that point are persisted, so a reorg of that depth or shallower cannot remove a note the wallet has already scanned. With the default 0, syncs scan to the head.
  • finalityThreshold controls the balance view. It is the number of confirmations a commitment needs before balances() counts it as spendable rather than pending. With the default 0, a commitment counts as spendable as soon as it is scanned.

Both gate on a commitment's confirmations — how many blocks behind the chain head it is: confirmationDepth decides whether it is scanned at all, and finalityThreshold decides whether a scanned commitment is spendable or pending.

With both at their default of 0, a commitment is scanned and spendable as soon as its block is reached.

Deeper reorgs are detected rather than prevented. Each sync records the hash of the last block it scanned; if the chain's hash at that height has changed by the next sync, the wallet resets its chain-derived state and rescans from the pool's deploy block (in-flight spend holds are kept). The same rescan runs if the saved state turns out to be missing part of the chain. Both emit sync.reorg-recovery telemetry with a reason. A rescan takes a while on a long chain, so on a chain with frequent one-block reorgs a confirmationDepth of 1–2 avoids repeated rescans.

Every sync is also verified before it is accepted: the rebuilt merkle tree must match the pool's tree (tree number, leaf count, and root) at the scanned block. If an RPC node returns incomplete logs, the sync fails without moving the checkpoint, and the next sync retries the same range.

A long sync — a wallet's first, on a pool with history — advances in chunks of 100,000 blocks, each verified and saved before the next. If it fails partway, the chunks before the failure are kept and the next sync carries on from there instead of starting over. Chunks before the head are checked against the pool's history of roots; only the last one is checked against the pool's exact tree. Verification reads the pool's state at the scanned block, so keep confirmationDepth within the RPC node's recent-state window (about 128 blocks on a standard, non-archive node).

Event sources ​

By default, syncing reads pool events from the RPC endpoints in rpc.urls. You can optionally supply an indexer as the primary event source; when set, RPC covers the tail and results are verified against the on-chain tree, and the value and token of each of your shielded notes must match its commitment. A batch that fails either check is discarded and the range rescanned from RPC. Omit it to sync purely from RPC:

ts
const sdk = await createArmadaSdk({
  // …
  indexer: { url: 'https://…' },
});

Scan events ​

wallet.on(event, listener) subscribes to scan and balance events and returns a function that unsubscribes:

ts
const unsubscribe = wallet.on('balance:updated', ({ tokenHash, tokenAddress, spendable, pending }) => {
  console.log(tokenHash, tokenAddress, spendable, pending);
});

// later
unsubscribe();

The events and their payloads:

EventPayload
scan:started{ fromBlock, toBlock }
scan:progress{ syncedThrough, fraction }
scan:complete{ syncedThrough }
scan:error{ error }
note:received{ tokenHash, tokenAddress, value, memo?, senderShieldedAddress? }
balance:updated{ tokenHash, tokenAddress, spendable, pending }

note:received fires once for each incoming transfer a sync picks up — including transfers that arrived while the app was closed, which the first sync after a reload reports. A wallet with no saved state doesn't replay its history as received on its first sync.

Both token events carry the same pair of identifiers balances() returns: tokenHash — the canonical 32-byte hash, without a 0x prefix — and tokenAddress, its ERC-20 address. Join a live event back to a balances() snapshot on tokenHash, or key your UI on tokenAddress.

On a sync() that does work, scan:started fires first. scan:complete fires once the new state is saved, so balances() and history() already reflect it. After it, balance:updated fires for each token whose balance changed (a token that is fully spent emits a zero), then note:received for each new incoming transfer. If the scan throws, scan:error fires instead.