Skip to Content
SDK ReferenceTypeScript APIreact
SDK reference (auto)

react

Classes

CommitmentProofUnavailableError

Thrown when the supplied pool has a real CommitmentPool but the commitment isn’t (yet) in the tree — usually means the deposit’s log hasn’t been processed, the tree is mid-sync, or the user spent before reconciliation. Safer than silently generating an empty-tree proof whose root would mismatch the pool’s getLastRoot() at settle time.

Extends

  • Error

Constructors

Constructor
new CommitmentProofUnavailableError(commitment, message?): CommitmentProofUnavailableError;
Parameters
ParameterType
commitmentbigint
message?string
Returns

CommitmentProofUnavailableError

Overrides
Error.constructor

Properties

PropertyModifierTypeDefault valueDescriptionInherited from
stackTraceLimitstaticnumberundefinedThe Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)). The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames.Error.stackTraceLimit
codereadonly"COMMITMENT_PROOF_UNAVAILABLE""COMMITMENT_PROOF_UNAVAILABLE"--
commitmentreadonlybigintundefined--
cause?publicunknownundefined-Error.cause
namepublicstringundefined-Error.name
messagepublicstringundefined-Error.message
stack?publicstringundefined-Error.stack

Methods

captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void;

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a();
Parameters
ParameterType
targetObjectobject
constructorOpt?Function
Returns

void

Inherited from
Error.captureStackTrace
prepareStackTrace()
static prepareStackTrace(err, stackTraces): any;
Parameters
ParameterType
errError
stackTracesCallSite[]
Returns

any

See

https://v8.dev/docs/stack-trace-api#customizing-stack-traces 

Inherited from
Error.prepareStackTrace
isError()
static isError(error): error is Error;

Indicates whether the argument provided is a built-in Error instance or not.

Parameters
ParameterType
errorunknown
Returns

error is Error

Inherited from
Error.isError

Interfaces

CachedWhitelistOptions

Options for fetchWhitelistedTokens.

Extends

Properties

PropertyTypeDescriptionInherited from
overlay?readonly TokenInfo[]Metadata/label overlay — typically parseTokenList(NEXT_PUBLIC_TOKENS). When an on-chain token’s address matches an overlay entry, the overlay’s symbol wins (a deliberate label override, e.g. relabel a deploy’s mock “TestUSDC” to “USDC” without redeploying). Decimals always come from the chain — see below. Overlay also acts as a symbol/decimals fallback when a token’s symbol()/decimals() call reverts (non-standard ERC-20). Addresses are matched case-insensitively.FetchWhitelistedTokensOptions.overlay
ttlMs?numberFreshness window in ms. Default DEFAULT_WHITELIST_TTL_MS.-
force?booleanBypass any cached / in-flight value and refetch, then repopulate.-
now?() => numberClock injection for tests. Defaults to Date.now.-

LiveFreshnessProps

Properties

PropertyTypeDescription
lastRefreshedAtnumber | nullUnix-ms timestamp of the most recent successful refresh, or null while never-fetched.
label?stringLabel prefix shown before the age. Default “live”.
onRefresh?() => voidOptional manual-refresh callback. When provided, renders a small “Refresh” link alongside the age. The polling behind the scenes already keeps data fresh, but the explicit link is useful as an “I changed something elsewhere just now, catch up” escape hatch.
loading?booleanWhen loading is true the age stays visible (so the user doesn’t see a flash of “never”) and a “refreshing…” tag appears next to it.
className?string-

ClaimWatchKey

One row the reconciler watches. rowKey is the app’s identity for the claim — Pay uses recipientRow.rowIndex, Pro could use the order id. Anything that round-trips through onClaimed.

Type Parameters

Type ParameterDefault type
K extends string | numberstring | number

Properties

PropertyTypeDescription
rowKeyK-
secretbigintPer-claim secret from the original ClaimEntry / OrderClaim.
leafIndexnumberLeaf index inside the 16-leaf claims tree (0..15).
claimsRootstringBytes32 hex of the claimsRoot the row was settled under.

UseClaimReconcilerArgs

Type Parameters

Type ParameterDefault type
K extends string | numberstring | number

Properties

PropertyTypeDescription
settlementAddressstring-
watchKeysreadonly ClaimWatchKey<K>[]Rows to watch. App pre-decodes its storage shape into this list. Empty list short-circuits the effect — no subscribe, no query.
settleTxHash?stringAnchor for the historical queryFilter so it doesn’t scan from genesis (most public RPCs cap at ~10k blocks). When omitted or unresolvable, falls back to head − 50k blocks.
label?stringLogger label so multi-app debug output stays readable.

Methods

onClaimed()
onClaimed(rowKey, claimedAt): void | Promise<void>;

Fired for each on-chain PrivateClaim whose nullifier+claimsRoot match a watched row. Errors are swallowed + logged so a single storage failure can’t poison the live subscription.

Parameters
ParameterType
rowKeyK
claimedAtnumber
Returns

void | Promise<void>


CommitmentTreeState

Properties

PropertyTypeDescription
modeMode”live” once the tree is being maintained from on-chain events; “demo” when the supplied poolAddress is the zero address.
readybooleanTrue after the initial event-history fetch completes (or immediately in demo mode). Spend flows that need an authoritative proof should wait on this.
leafCountnumberCurrent leaf count. Demo mode: 0.
hydrationErrorstring | nullNon-null when the last hydrate could not produce a trustworthy tree from the connected network — the node rate-limited us (HTTP 429), was unreachable, returned a leaf set that fails the on-chain root check, or looks like a different fork than the canonical chain. A user-facing string; UIs should surface it (e.g. a banner) so the user can fix their wallet’s network instead of hitting an opaque CommitmentProofUnavailableError at spend time. Null when healthy.

Methods

findIndex()
findIndex(commitment): number;

Find the leaf index for a previously-deposited commitment. Returns -1 when not present.

Parameters
ParameterType
commitmentbigint
Returns

number

tryProofFor()
tryProofFor(commitment): Promise<MerkleProof | null>;

Inclusion proof for the given commitment, sourced from the on-chain tree. Returns null when the commitment isn’t yet in the tree. Use getMerkleProofWithFallback for the common demo-mode-aware case.

Parameters
ParameterType
commitmentbigint
Returns

Promise<MerkleProof | null>

refresh()
refresh(): void;

Force a re-hydrate from loadCommitmentInsertedHistory. Used by UI surfaces that observe a stale state — e.g. a deposit that hasn’t transitioned out of “Confirming” because the ethers contract.on(...) polling missed the event. In demo mode the hydrate effect early-returns so no network work happens, but the bumped nonce still re-fires the effect (a cheap no-op).

Returns

void


CommitmentTreeProviderProps

Properties

PropertyTypeDescription
poolAddressstringOn-chain CommitmentPool the tree mirrors. Pass ZERO_ADDRESS to stay in demo mode (no fetch, no subscription). The provider rebuilds the tree whenever this changes — apps that switch networks supply the active address through their network hook.
fromBlock?string | number | bigintPool deploy block — hydration scans CommitmentInserted from here, not genesis. Omitting it scans from block 0: the loader still chunks the range so it won’t exceed the per-request block-range cap, but it’s wasteful and can hit rate/log limits on a long chain. Accepts a number, a decimal/hex string (env vars arrive as strings), or a bigint.
serverUrl?stringOptional shared-orderbook base URL. When set, hydration fetches leaves from GET /api/commitments first (fast, no client log scan) and falls back to getLogs if the server is unreachable OR its leaves fail the on-chain root check. Omit to use getLogs only.
childrenReactNode-

ConnectWalletPillState

Properties

PropertyTypeDescription
connectedboolean-
shortAccountstring-
walletNamestring | null-
connect() => void-
disconnect() => void-
connectErrorstring | null-
networkLabelstring-
wrongChainboolean-
currentChainIdnumber | nullThe chain the wallet is actually on right now (null when disconnected). Surfaced so a wrong-chain banner can tell the user which network they’re on, not just which one they should be on.
currentChainLabelstring | nullFriendly name for currentChainId when known (e.g. “Localhost”, “Ethereum”); null for unknown chains so the UI shows the raw id.
switchChain() => Promise<void>Ask the wallet to switch to network.chainId. Falls back to wallet_addEthereumChain when the wallet doesn’t have the network configured (EIP-1193 error code 4902). Resolves on user-accept, rejects on user-cancel; the WalletProvider’s chainChanged listener flips wrongChain automatically.

EdDSAKeyState

Properties

PropertyTypeDescription
keyPairEdDSAKeyPair | nullDerived keypair, or null until the first successful derivation.
signaturestring | nullOriginal ECDSA signature used for derivation — kept so flows that also need to wrap material (e.g. vault backup) don’t have to prompt the wallet a second time.
isDerivingbooleanTrue while a derive() call is in flight.
errorstring | nullLast derivation error, surfaced to the UI. Cleared on next call.

Methods

derive()
derive(): Promise<EdDSAKeyPair>;

Trigger derivation via the connected wallet. Resolves to the cached keypair on subsequent calls — never prompts the wallet twice in the same session, even when called concurrently from multiple components. Throws when no wallet is connected.

Returns

Promise<EdDSAKeyPair>


LeafIndexNote

Minimal note shape the reconciler needs: a stable id, the on-chain index it’s waiting for, and the commitment to look up in the tree. App-specific note types are wider; structural typing lets useLeafIndexReconciler work without coupling to any one vault implementation.

Properties

PropertyTypeDescription
idstring-
leafIndexnumber-1 means “deposit confirmed but the CommitmentInserted event hasn’t been reconciled yet”. Anything ≥ 0 is treated as resolved and skipped.
commitmentbigint-

UseLeafIndexReconcilerArgs

Properties

PropertyTypeDescription
notesreadonly LeafIndexNote[]-
treeLeafIndexTreeLive tree state. findIndex must also be referentially stable; the SDK’s CommitmentTreeProvider already returns a useCallback’d value, so passing the provider’s value through unchanged is the easiest way to satisfy this.
label?stringOptional logger label used in the dropped-write warning so multi-app debug logs can tell who rejected. Defaults to “leafIndexReconciler”.

Methods

setLeafIndex()
setLeafIndex(id, leafIndex): Promise<void>;

Atomic id → leafIndex updater. Must be referentially stable (wrap in useCallback with a stable dep set) — the hook lists it in the effect deps, so a fresh identity every render would retrigger the reconciliation pass even when nothing changed.

Parameters
ParameterType
idstring
leafIndexnumber
Returns

Promise<void>


PhantomDepositNote

Minimal note shape the phantom detector needs. App note types are wider; structural typing keeps the hook decoupled from any one vault implementation.

Properties

PropertyTypeDescription
idstring-
leafIndexnumber-1 = deposit not yet reconciled to a leaf. ≥0 = on-chain, skipped.
txHash?stringDeposit tx hash. Without it the receipt can’t be checked, so the note is skipped (left Pending).
createdAtnumberms epoch the note was added.
status?"failed"Already-decided verdict; "failed" notes are skipped.

UsePhantomDepositDetectorArgs

Properties

PropertyTypeDescription
notesreadonly PhantomDepositNote[]-
providerProvider | null | undefinedProvider used to read tx receipts — use the public / authoritative node, since a reverted receipt is a global fact independent of the wallet’s view. null/undefined disables the detector.
staleAfterMs?numberOnly probe notes older than this (ms) so a just-broadcast deposit that’s legitimately mining isn’t judged prematurely. Default 60s.
intervalMs?numberPoll cadence (ms). Default 30s — receipts are cheap but a reverted tx is terminal, so there’s no need to hammer.
label?string-

Methods

markFailed()
markFailed(id): Promise<void>;

Flags a note whose deposit tx is proven reverted. Must be referentially stable-ish; it’s read through a ref so identity churn doesn’t restart the poll. Idempotent on the vault side.

Parameters
ParameterType
idstring
Returns

Promise<void>


RelayersState

Properties

PropertyTypeDescription
relayersRelayerInfo[]-
selectedRelayerInfo | null-
loadingboolean-
registryConfiguredbooleanTrue when an on-chain registry IS configured for the network. False for unconfigured / placeholder addresses (e.g. a demo network with a zero-address relayer registry). UI branches on !registryConfigured to render a “no registry” state instead of an empty-list fallback.
errorstring | null-
lastRefreshedAtnumber | nullUnix-ms timestamp of the most recent successful fetch, or null until the first one completes. Surface this in UI to show “live • Xs ago” so the polling cadence introduced by useTimedRefresh is visible to the user — otherwise they have no signal that the data isn’t stale. Updated on every successful refresh, NOT on failures (so the displayed age stays accurate during an RPC outage rather than freezing optimistically).

Methods

refresh()
refresh(): void;
Returns

void

select()
select(address): void;
Parameters
ParameterType
addressstring
Returns

void


RelayersProviderProps

Properties

PropertyTypeDescription
registryAddressstringRelayerRegistry address for the active network. The provider treats unconfigured (isConfiguredAddress false) addresses as “no registry” — render an empty list with registryConfigured flipped so the UI can branch on that.
childrenReactNode-

UseCuratedNetworkTokensResult

Properties

PropertyTypeDescription
tokensTokenInfo[]The curated network.tokens list (order + display metadata preserved) with addresses and decimals overlaid from the on-chain Pool∩Settlement whitelist. Same shape as network.tokens, so existing .find(t => t.symbol === …) / .map call sites are a drop-in swap.
loadingbooleanTrue while the first on-chain fetch is in flight (the curated env addresses are shown until it resolves).
sourceTokenListSource-

UseNetworkTokensOptions

Properties

PropertyTypeDescription
enabled?booleanEnable the on-chain fetch. When false, the hook stays on network.tokens. Default true (see useWhitelistedTokens).

UseTimedRefreshOptions

Properties

PropertyTypeDescription
refresh() => void | Promise<void>Callback to invoke on each tick + on visibility change. Identity-stable across renders is preferred (avoids needless effect work), but the hook pins the latest reference in a ref, so an inline arrow function will still see updates from closure without re-arming the timer.
intervalMsnumberPolling interval in milliseconds. Choose with the consumer’s freshness needs in mind: a list that operators expect to see new entries in within ~30s can poll at 15–30s; a status the user is actively waiting on (e.g. just-issued cert) can poll at 5–10s and stop via enabled once terminal.
enabled?booleanDisable polling without unmounting. Use this to stop polling once the watched state reaches a terminal value (e.g. cert verified, approval granted) so we don’t keep hammering the RPC forever on a tab the user left open. Default true.
refreshOnVisible?booleanAlso call refresh immediately when the document becomes visible. Critical for the “user came back to this tab after doing something in another tab” UX — the manual Refresh button this replaces existed specifically for that case. Default true.

StartTimedRefreshOptions

Properties

PropertyTypeDescription
refresh() => void | Promise<void>-
intervalMsnumber-
refreshOnVisibleboolean-
setInterval?(cb, ms) => numberInjected for testability — defaults to the real browser primitives.
clearInterval?(id) => void-
isHidden?() => boolean-
addVisibilityListener?(cb) => () => void-

UseWhitelistedTokensParams

Properties

PropertyTypeDescription
providerProvider | null | undefinedRead provider for the active chain. When null the hook stays on fallback (e.g. SSR / wallet not ready).
poolAddressstring-
settlementAddressstring-
fallbackTokenInfo[]Env-derived list (parseTokenList(NEXT_PUBLIC_TOKENS)). Serves two roles: the overlay that relabels on-chain tokens and backstops reverted symbol()/decimals() reads, and the fallback rendered immediately and whenever the on-chain fetch can’t produce a list. Pass the non-native list — the native-ETH alias (if wanted) is the caller’s concern.
enabled?booleanEnable the on-chain fetch. When false, the hook stays on fallback and never touches the chain. Default true.

UseWhitelistedTokensResult

Properties

PropertyTypeDescription
tokensTokenInfo[]-
loadingbooleanTrue while the first (or a refresh) on-chain fetch is in flight.
errorstring | null-
sourceTokenListSource-
refresh() => voidRe-run the on-chain fetch (e.g. after the owner whitelists a token).

VaultState

Properties

PropertyTypeDescription
notesStoredNote[]-
loadedbooleanTrue once the storage adapter has loaded existing notes. UI surfaces a brief loading state to avoid flashing “vault empty” on a refresh of a page that actually has notes.
lockedNotesnumberNotes present in the backing store that the last hydrate could NOT recover — encrypted rows whose decryption key isn’t available yet this session (see NoteStorageAdapter.lockedCount). Apps surface an “unlock with your wallet” affordance when > 0; always 0 for adapters without a locked concept.

Methods

add()
add(n): Promise<StoredNote>;
Parameters
ParameterType
nOmit<VaultNote, "id" | "createdAt" | "label" | "chainId" | "leafIndex">
Returns

Promise<StoredNote>

remove()
remove(id): Promise<void>;
Parameters
ParameterType
idstring
Returns

Promise<void>

setLeafIndex()
setLeafIndex(id, leafIndex): Promise<void>;

Patch the leafIndex on a stored note. Used by the reconciler to back-fill the tree position once the deposit’s CommitmentInserted event lands. Idempotent: if the note is already at the supplied index, returns immediately with zero IDB writes and no re-render; otherwise persists via adapter.put and triggers one re-render of vault consumers.

Parameters
ParameterType
idstring
leafIndexnumber
Returns

Promise<void>

markFailed()
markFailed(id): Promise<void>;

Flag a note as a failed/phantom deposit (its tx reverted, so the commitment was never inserted). Persisted so the verdict survives reloads; the UI then filters it out instead of showing it as Pending forever. Idempotent: a note already "failed" is a no-op. Like setLeafIndex, guarded against the removed/chain-switch races so a stale write can’t resurrect or cross-write a note.

Parameters
ParameterType
idstring
Returns

Promise<void>


CreateVaultProviderOpts

Methods

useChainId()
useChainId(): number;

Hook returning the active chain id. Called once per render inside the provider; consumers can return a constant (env-driven, single-network apps) or thread an active-network context value (multi-network apps).

Returns

number

useAdapter()
useAdapter(chainId): NoteStorageAdapter;

Hook returning the storage adapter for the active chainId. Called inside the provider as a hook — implementations are free to call any other hook (useWallet, useMemo, etc.) so long as the call order stays stable across renders. The returned reference’s identity matters: the hydrate effect retriggers when it changes, so wrap creation in useMemo.

Parameters
ParameterType
chainIdnumber
Returns

NoteStorageAdapter

makeId()
makeId(input): string;

Derive a stable id for a freshly-added note. Pay uses a content-addressed idForCommitment(commitment); Pro uses a random UUID. The factory passes the new note’s commitment so content-addressed callers don’t need extra inputs.

Parameters
ParameterType
input{ commitment: bigint; }
input.commitmentbigint
Returns

string

filterHydrated()?
optional filterHydrated(notes, chainId): StoredNote[];

Optional post-load filter applied to hydrated notes before they hit React state. Pay’s adapters already filter by chainId internally (folder via opts, per-chain IDB DB name), so Pay omits this; Pro filters here because its single IDB DB is shared across chainIds.

Parameters
ParameterType
notesreadonly StoredNote[]
chainIdnumber
Returns

StoredNote[]


CreateVaultProviderResult

Properties

PropertyType
VaultProvider(props) => ReactNode

Methods

useVault()
useVault(): VaultState;
Returns

VaultState


WalletState

Properties

PropertyTypeDescription
accountstring | nullConnected EOA, lowercased. Null when disconnected.
chainIdnumber | nullChain id reported by the wallet. May differ from network.chainId while the user is on the wrong chain.
signerSigner | nullWallet-backed signer for transactions. Null when disconnected.
providerBrowserProvider | nullBrowser provider wrapping the wallet’s EIP-1193.
readProviderProviderRead provider for per-user view calls (your balance, your claim status — data scoped to the connected account). Always non-null. When a wallet is connected on the right chain this is an InjectedMulticallProvider reading through the user’s own node (with Multicall3 batching); otherwise it’s a public-RPC JsonRpcProvider fallback built from network.rpcUrl. Drop-in either way — pass it to new Contract. For correctness-critical, globally-identical reads the rule is nuanced: the commitment tree DOES read here (to dodge the public RPC’s rate limits), but only because it independently re-verifies the result on-chain (isKnownRoot + completeness gate) AND best-effort cross-checks the root against rpcProvider — so a forked/stale wallet node fails the gate or trips the cross-check instead of being trusted. Reads WITHOUT such a guard (e.g. identity-gate verification) must still use rpcProvider, since the user’s node can be a chainId- spoofing fork or a broken/unauthorized endpoint serving stale data.
readSource"wallet" | "rpc"Which node the current readProvider reads from — "wallet" (the user’s connected node) or "rpc" (public fallback). Consumers that read through readProvider use this to decide whether a canonical cross-check against rpcProvider is warranted (only when "wallet").
rpcProviderJsonRpcProviderAlways-public JsonRpcProvider built from network.rpcUrl — the app’s authoritative node. Uses: 1. Write preflight (gas/fee estimation via runWrite) so a throttled wallet RPC can’t gate the estimate; the tx still broadcasts through the connected wallet. 2. Unguarded correctness-critical reads (identity gate) that must not trust a forked/broken wallet node. 3. The commitment tree’s best-effort canonical root cross-check — a guard ON TOP of its wallet-node reads, not the primary source. Guarantees agreement with the node settlement trusts.
walletNamestring | nullBest-effort wallet vendor name; null when disconnected.
connectErrorstring | nullLast error from a connect() attempt — covers both the “no wallet detected” case and user rejections.
connect() => Promise<void>Trigger the wallet’s account-request flow.
disconnect() => voidDrop the connected account from app state. (Most wallets don’t expose a programmatic disconnect; this clears local state only.)

Type Aliases

LeafIndexTree

type LeafIndexTree = Pick<CommitmentTreeState, "ready" | "mode" | "leafCount" | "findIndex" | "refresh">;

Subset of CommitmentTreeState the reconciler reads. Picked rather than redefined so a future field addition on the provider doesn’t drift this contract.


TokenListSource

type TokenListSource = "loading" | "onchain" | "fallback";

Where the returned token list came from:

  • loading — the on-chain fetch is in flight (showing fallback)
  • onchain — resolved from the live pool∩settlement whitelist
  • fallback — using the env list (fetch disabled, unconfigured, errored, or the chain returned no usable tokens)

VaultNote

type VaultNote = StoredNote;

A note in the user’s local vault. The full CommitmentNote is carried so spending circuits (authorize / claim) can spend this note later without re-deriving its preimage from on-chain data. Persisted via the supplied adapter — survives page reload.

Variables

DEFAULT_WHITELIST_TTL_MS

const DEFAULT_WHITELIST_TTL_MS: 60000 = 60_000;

Default freshness window. A minute is plenty to collapse the burst of reads from one screen while still picking up an admin whitelist change soon after (or instantly via invalidateWhitelistCache).

Functions

fetchWhitelistedTokensCached()

function fetchWhitelistedTokensCached( provider, poolAddress, settlementAddress, options?): Promise<TokenInfo[]>;

fetchWhitelistedTokens with the process-wide cache + in-flight de-duplication described in the module header. Pass force: true (or call invalidateWhitelistCache) to refetch after a whitelist write.

Parameters

ParameterType
providerProvider
poolAddressstring
settlementAddressstring
optionsCachedWhitelistOptions

Returns

Promise<TokenInfo[]>


invalidateWhitelistCache()

function invalidateWhitelistCache(poolAddress?, settlementAddress?): void;

Drop cached whitelist data so the next read refetches. With both addresses, clears just that pair; with no args, clears everything (e.g. on a network switch, or after an admin whitelist write).

Parameters

ParameterType
poolAddress?string
settlementAddress?string

Returns

void


resolveCuratedTokensCached()

function resolveCuratedTokensCached( provider, poolAddress, settlementAddress, curated, wethAddress, options?): Promise<TokenInfo[]>;

Lib-side (non-hook) equivalent of useCuratedNetworkTokens: the curated token list with addresses + decimals overlaid from the on-chain Pool∩Settlement whitelist. For async money flows (deposit / settle / withdraw) that can’t call the React hook but still must resolve a token’s real on-chain address/decimals instead of the env sentinel.

Shares the session whitelist cache, so calling it from a flow that also rendered a hook-backed picker costs no extra RPC. The native “ETH” entry resolves via wethAddress; others match by symbol.

Parameters

ParameterType
providerProvider
poolAddressstring
settlementAddressstring
curatedTokenInfo[]
wethAddressstring
optionsCachedWhitelistOptions

Returns

Promise<TokenInfo[]>


isChunkLoadError()

function isChunkLoadError(reason): boolean;

True for the chunk-load failures Next/Turbopack/webpack surface — by error name, or by the message text when the name was lost crossing an unhandledrejection boundary.

Parameters

ParameterType
reasonunknown

Returns

boolean


ChunkReloadGuard()

function ChunkReloadGuard(): null;

Mount once near the root of a Next App Router layout (inside <body>). Renders nothing; installs window error listeners that turn a stale-chunk reload loop into a single recovering reload.

Returns

null


formatAge()

function formatAge(timestampMs, nowMs): string;

Render an age like “5s ago” / “3m ago” / “2h ago” from a Unix-ms timestamp. Pure for unit tests.

Parameters

ParameterType
timestampMsnumber
nowMsnumber

Returns

string


LiveFreshness()

function LiveFreshness(__namedParameters): Element;

Tiny status pill that surfaces the freshness of a polled dataset. Re-renders the age string every second so “5s ago” visibly counts up to ”30s ago” between polls — gives the user visceral confirmation that the data IS live.

Pair with a provider that exposes lastRefreshedAt (e.g. RelayersProvider). Without this badge the user has no signal that data is auto-refreshing and may distrust it.

Parameters

ParameterType
__namedParametersLiveFreshnessProps

Returns

Element


useClaimReconciler()

function useClaimReconciler<K>(__namedParameters): void;

Watches PrivateClaim events on a settlement contract and fires onClaimed(rowKey, claimedAt) once per matched row. Subscribes for live events AND queries history once on mount so a page revisit picks up claims that completed before the user opened the dashboard.

Type Parameters

Type ParameterDefault type
K extends string | numberstring | number

Parameters

ParameterType
__namedParametersUseClaimReconcilerArgs<K>

Returns

void


getMerkleProofWithFallback()

function getMerkleProofWithFallback( tree, commitment, fallback): Promise<{ merkleProof: MerkleProof; leafIndex: number; }>;

Resolve a Merkle proof for a note’s commitment: prefer the on-chain tree, fall back to the empty-tree shortcut only in demo mode. In live mode a missing commitment throws so the UI surfaces “wait for confirmation” instead of producing an invalid-root proof that would fail at settle time.

When the live tree returns null on the first try, force one re-hydrate and poll the local index for up to ~7.5 s before giving up. This covers two real failure modes that used to surface as a hard CommitmentProofUnavailableError even when the commitment was already on-chain:

  1. The hydrate effect raced the user’s click — ready is still propagating when withdraw/order submit fires.
  2. The subscribeCommitmentInserted polling missed the insert event (ethers contract.on is best-effort over JsonRpcProvider polling; one missed tick = a permanently stale indexRef until the user refreshes). tree.refresh() bumps the provider’s refreshNonce, which re-runs loadCommitmentInsertedHistory and re-populates the shared indexRef. Polling findIndex from the OLD snapshot closure still sees the new data because the ref is mutated in place across re-renders.

Parameters

ParameterType
treeCommitmentTreeState
commitmentbigint
fallback() => Promise<{ merkleProof: MerkleProof; leafIndex: number; }>

Returns

Promise<{ merkleProof: MerkleProof; leafIndex: number; }>


rehydrateBackoffMs()

function rehydrateBackoffMs(failStreak): number;

Backoff (ms) before a refresh()-driven re-hydrate may re-run, given the consecutive-failure streak. Streak 0 (healthy, no failures yet) yields 0.5s — only enough to debounce bursts. Each subsequent failure doubles it: streak 1 → 1s, streak 2 → 2s, … up to a 30s ceiling (reached at streak 6). Exported for unit tests.

Parameters

ParameterType
failStreaknumber

Returns

number


describeHydrationError()

function describeHydrationError(err, source): string;

Map a hydrate failure to a user-facing, actionable message. Verification failures (HydrationUnverifiedError) carry their own message and are handled at the catch site; this classifies the REMAINING transport errors — an HTTP 429 / throttle gets the rate-limit message, anything else falls back to a generic “couldn’t load” with the raw reason. source names whether the offending node is the user’s wallet RPC (actionable: switch it) or the app’s public RPC. Exported for tests.

Parameters

ParameterType
errunknown
source"wallet" | "rpc"

Returns

string


useCommitmentTree()

function useCommitmentTree(): CommitmentTreeState;

Returns

CommitmentTreeState


CommitmentTreeProvider()

function CommitmentTreeProvider(__namedParameters): Element;

Parameters

ParameterType
__namedParametersCommitmentTreeProviderProps

Returns

Element


useConnectWalletPill()

function useConnectWalletPill(network): ConnectWalletPillState;

Bind useWallet() + the host app’s NetworkConfig to the prop shape ConnectWalletPillView (in @zkscatter/ui) expects. Apps spread the result directly onto the view, so the per-app wrapper collapses to a one-liner instead of repeating the same glue.

Parameters

ParameterType
networkNetworkConfig

Returns

ConnectWalletPillState


useEdDSAKey()

function useEdDSAKey(): EdDSAKeyState;

Returns

EdDSAKeyState


EdDSAKeyProvider()

function EdDSAKeyProvider(__namedParameters): Element;

Parameters

ParameterType
__namedParameters{ children: ReactNode; }
__namedParameters.childrenReactNode

Returns

Element


useLeafIndexReconciler()

function useLeafIndexReconciler(__namedParameters): void;

Back-fills leafIndex on vault notes once the matching CommitmentInserted event lands in the live tree. Pure side-effect hook — no UI; pair with whatever the app uses to surface vault state.

Without this, every spend path that gates on leafIndex >= 0 (Pay’s realSettle, Pro’s settle / cancel) leaves a freshly- deposited or change-UTXO note unspendable until the user manually refreshes.

Parameters

ParameterType
__namedParametersUseLeafIndexReconcilerArgs

Returns

void


usePhantomDepositDetector()

function usePhantomDepositDetector(__namedParameters): void;

Detects and flags phantom deposits: pending notes (leafIndex < 0) whose deposit transaction reverted, so the commitment was never inserted and the note can never reconcile to a leaf. Such a note otherwise sits as “Pending” forever; flagging it "failed" lets the UI filter it out.

SAFETY — only a receipt.status === 0 (reverted) verdict triggers a flag. A null receipt (still pending or dropped — could yet mine) and a status === 1 receipt (succeeded, just not indexed yet) are deliberately left untouched: flagging either could strand a real, recoverable deposit (its spendable secret would be hidden). A reverted tx, by contrast, consumed its nonce and can never insert the commitment, and moved no funds — so the verdict is definitive.

Parameters

ParameterType
__namedParametersUsePhantomDepositDetectorArgs

Returns

void


useRelayers()

function useRelayers(): RelayersState;

Returns

RelayersState


RelayersProvider()

function RelayersProvider(__namedParameters): Element;

Loads the relayer registry, exposes the list + a current selection, and auto-picks the first online relayer (or the first relayer if none are online). Apps thin-wrap this to source registryAddress from their own network config.

Parameters

ParameterType
__namedParametersRelayersProviderProps

Returns

Element


useCuratedNetworkTokens()

function useCuratedNetworkTokens(network): UseCuratedNetworkTokensResult;

Curated token list with addresses + decimals sourced from the on-chain whitelist instead of NEXT_PUBLIC_* env. The goal: a team deployment adds tokens via setTokenWhitelist and the wallet / balance surfaces resolve them — with the right decimals — without an env edit, while keeping LAUNCH_TOKENS’ display metadata (name, markets, order, native-ness).

Native ETH resolves via the WETH address (on-chain it is “WETH”, sharing the address); other tokens match by symbol. Tokens absent from the whitelist keep their curated (possibly zero) address and render as “not configured” at the call site.

Shared by the Pay wallet and Pro workbench. Must be used within the SDK <WalletProvider> (every app already is). network is nullable so a caller that hasn’t resolved the active network yet gets a graceful curated/empty list with the fetch disabled.

Parameters

ParameterType
networkNetworkConfig | null | undefined

Returns

UseCuratedNetworkTokensResult


useMounted()

function useMounted(): boolean;

Returns false on the server render and the very first client paint, then flips to true after useEffect runs. Use this to gate any rendering that depends on Date.now(), the browser’s current locale, IndexedDB state, or other values the server can’t see — without it, Next would emit a hydration mismatch when the server-side string differs from the post-mount client string.

const mounted = useMounted(); return <span>{mounted ? formatRelative(t) : formatAbsoluteUTC(t)}</span>;

Returns

boolean


useNetworkTokens()

function useNetworkTokens(network, options?): UseWhitelistedTokensResult;

App-convenience wrapper over useWhitelistedTokens: pulls the read provider from the wallet context and the pool/settlement addresses + env fallback from a NetworkConfig, so an app component is a single line:

const { tokens, loading } = useNetworkTokens(DEMO_NETWORK);

Returns the on-chain Pool∩Settlement whitelist (tokens usable for the full deposit→settle→claim flow), with network.tokens (NEXT_PUBLIC_TOKENS) as the metadata overlay + fallback. Must be used within the SDK <WalletProvider> (every app already is). For an admin “which tokens are whitelisted anywhere” view, fetch the union directly instead — this returns the intersection.

network is accepted as nullable so a caller that hasn’t resolved the active network yet (initialization / disconnected wallet) gets a graceful empty list with the fetch disabled, instead of a TypeError.

Parameters

ParameterType
networkNetworkConfig | null | undefined
optionsUseNetworkTokensOptions

Returns

UseWhitelistedTokensResult


startTimedRefresh()

function startTimedRefresh(opts): () => void;

Pure scheduler the React hook delegates to. Extracted so the tick/visibility behaviour can be unit-tested without spinning up a DOM — every browser primitive is injectable. Returns a teardown that cancels the interval + removes the listener.

Parameters

ParameterType
optsStartTimedRefreshOptions

Returns

() => void


useTimedRefresh()

function useTimedRefresh(__namedParameters): void;

Periodically calls refresh + also on document visibility → visible. Skips the call while the document is hidden so a background tab doesn’t poll the RPC every N seconds for hours.

Why polling instead of contract.on event subscriptions: ethers v6’s filter-subscription path is unreliable on anvil (it silently stops firing — repo memory feedback_contract_on_unreliable) and the consumers here read view functions or run aggregate queries that don’t have a single corresponding event anyway (relayer list is composed of N reads; approval state is one struct read; identity is a view call into IdentityGate). A uniform polling cadence is simpler, observable, and easy to reason about for ops.

Parameters

ParameterType
__namedParametersUseTimedRefreshOptions

Returns

void


useWhitelistedTokens()

function useWhitelistedTokens(__namedParameters): UseWhitelistedTokensResult;

Live token list backed by the on-chain whitelist, with the env list as overlay + fallback. The goal: a team deployment adds tokens via setTokenWhitelist and every app surfaces them with no NEXT_PUBLIC_TOKENS edit — while a missing/old chain still renders the env list instead of an empty picker.

Renders fallback first (no empty flash), then swaps to the on-chain intersection once it resolves. The caller layers withNativeEthAlias on tokens if it wants the synthetic ETH entry.

Parameters

ParameterType
__namedParametersUseWhitelistedTokensParams

Returns

UseWhitelistedTokensResult


createVaultProvider()

function createVaultProvider(opts): CreateVaultProviderResult;

Build a vault Provider + hook pair scoped to one app. The factory consolidates the race-safe vault primitives (notesRef mirror, removedIdsRef synchronous set, generationRef chain-switch guard, setLeafIndex with pre/post-await guards) so app-side vault.tsx files reduce to “wire chainId + adapter + id-maker, re-export”.

Parameters

ParameterType
optsCreateVaultProviderOpts

Returns

CreateVaultProviderResult


useWallet()

function useWallet(): WalletState;

Read the wallet state. Throws when called outside a <WalletProvider> so missing-provider mistakes surface immediately instead of silently degrading.

Returns

WalletState


WalletProvider()

function WalletProvider(__namedParameters): Element;

Parameters

ParameterType
__namedParametersWalletProviderProps

Returns

Element


shortAddr()

function shortAddr(addr): string;

Truncated address helper for display (0xabcd…1234). Returns empty string for empty input so callers can chain without guards.

Parameters

ParameterType
addrstring | null | undefined

Returns

string

Last updated on