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
| Parameter | Type |
|---|---|
commitment | bigint |
message? | string |
Returns
CommitmentProofUnavailableError
Overrides
Error.constructorProperties
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
| Parameter | Type |
|---|---|
targetObject | object |
constructorOpt? | Function |
Returns
void
Inherited from
Error.captureStackTraceprepareStackTrace()
static prepareStackTrace(err, stackTraces): any;Parameters
| Parameter | Type |
|---|---|
err | Error |
stackTraces | CallSite[] |
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTraceisError()
static isError(error): error is Error;Indicates whether the argument provided is a built-in Error instance or not.
Parameters
| Parameter | Type |
|---|---|
error | unknown |
Returns
error is Error
Inherited from
Error.isErrorInterfaces
CachedWhitelistOptions
Options for fetchWhitelistedTokens.
Extends
Properties
| Property | Type | Description | Inherited 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? | number | Freshness window in ms. Default DEFAULT_WHITELIST_TTL_MS. | - |
force? | boolean | Bypass any cached / in-flight value and refetch, then repopulate. | - |
now? | () => number | Clock injection for tests. Defaults to Date.now. | - |
LiveFreshnessProps
Properties
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 Parameter | Default type |
|---|---|
K extends string | number | string | number |
Properties
UseClaimReconcilerArgs
Type Parameters
| Type Parameter | Default type |
|---|---|
K extends string | number | string | number |
Properties
| Property | Type | Description |
|---|---|---|
settlementAddress | string | - |
watchKeys | readonly 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? | string | Anchor 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? | string | Logger 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
| Parameter | Type |
|---|---|
rowKey | K |
claimedAt | number |
Returns
void | Promise<void>
CommitmentTreeState
Properties
Methods
findIndex()
findIndex(commitment): number;Find the leaf index for a previously-deposited commitment. Returns -1 when not present.
Parameters
| Parameter | Type |
|---|---|
commitment | bigint |
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
| Parameter | Type |
|---|---|
commitment | bigint |
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
ConnectWalletPillState
Properties
EdDSAKeyState
Properties
| Property | Type | Description |
|---|---|---|
keyPair | EdDSAKeyPair | null | Derived keypair, or null until the first successful derivation. |
signature | string | null | Original 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. |
isDeriving | boolean | True while a derive() call is in flight. |
error | string | null | Last 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
UseLeafIndexReconcilerArgs
Properties
| Property | Type | Description |
|---|---|---|
notes | readonly LeafIndexNote[] | - |
tree | LeafIndexTree | Live 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? | string | Optional 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
| Parameter | Type |
|---|---|
id | string |
leafIndex | number |
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
UsePhantomDepositDetectorArgs
Properties
| Property | Type | Description |
|---|---|---|
notes | readonly PhantomDepositNote[] | - |
provider | Provider | null | undefined | Provider 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? | number | Only probe notes older than this (ms) so a just-broadcast deposit that’s legitimately mining isn’t judged prematurely. Default 60s. |
intervalMs? | number | Poll 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
| Parameter | Type |
|---|---|
id | string |
Returns
Promise<void>
RelayersState
Properties
| Property | Type | Description |
|---|---|---|
relayers | RelayerInfo[] | - |
selected | RelayerInfo | null | - |
loading | boolean | - |
registryConfigured | boolean | True 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. |
error | string | null | - |
lastRefreshedAt | number | null | Unix-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
| Parameter | Type |
|---|---|
address | string |
Returns
void
RelayersProviderProps
Properties
UseCuratedNetworkTokensResult
Properties
| Property | Type | Description |
|---|---|---|
tokens | TokenInfo[] | 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. |
loading | boolean | True while the first on-chain fetch is in flight (the curated env addresses are shown until it resolves). |
source | TokenListSource | - |
UseNetworkTokensOptions
Properties
| Property | Type | Description |
|---|---|---|
enabled? | boolean | Enable the on-chain fetch. When false, the hook stays on network.tokens. Default true (see useWhitelistedTokens). |
UseTimedRefreshOptions
Properties
StartTimedRefreshOptions
Properties
UseWhitelistedTokensParams
Properties
| Property | Type | Description |
|---|---|---|
provider | Provider | null | undefined | Read provider for the active chain. When null the hook stays on fallback (e.g. SSR / wallet not ready). |
poolAddress | string | - |
settlementAddress | string | - |
fallback | TokenInfo[] | 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? | boolean | Enable the on-chain fetch. When false, the hook stays on fallback and never touches the chain. Default true. |
UseWhitelistedTokensResult
Properties
| Property | Type | Description |
|---|---|---|
tokens | TokenInfo[] | - |
loading | boolean | True while the first (or a refresh) on-chain fetch is in flight. |
error | string | null | - |
source | TokenListSource | - |
refresh | () => void | Re-run the on-chain fetch (e.g. after the owner whitelists a token). |
VaultState
Properties
| Property | Type | Description |
|---|---|---|
notes | StoredNote[] | - |
loaded | boolean | True 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. |
lockedNotes | number | Notes 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
| Parameter | Type |
|---|---|
n | Omit<VaultNote, "id" | "createdAt" | "label" | "chainId" | "leafIndex"> |
Returns
Promise<StoredNote>
remove()
remove(id): Promise<void>;Parameters
| Parameter | Type |
|---|---|
id | string |
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
| Parameter | Type |
|---|---|
id | string |
leafIndex | number |
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
| Parameter | Type |
|---|---|
id | string |
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
| Parameter | Type |
|---|---|
chainId | number |
Returns
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
| Parameter | Type |
|---|---|
input | { commitment: bigint; } |
input.commitment | bigint |
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
| Parameter | Type |
|---|---|
notes | readonly StoredNote[] |
chainId | number |
Returns
CreateVaultProviderResult
Properties
| Property | Type |
|---|---|
VaultProvider | (props) => ReactNode |
Methods
useVault()
useVault(): VaultState;Returns
WalletState
Properties
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 (showingfallback)onchain— resolved from the live pool∩settlement whitelistfallback— 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
| Parameter | Type |
|---|---|
provider | Provider |
poolAddress | string |
settlementAddress | string |
options | CachedWhitelistOptions |
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
| Parameter | Type |
|---|---|
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
| Parameter | Type |
|---|---|
provider | Provider |
poolAddress | string |
settlementAddress | string |
curated | TokenInfo[] |
wethAddress | string |
options | CachedWhitelistOptions |
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
| Parameter | Type |
|---|---|
reason | unknown |
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
| Parameter | Type |
|---|---|
timestampMs | number |
nowMs | number |
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
| Parameter | Type |
|---|---|
__namedParameters | LiveFreshnessProps |
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 Parameter | Default type |
|---|---|
K extends string | number | string | number |
Parameters
| Parameter | Type |
|---|---|
__namedParameters | UseClaimReconcilerArgs<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:
- The hydrate effect raced the user’s click —
readyis still propagating when withdraw/order submit fires. - The
subscribeCommitmentInsertedpolling missed the insert event (etherscontract.onis best-effort over JsonRpcProvider polling; one missed tick = a permanently staleindexRefuntil the user refreshes).tree.refresh()bumps the provider’srefreshNonce, which re-runsloadCommitmentInsertedHistoryand re-populates the sharedindexRef. PollingfindIndexfrom the OLD snapshot closure still sees the new data because the ref is mutated in place across re-renders.
Parameters
| Parameter | Type |
|---|---|
tree | CommitmentTreeState |
commitment | bigint |
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
| Parameter | Type |
|---|---|
failStreak | number |
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
| Parameter | Type |
|---|---|
err | unknown |
source | "wallet" | "rpc" |
Returns
string
useCommitmentTree()
function useCommitmentTree(): CommitmentTreeState;Returns
CommitmentTreeProvider()
function CommitmentTreeProvider(__namedParameters): Element;Parameters
| Parameter | Type |
|---|---|
__namedParameters | CommitmentTreeProviderProps |
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
| Parameter | Type |
|---|---|
network | NetworkConfig |
Returns
useEdDSAKey()
function useEdDSAKey(): EdDSAKeyState;Returns
EdDSAKeyProvider()
function EdDSAKeyProvider(__namedParameters): Element;Parameters
| Parameter | Type |
|---|---|
__namedParameters | { children: ReactNode; } |
__namedParameters.children | ReactNode |
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
| Parameter | Type |
|---|---|
__namedParameters | UseLeafIndexReconcilerArgs |
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
| Parameter | Type |
|---|---|
__namedParameters | UsePhantomDepositDetectorArgs |
Returns
void
useRelayers()
function useRelayers(): RelayersState;Returns
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
| Parameter | Type |
|---|---|
__namedParameters | RelayersProviderProps |
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
| Parameter | Type |
|---|---|
network | NetworkConfig | null | undefined |
Returns
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
| Parameter | Type |
|---|---|
network | NetworkConfig | null | undefined |
options | UseNetworkTokensOptions |
Returns
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
| Parameter | Type |
|---|---|
opts | StartTimedRefreshOptions |
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
| Parameter | Type |
|---|---|
__namedParameters | UseTimedRefreshOptions |
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
| Parameter | Type |
|---|---|
__namedParameters | UseWhitelistedTokensParams |
Returns
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
| Parameter | Type |
|---|---|
opts | CreateVaultProviderOpts |
Returns
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
WalletProvider()
function WalletProvider(__namedParameters): Element;Parameters
| Parameter | Type |
|---|---|
__namedParameters | WalletProviderProps |
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
| Parameter | Type |
|---|---|
addr | string | null | undefined |
Returns
string