core
Classes
InjectedMulticallProvider
A read provider backed by the user’s injected wallet (MetaMask et al.)
that transparently coalesces concurrent view reads into a single
Multicall3 aggregate3 request.
Why this exists: ethers forces BrowserProvider to batchMaxCount: 1,
so EIP-1193 cannot batch JSON-RPC calls — every contract.view()
becomes its own window.ethereum.request, i.e. its own hit on the
wallet’s (often rate-limited public) RPC. Pointing app reads at the
wallet without batching would multiply traffic by N and trip
MetaMask’s -32002 circuit breaker. Overriding call() to gather a
microtask-window of view reads and fire them as ONE aggregate3
keeps the wallet-RPC cost at ~1 request per refresh, regardless of
how many fields a page reads.
Drop-in for JsonRpcProvider: callers keep doing
new Contract(addr, abi, readProvider) and contract.foo().
Non-view calls, calls with an explicit from/value/blockTag, and
chains without the Multicall3 predeploy all fall back to a plain
per-call eth_call (a reverting view still throws its real revert
reason).
Caveat: a batched sub-call executes with msg.sender = Multicall3, not
the zero address an unbatched from-less eth_call uses. This only
matters for msg.sender-sensitive view functions — pass an explicit
from for those and isBatchableView sends them unbatched.
Extends
BrowserProvider
Constructors
Constructor
new InjectedMulticallProvider(
eip1193,
network?,
opts?): InjectedMulticallProvider;Parameters
| Parameter | Type |
|---|---|
eip1193 | Eip1193Provider |
network? | Networkish |
opts? | { stallMs?: number; } |
opts.stallMs? | number |
Returns
Overrides
ethers.BrowserProvider.constructorAccessors
provider
Get Signature
get provider(): this;Returns this, to allow an AbstractProvider to implement
the [[ContractRunner]] interface.
Returns
this
Inherited from
ethers.BrowserProvider.providerplugins
Get Signature
get plugins(): AbstractProviderPlugin[];Returns all the registered plug-ins.
Returns
AbstractProviderPlugin[]
Inherited from
ethers.BrowserProvider.pluginsdisableCcipRead
Get Signature
get disableCcipRead(): boolean;Prevent any CCIP-read operation, regardless of whether requested
in a [[call]] using enableCcipRead.
Returns
boolean
Set Signature
set disableCcipRead(value): void;Parameters
| Parameter | Type |
|---|---|
value | boolean |
Returns
void
Inherited from
ethers.BrowserProvider.disableCcipReaddestroyed
Get Signature
get destroyed(): boolean;If this provider has been destroyed using the [[destroy]] method.
Once destroyed, all resources are reclaimed, internal event loops and timers are cleaned up and no further requests may be sent to the provider.
Returns
boolean
Inherited from
ethers.BrowserProvider.destroyedpaused
Get Signature
get paused(): boolean;Whether the provider is currently paused.
A paused provider will not emit any events, and generally should not make any requests to the network, but that is up to sub-classes to manage.
Setting paused = true is identical to calling .pause(false),
which will buffer any events that occur while paused until the
provider is unpaused.
Returns
boolean
Set Signature
set paused(pause): void;Parameters
| Parameter | Type |
|---|---|
pause | boolean |
Returns
void
Inherited from
ethers.BrowserProvider.pausedproviderInfo
Get Signature
get providerInfo(): Eip6963ProviderInfo | null;Returns
Eip6963ProviderInfo | null
Inherited from
ethers.BrowserProvider.providerInfo_network
Get Signature
get _network(): Network;Gets the [[Network]] this provider has committed to. On each call, the network is detected, and if it has changed, the call will reject.
Returns
Network
Inherited from
ethers.BrowserProvider._networkready
Get Signature
get ready(): boolean;Returns true only if the [[_start]] has been called.
Returns
boolean
Inherited from
ethers.BrowserProvider.readypollingInterval
Get Signature
get pollingInterval(): number;The polling interval (default: 4000 ms)
Returns
number
Set Signature
set pollingInterval(value): void;Parameters
| Parameter | Type |
|---|---|
value | number |
Returns
void
Inherited from
ethers.BrowserProvider.pollingIntervalMethods
call()
call(tx): Promise<string>;Parameters
| Parameter | Type |
|---|---|
tx | TransactionRequest |
Returns
Promise<string>
Overrides
ethers.BrowserProvider.callattachPlugin()
attachPlugin(plugin): this;Attach a new plug-in.
Parameters
| Parameter | Type |
|---|---|
plugin | AbstractProviderPlugin |
Returns
this
Inherited from
ethers.BrowserProvider.attachPlugingetPlugin()
getPlugin<T>(name): T | null;Get a plugin by name.
Type Parameters
| Type Parameter | Default type |
|---|---|
T extends AbstractProviderPlugin | AbstractProviderPlugin |
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
T | null
Inherited from
ethers.BrowserProvider.getPluginccipReadFetch()
ccipReadFetch(
tx,
calldata,
urls): Promise<string | null>;Resolves to the data for executing the CCIP-read operations.
Parameters
| Parameter | Type |
|---|---|
tx | PerformActionTransaction |
calldata | string |
urls | string[] |
Returns
Promise<string | null>
Inherited from
ethers.BrowserProvider.ccipReadFetch_wrapBlock()
_wrapBlock(value, network): Block;Provides the opportunity for a sub-class to wrap a block before returning it, to add additional properties or an alternate sub-class of [[Block]].
Parameters
| Parameter | Type |
|---|---|
value | BlockParams |
network | Network |
Returns
Block
Inherited from
ethers.BrowserProvider._wrapBlock_wrapLog()
_wrapLog(value, network): Log;Provides the opportunity for a sub-class to wrap a log before returning it, to add additional properties or an alternate sub-class of [[Log]].
Parameters
| Parameter | Type |
|---|---|
value | LogParams |
network | Network |
Returns
Log
Inherited from
ethers.BrowserProvider._wrapLog_wrapTransactionReceipt()
_wrapTransactionReceipt(value, network): TransactionReceipt;Provides the opportunity for a sub-class to wrap a transaction receipt before returning it, to add additional properties or an alternate sub-class of [[TransactionReceipt]].
Parameters
| Parameter | Type |
|---|---|
value | TransactionReceiptParams |
network | Network |
Returns
TransactionReceipt
Inherited from
ethers.BrowserProvider._wrapTransactionReceipt_wrapTransactionResponse()
_wrapTransactionResponse(tx, network): TransactionResponse;Provides the opportunity for a sub-class to wrap a transaction response before returning it, to add additional properties or an alternate sub-class of [[TransactionResponse]].
Parameters
| Parameter | Type |
|---|---|
tx | TransactionResponseParams |
network | Network |
Returns
TransactionResponse
Inherited from
ethers.BrowserProvider._wrapTransactionResponsegetBlockNumber()
getBlockNumber(): Promise<number>;Get the current block number.
Returns
Promise<number>
Inherited from
ethers.BrowserProvider.getBlockNumber_getAddress()
_getAddress(address): string | Promise<string>;Returns or resolves to the address for %%address%%, resolving ENS names and [[Addressable]] objects and returning if already an address.
Parameters
| Parameter | Type |
|---|---|
address | AddressLike |
Returns
string | Promise<string>
Inherited from
ethers.BrowserProvider._getAddress_getBlockTag()
_getBlockTag(blockTag?): string | Promise<string>;Returns or resolves to a valid block tag for %%blockTag%%, resolving negative values and returning if already a valid block tag.
Parameters
| Parameter | Type |
|---|---|
blockTag? | BlockTag |
Returns
string | Promise<string>
Inherited from
ethers.BrowserProvider._getBlockTag_getFilter()
_getFilter(filter): PerformActionFilter | Promise<PerformActionFilter>;Returns or resolves to a filter for %%filter%%, resolving any ENS names or [[Addressable]] object and returning if already a valid filter.
Parameters
| Parameter | Type |
|---|---|
filter | Filter | FilterByBlockHash |
Returns
PerformActionFilter | Promise<PerformActionFilter>
Inherited from
ethers.BrowserProvider._getFilter_getTransactionRequest()
_getTransactionRequest(_request): PerformActionTransaction | Promise<PerformActionTransaction>;Returns or resolves to a transaction for %%request%%, resolving any ENS names or [[Addressable]] and returning if already a valid transaction.
Parameters
| Parameter | Type |
|---|---|
_request | TransactionRequest |
Returns
PerformActionTransaction | Promise<PerformActionTransaction>
Inherited from
ethers.BrowserProvider._getTransactionRequestgetNetwork()
getNetwork(): Promise<Network>;Get the connected [[Network]].
Returns
Promise<Network>
Inherited from
ethers.BrowserProvider.getNetworkgetFeeData()
getFeeData(): Promise<FeeData>;Get the best guess at the recommended [[FeeData]].
Returns
Promise<FeeData>
Inherited from
ethers.BrowserProvider.getFeeDataestimateGas()
estimateGas(_tx): Promise<bigint>;Estimates the amount of gas required to execute %%tx%%.
Parameters
| Parameter | Type |
|---|---|
_tx | TransactionRequest |
Returns
Promise<bigint>
Inherited from
ethers.BrowserProvider.estimateGasgetBalance()
getBalance(address, blockTag?): Promise<bigint>;Get the account balance (in wei) of %%address%%. If %%blockTag%% is specified and the node supports archive access for that %%blockTag%%, the balance is as of that [[BlockTag]].
Parameters
| Parameter | Type |
|---|---|
address | AddressLike |
blockTag? | BlockTag |
Returns
Promise<bigint>
Note
On nodes without archive access enabled, the %%blockTag%% may be silently ignored by the node, which may cause issues if relied on.
Inherited from
ethers.BrowserProvider.getBalancegetTransactionCount()
getTransactionCount(address, blockTag?): Promise<number>;Get the number of transactions ever sent for %%address%%, which
is used as the nonce when sending a transaction. If
%%blockTag%% is specified and the node supports archive access
for that %%blockTag%%, the transaction count is as of that
[[BlockTag]].
Parameters
| Parameter | Type |
|---|---|
address | AddressLike |
blockTag? | BlockTag |
Returns
Promise<number>
Note
On nodes without archive access enabled, the %%blockTag%% may be silently ignored by the node, which may cause issues if relied on.
Inherited from
ethers.BrowserProvider.getTransactionCountgetCode()
getCode(address, blockTag?): Promise<string>;Get the bytecode for %%address%%.
Parameters
| Parameter | Type |
|---|---|
address | AddressLike |
blockTag? | BlockTag |
Returns
Promise<string>
Note
On nodes without archive access enabled, the %%blockTag%% may be silently ignored by the node, which may cause issues if relied on.
Inherited from
ethers.BrowserProvider.getCodegetStorage()
getStorage(
address,
_position,
blockTag?): Promise<string>;Get the storage slot value for %%address%% at slot %%position%%.
Parameters
| Parameter | Type |
|---|---|
address | AddressLike |
_position | BigNumberish |
blockTag? | BlockTag |
Returns
Promise<string>
Note
On nodes without archive access enabled, the %%blockTag%% may be silently ignored by the node, which may cause issues if relied on.
Inherited from
ethers.BrowserProvider.getStoragebroadcastTransaction()
broadcastTransaction(signedTx): Promise<TransactionResponse>;Broadcasts the %%signedTx%% to the network, adding it to the memory pool of any node for which the transaction meets the rebroadcast requirements.
Parameters
| Parameter | Type |
|---|---|
signedTx | string |
Returns
Promise<TransactionResponse>
Inherited from
ethers.BrowserProvider.broadcastTransactiongetBlock()
getBlock(block, prefetchTxs?): Promise<Block | null>;Resolves to the block for %%blockHashOrBlockTag%%.
If %%prefetchTxs%%, and the backend supports including transactions with block requests, all transactions will be included and the [[Block]] object will not need to make remote calls for getting transactions.
Parameters
| Parameter | Type |
|---|---|
block | BlockTag |
prefetchTxs? | boolean |
Returns
Promise<Block | null>
Inherited from
ethers.BrowserProvider.getBlockgetTransaction()
getTransaction(hash): Promise<TransactionResponse | null>;Resolves to the transaction for %%hash%%.
If the transaction is unknown or on pruning nodes which
discard old transactions this resolves to null.
Parameters
| Parameter | Type |
|---|---|
hash | string |
Returns
Promise<TransactionResponse | null>
Inherited from
ethers.BrowserProvider.getTransactiongetTransactionReceipt()
getTransactionReceipt(hash): Promise<TransactionReceipt | null>;Resolves to the transaction receipt for %%hash%%, if mined.
If the transaction has not been mined, is unknown or on
pruning nodes which discard old transactions this resolves to
null.
Parameters
| Parameter | Type |
|---|---|
hash | string |
Returns
Promise<TransactionReceipt | null>
Inherited from
ethers.BrowserProvider.getTransactionReceiptgetTransactionResult()
getTransactionResult(hash): Promise<string | null>;Resolves to the result returned by the executions of %%hash%%.
This is only supported on nodes with archive access and with the necessary debug APIs enabled.
Parameters
| Parameter | Type |
|---|---|
hash | string |
Returns
Promise<string | null>
Inherited from
ethers.BrowserProvider.getTransactionResultgetLogs()
getLogs(_filter): Promise<Log[]>;Resolves to the list of Logs that match %%filter%%
Parameters
| Parameter | Type |
|---|---|
_filter | Filter | FilterByBlockHash |
Returns
Promise<Log[]>
Inherited from
ethers.BrowserProvider.getLogs_getProvider()
_getProvider(chainId): AbstractProvider;Parameters
| Parameter | Type |
|---|---|
chainId | number |
Returns
AbstractProvider
Inherited from
ethers.BrowserProvider._getProvidergetResolver()
getResolver(name): Promise<EnsResolver | null>;Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
Promise<EnsResolver | null>
Inherited from
ethers.BrowserProvider.getResolvergetAvatar()
getAvatar(name): Promise<string | null>;Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
Promise<string | null>
Inherited from
ethers.BrowserProvider.getAvatarresolveName()
resolveName(name): Promise<string | null>;Resolves to the address configured for the %%ensName%% or
null if unconfigured.
Parameters
| Parameter | Type |
|---|---|
name | string |
Returns
Promise<string | null>
Inherited from
ethers.BrowserProvider.resolveNamelookupAddress()
lookupAddress(address): Promise<string | null>;Resolves to the ENS name associated for the %%address%% or
null if the //primary name// is not configured.
Users must perform additional steps to configure a //primary name//, which is not currently common.
Parameters
| Parameter | Type |
|---|---|
address | string |
Returns
Promise<string | null>
Inherited from
ethers.BrowserProvider.lookupAddresswaitForTransaction()
waitForTransaction(
hash,
_confirms?,
timeout?): Promise<TransactionReceipt | null>;Waits until the transaction %%hash%% is mined and has %%confirms%% confirmations.
Parameters
| Parameter | Type |
|---|---|
hash | string |
_confirms? | number | null |
timeout? | number | null |
Returns
Promise<TransactionReceipt | null>
Inherited from
ethers.BrowserProvider.waitForTransactionwaitForBlock()
waitForBlock(blockTag?): Promise<Block>;Resolves to the block at %%blockTag%% once it has been mined.
This can be useful for waiting some number of blocks by using
the currentBlockNumber + N.
Parameters
| Parameter | Type |
|---|---|
blockTag? | BlockTag |
Returns
Promise<Block>
Inherited from
ethers.BrowserProvider.waitForBlock_clearTimeout()
_clearTimeout(timerId): void;Clear a timer created using the [[_setTimeout]] method.
Parameters
| Parameter | Type |
|---|---|
timerId | number |
Returns
void
Inherited from
ethers.BrowserProvider._clearTimeout_setTimeout()
_setTimeout(_func, timeout?): number;Create a timer that will execute %%func%% after at least %%timeout%% (in ms). If %%timeout%% is unspecified, then %%func%% will execute in the next event loop.
Pausing the provider will pause any associated timers.
Parameters
| Parameter | Type |
|---|---|
_func | () => void |
timeout? | number |
Returns
number
Inherited from
ethers.BrowserProvider._setTimeout_forEachSubscriber()
_forEachSubscriber(func): void;Perform %%func%% on each subscriber.
Parameters
| Parameter | Type |
|---|---|
func | (s) => void |
Returns
void
Inherited from
ethers.BrowserProvider._forEachSubscriber_recoverSubscriber()
_recoverSubscriber(oldSub, newSub): void;If a [[Subscriber]] fails and needs to replace itself, this method may be used.
For example, this is used for providers when using the
eth_getFilterChanges method, which can return null if state
filters are not supported by the backend, allowing the Subscriber
to swap in a [[PollingEventSubscriber]].
Parameters
| Parameter | Type |
|---|---|
oldSub | Subscriber |
newSub | Subscriber |
Returns
void
Inherited from
ethers.BrowserProvider._recoverSubscriberon()
on(event, listener): Promise<InjectedMulticallProvider>;Registers a %%listener%% that is called whenever the %%event%% occurs until unregistered.
Parameters
| Parameter | Type |
|---|---|
event | ProviderEvent |
listener | Listener |
Returns
Promise<InjectedMulticallProvider>
Inherited from
ethers.BrowserProvider.ononce()
once(event, listener): Promise<InjectedMulticallProvider>;Registers a %%listener%% that is called the next time %%event%% occurs.
Parameters
| Parameter | Type |
|---|---|
event | ProviderEvent |
listener | Listener |
Returns
Promise<InjectedMulticallProvider>
Inherited from
ethers.BrowserProvider.onceemit()
emit(event, ...args): Promise<boolean>;Triggers each listener for %%event%% with the %%args%%.
Parameters
| Parameter | Type |
|---|---|
event | ProviderEvent |
…args | any[] |
Returns
Promise<boolean>
Inherited from
ethers.BrowserProvider.emitlistenerCount()
listenerCount(event?): Promise<number>;Resolves to the number of listeners for %%event%%.
Parameters
| Parameter | Type |
|---|---|
event? | ProviderEvent |
Returns
Promise<number>
Inherited from
ethers.BrowserProvider.listenerCountlisteners()
listeners(event?): Promise<Listener[]>;Resolves to the listeners for %%event%%.
Parameters
| Parameter | Type |
|---|---|
event? | ProviderEvent |
Returns
Promise<Listener[]>
Inherited from
ethers.BrowserProvider.listenersoff()
off(event, listener?): Promise<InjectedMulticallProvider>;Unregister the %%listener%% for %%event%%. If %%listener%% is unspecified, all listeners are unregistered.
Parameters
| Parameter | Type |
|---|---|
event | ProviderEvent |
listener? | Listener |
Returns
Promise<InjectedMulticallProvider>
Inherited from
ethers.BrowserProvider.offremoveAllListeners()
removeAllListeners(event?): Promise<InjectedMulticallProvider>;Unregister all listeners for %%event%%.
Parameters
| Parameter | Type |
|---|---|
event? | ProviderEvent |
Returns
Promise<InjectedMulticallProvider>
Inherited from
ethers.BrowserProvider.removeAllListenersaddListener()
addListener(event, listener): Promise<InjectedMulticallProvider>;Alias for [[on]].
Parameters
| Parameter | Type |
|---|---|
event | ProviderEvent |
listener | Listener |
Returns
Promise<InjectedMulticallProvider>
Inherited from
ethers.BrowserProvider.addListenerremoveListener()
removeListener(event, listener): Promise<InjectedMulticallProvider>;Alias for [[off]].
Parameters
| Parameter | Type |
|---|---|
event | ProviderEvent |
listener | Listener |
Returns
Promise<InjectedMulticallProvider>
Inherited from
ethers.BrowserProvider.removeListenerpause()
pause(dropWhilePaused?): void;Pause the provider. If %%dropWhilePaused%%, any events that occur while paused are dropped, otherwise all events will be emitted once the provider is unpaused.
Parameters
| Parameter | Type |
|---|---|
dropWhilePaused? | boolean |
Returns
void
Inherited from
ethers.BrowserProvider.pauseresume()
resume(): void;Resume the provider.
Returns
void
Inherited from
ethers.BrowserProvider.resumesend()
send(method, params): Promise<any>;Requests the %%method%% with %%params%% via the JSON-RPC protocol over the underlying channel. This can be used to call methods on the backend that do not have a high-level API within the Provider API.
This method queues requests according to the batch constraints in the options, assigns the request a unique ID.
Do NOT override this method in sub-classes; instead override [[_send]] or force the options values in the call to the constructor to modify this method’s behavior.
Parameters
| Parameter | Type |
|---|---|
method | string |
params | any[] | Record<string, any> |
Returns
Promise<any>
Inherited from
ethers.BrowserProvider.send_send()
_send(payload): Promise<(JsonRpcResult | JsonRpcError)[]>;Sends a JSON-RPC %%payload%% (or a batch) to the underlying channel.
Sub-classes MUST override this.
Parameters
| Parameter | Type |
|---|---|
payload | JsonRpcPayload | JsonRpcPayload[] |
Returns
Promise<(JsonRpcResult | JsonRpcError)[]>
Inherited from
ethers.BrowserProvider._sendgetRpcError()
getRpcError(payload, error): Error;Returns an ethers-style Error for the given JSON-RPC error %%payload%%, coalescing the various strings and error shapes that different nodes return, coercing them into a machine-readable standardized error.
Parameters
| Parameter | Type |
|---|---|
payload | JsonRpcPayload |
error | JsonRpcError |
Returns
Error
Inherited from
ethers.BrowserProvider.getRpcErrorhasSigner()
hasSigner(address): Promise<boolean>;Resolves to true if the provider manages the %%address%%.
Parameters
| Parameter | Type |
|---|---|
address | string | number |
Returns
Promise<boolean>
Inherited from
ethers.BrowserProvider.hasSignergetSigner()
getSigner(address?): Promise<JsonRpcSigner>;Resolves to the [[Signer]] account for %%address%% managed by the client.
If the %%address%% is a number, it is used as an index in the the accounts from [[listAccounts]].
This can only be used on clients which manage accounts (such as Geth with imported account or MetaMask).
Throws if the account doesn’t exist.
Parameters
| Parameter | Type |
|---|---|
address? | string | number |
Returns
Promise<JsonRpcSigner>
Inherited from
ethers.BrowserProvider.getSignerdiscover()
static discover(options?): Promise<BrowserProvider | null>;Discover and connect to a Provider in the Browser using the
[[link-eip-6963]] discovery mechanism. If no providers are
present, null is resolved.
Parameters
| Parameter | Type |
|---|---|
options? | BrowserDiscoverOptions |
Returns
Promise<BrowserProvider | null>
Inherited from
ethers.BrowserProvider.discover_getOption()
_getOption<K>(key): JsonRpcApiProviderOptions[K];Returns the value associated with the option %%key%%.
Sub-classes can use this to inquire about configuration options.
Type Parameters
| Type Parameter |
|---|
K extends keyof JsonRpcApiProviderOptions |
Parameters
| Parameter | Type |
|---|---|
key | K |
Returns
JsonRpcApiProviderOptions[K]
Inherited from
ethers.BrowserProvider._getOption_perform()
_perform(req): Promise<any>;Resolves to the non-normalized value by performing %%req%%.
Sub-classes may override this to modify behavior of actions,
and should generally call super._perform as a fallback.
Parameters
| Parameter | Type |
|---|---|
req | PerformActionRequest |
Returns
Promise<any>
Inherited from
ethers.BrowserProvider._perform_detectNetwork()
_detectNetwork(): Promise<Network>;Sub-classes may override this; it detects the actual network that we are currently connected to.
Keep in mind that [[send]] may only be used once [[ready]], otherwise the _send primitive must be used instead.
Returns
Promise<Network>
Inherited from
ethers.BrowserProvider._detectNetwork_start()
_start(): void;Sub-classes MUST call this. Until [[_start]] has been called, no calls
will be passed to [[_send]] from [[send]]. If it is overridden, then
super._start() MUST be called.
Calling it multiple times is safe and has no effect.
Returns
void
Inherited from
ethers.BrowserProvider._start_waitUntilReady()
_waitUntilReady(): Promise<void>;Resolves once the [[_start]] has been called. This can be used in sub-classes to defer sending data until the connection has been established.
Returns
Promise<void>
Inherited from
ethers.BrowserProvider._waitUntilReadygetRpcTransaction()
getRpcTransaction(tx): JsonRpcTransactionRequest;Returns %%tx%% as a normalized JSON-RPC transaction request, which has all values hexlified and any numeric values converted to Quantity values.
Parameters
| Parameter | Type |
|---|---|
tx | TransactionRequest |
Returns
JsonRpcTransactionRequest
Inherited from
ethers.BrowserProvider.getRpcTransactiongetRpcRequest()
getRpcRequest(req):
| {
method: string;
args: any[];
}
| null;Returns the request method and arguments required to perform %%req%%.
Parameters
| Parameter | Type |
|---|---|
req | PerformActionRequest |
Returns
| {
method: string;
args: any[];
}
| null
Inherited from
ethers.BrowserProvider.getRpcRequestlistAccounts()
listAccounts(): Promise<JsonRpcSigner[]>;Returns
Promise<JsonRpcSigner[]>
Inherited from
ethers.BrowserProvider.listAccountsdestroy()
destroy(): void;Sub-classes may use this to shutdown any sockets or release their resources and reject any pending requests.
Sub-classes must call super.destroy().
Returns
void
Inherited from
ethers.BrowserProvider.destroy_getSubscriber()
_getSubscriber(sub): Subscriber;Return a Subscriber that will manage the %%sub%%.
Sub-classes may override this to modify the behavior of subscription management.
Parameters
| Parameter | Type |
|---|---|
sub | Subscription |
Returns
Subscriber
Inherited from
ethers.BrowserProvider._getSubscriberInterfaces
MulticallRequest
Properties
| Property | Type |
|---|---|
target | string |
callData | string |
MulticallResult
Properties
| Property | Type |
|---|---|
success | boolean |
returnData | string |
ContractAddresses
Addresses of every core zkScatter contract on a given chain.
Properties
NetworkConfig
Everything an app needs to talk to one zkScatter deployment.
Deliberately passive — the SDK never reads it from
process.env or window.__ENV__. The host app builds it from its
own config layer and passes it in.
Properties
| Property | Type | Description |
|---|---|---|
chainId | number | - |
name? | string | Display name; falls back to chainName(chainId) when omitted. |
rpcUrl | string | - |
explorerBase? | string | Block explorer base URL (e.g. https://sepolia.etherscan.io). |
contracts | ContractAddresses | - |
tokens | TokenInfo[] | - |
relayer? | { url: string; } | Default relayer URL used when the user hasn’t picked one. |
relayer.url | string | - |
sharedOrderbookUrl? | string | Shared orderbook service URL (cross-relayer order discovery). |
zkX509Url? | string | zk-X509 verification flow URL. |
deployBlock? | number | Block to start event scans from (deploy block). 0 = full scan. |
CommitmentInsertedRow
One CommitmentInserted event row, normalised to native bigints
and a JS number for the leaf index.
Properties
| Property | Type |
|---|---|
commitment | bigint |
leafIndex | number |
CommitmentInsertedHistoryOptions
Block range for hydration. Always pass fromBlock = the pool’s
deploy block: scanning from genesis is wasteful and, on a chain
far past the deploy block, exceeds a provider’s eth_getLogs
cap. The scan is split into chunkSize-block windows so a wide
range never trips that cap regardless of how far the chain has
advanced. toBlock defaults to the current head.
Properties
FetchCommitmentLeavesOptions
Properties
TokenInfo
A token an app can offer in pickers, balances, orders.
Extended by
Properties
WhitelistedToken
A token an app can offer in pickers, balances, orders.
Extends
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
address | string | On-chain ERC-20 address. For native ETH this is the WETH slot. | TokenInfo.address |
symbol | string | - | TokenInfo.symbol |
decimals | number | - | TokenInfo.decimals |
isNative | boolean | True for the synthetic “ETH” entry that wraps/unwraps via WETH. | TokenInfo.isNative |
name | string | Display name, e.g. “Ether”, “USD Coin”. | - |
baseInMarkets? | QuoteMarket[] | Quote markets in which this token serves as base — i.e. what tabs the pair {this}/{quote} appears under. Empty for tokens that only ever trade as the quote side. | - |
isQuoteMarket? | boolean | True for tokens we ourselves treat as a quote market tab. ETH / USDC / USDT for the launch lineup; TON is base-only. | - |
category | "base" | "stable" | Stable-of-stable hint — UI can render a different chip color for stables and warn on stable→stable trades. | - |
launchOffer? | boolean | True when launch-event 0% fee applies. Today: all four tokens. | - |
WhitelistedPair
Properties
FetchWhitelistedTokensOptions
Options for fetchWhitelistedTokens.
Extended by
Properties
| Property | Type | Description |
|---|---|---|
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. |
WhitelistMembership
One token’s whitelist state across the two contracts.
Properties
| Property | Type | Description |
|---|---|---|
token | TokenInfo | - |
inPool | boolean | Whitelisted on the CommitmentPool (deposit side). |
inSettlement | boolean | Whitelisted on the PrivateSettlement (settle/claim side). |
WriteTx
Minimal shape returned by a contract write — hash plus wait().
Properties
| Property | Type |
|---|---|
hash | string |
Methods
wait()
wait(): Promise<
| {
hash?: string;
}
| null>;Returns
Promise<
| {
hash?: string;
}
| null>
RunWriteOpts
Properties
Type Aliases
ExplorerEntity
type ExplorerEntity = "tx" | "address" | "block";QuoteMarket
type QuoteMarket = "USDC" | "USDT" | "ETH";Markets a token can serve as the quote side of (Upbit-style market tabs). Used by pickers to group pairs by quote currency and by the orderbook UI to render a “USDC market / USDT market / ETH market” tab strip.
Variables
ZERO_ADDRESS
const ZERO_ADDRESS: "0x0000000000000000000000000000000000000000" = "0x0000000000000000000000000000000000000000";Canonical zero address — the placeholder a NetworkConfig uses
for any contract slot that hasn’t been deployed yet. Lowercase
to match the case-insensitive comparison in
isConfiguredAddress.
RELAYER_REGISTRY_ABI
const RELAYER_REGISTRY_ABI: readonly ["function register(string url, string name, uint256 fee, uint256 bondAmount) external payable", "function requestExit() external", "function executeExit() external", "function updateInfo(string url, string name, uint256 fee) external", "function addBond(uint256 bondAmount) external payable", "function isActiveRelayer(address relayer) external view returns (bool)", "function getActiveRelayers() external view returns (address[])", "function getRelayerCount() external view returns (uint256)", "function relayerList(uint256) external view returns (address)", "function relayers(address) external view returns (string url, string name, uint256 fee, uint256 bond, uint256 registeredAt, uint256 exitRequestedAt, bool active, address bondToken)", "function treasury() external view returns (address)", "function minBond() external view returns (uint256)", "function identityRegistry() external view returns (address)", "function bondToken() external view returns (address)", "function kycApprovalRegistry() external view returns (address)", "function operationalKycRequired() external view returns (bool)", "function exitCooldown() external view returns (uint256)", "function DEFAULT_EXIT_COOLDOWN() external view returns (uint256)", "function MAX_EXIT_COOLDOWN() external view returns (uint256)", "function owner() external view returns (address)", "function pendingOwner() external view returns (address)", "function setTreasury(address _treasury) external", "function setMinBond(uint256 _minBond) external", "function setBondToken(address _bondToken) external", "function setBond(address _bondToken, uint256 _minBond) external", "function setExitCooldown(uint256 _exitCooldown) external", "function setKycApprovalRegistry(address _kycApprovalRegistry) external", "function setOperationalKycRequired(bool _required) external", "function setIdentityRegistry(address _identityRegistry) external", "function transferOwnership(address newOwner) external", "function acceptOwnership() external", "event IdentityRegistryUpdated(address oldRegistry, address newRegistry)", "event TreasuryUpdated(address oldTreasury, address newTreasury)", "event MinBondUpdated(uint256 oldMinBond, uint256 newMinBond)", "event BondTokenUpdated(address indexed oldToken, address indexed newToken)", "event ExitCooldownUpdated(uint256 oldCooldown, uint256 newCooldown)", "event KycApprovalRegistryUpdated(address oldRegistry, address newRegistry)", "event OperationalKycRequirementUpdated(bool enabled)", "event RelayerForceRemoved(address indexed relayer, string reason, uint256 exitAfter)", "error AlreadyRegistered()", "error NotRegistered()", "error InsufficientBond()", "error ExitNotRequested()", "error CooldownNotPassed()", "error AlreadyExiting()", "error ZeroAddress()", "error RelayerNotActive()", "error BondTransferFailed()", "error FeeTooHigh()", "error NotVerified()", "error NotKycApproved()", "error WrongPaymentMode()", "error NotAContract()", "error CooldownTooLong()"];IDENTITY_GATE_ABI
const IDENTITY_GATE_ABI: readonly ["function isVerified(address user) external view returns (bool)", "function verifiedUntil(address user) external view returns (uint64)", "function owner() external view returns (address)", "function getRegistryCount() external view returns (uint256)", "function getRegistries() external view returns (address[])", "function addRegistry(address registry) external", "function removeRegistry(address registry) external", "event RegistryAdded(address indexed registry)", "event RegistryRemoved(address indexed registry)"];ERC20_ABI
const ERC20_ABI: readonly ["function approve(address spender, uint256 amount) external returns (bool)", "function allowance(address owner, address spender) external view returns (uint256)", "function balanceOf(address account) external view returns (uint256)", "function symbol() external view returns (string)", "function decimals() external view returns (uint8)", "function transfer(address to, uint256 amount) external returns (bool)", "function transferFrom(address from, address to, uint256 amount) external returns (bool)"];MOCK_TOKEN_ABI
const MOCK_TOKEN_ABI: readonly ["function approve(address spender, uint256 amount) external returns (bool)", "function allowance(address owner, address spender) external view returns (uint256)", "function balanceOf(address account) external view returns (uint256)", "function symbol() external view returns (string)", "function decimals() external view returns (uint8)", "function transfer(address to, uint256 amount) external returns (bool)", "function transferFrom(address from, address to, uint256 amount) external returns (bool)", "function mint(address to, uint256 amount) external"];AUTHORIZE_PROOF_TUPLE
const AUTHORIZE_PROOF_TUPLE: string;Inner-tuple shape of SettleVerifyLib.AuthorizeProof. Exported so
ethers callers, the relayer’s runtime tuple builder, and any
ad-hoc test ABI strings can share one source of truth — the field
list otherwise drifts on the next struct change (PR #528 added
tier; the previous version was dropped in three places before
this PR caught it). Keep in lock-step with
contracts/src/zk/SettleVerifyLib.sol#AuthorizeProof.
PRIVATE_SETTLEMENT_ABI
const PRIVATE_SETTLEMENT_ABI: readonly ["function nullifiers(bytes32) view returns (bool)", "function claimNullifiers(bytes32) view returns (bool)", "function claimsGroups(bytes32) view returns (uint128 totalLocked, uint128 totalClaimed, address token, uint8 tier)", "function authorizeVerifierByTier(uint8) view returns (address)", "function batchAuthorizeVerifierByTier(uint8) view returns (address)", "function claimVerifierByTier(uint8) view returns (address)", "function getWhitelistedTokens() external view returns (address[])", "function dexPlatformFeeBps() view returns (uint256)", "function cancelPrivate((uint256[2] proofA, uint256[2][2] proofB, uint256[2] proofC, uint256 commitmentRoot, bytes32 oldNullifier, bytes32 oldNonceNullifier, bytes32 newCommitment) p) external", "function settleWithDex(((uint256[2] proofA, uint256[2][2] proofB, uint256[2] proofC, bytes32 pubKeyBind, uint256 commitmentRoot, bytes32 nullifier, bytes32 nonceNullifier, bytes32 newCommitment, address sellToken, address buyToken, uint128 sellAmount, uint128 buyAmount, uint16 maxFee, uint64 expiry, bytes32 claimsRoot, uint128 totalLocked, address relayer, bytes32 orderHash, uint8 tier) proof, address dexRouter, bytes dexCalldata, uint256 deadline) p) external", "function settleAuth(((uint256[2] proofA, uint256[2][2] proofB, uint256[2] proofC, bytes32 pubKeyBind, uint256 commitmentRoot, bytes32 nullifier, bytes32 nonceNullifier, bytes32 newCommitment, address sellToken, address buyToken, uint128 sellAmount, uint128 buyAmount, uint16 maxFee, uint64 expiry, bytes32 claimsRoot, uint128 totalLocked, address relayer, bytes32 orderHash, uint8 tier) maker, (uint256[2] proofA, uint256[2][2] proofB, uint256[2] proofC, bytes32 pubKeyBind, uint256 commitmentRoot, bytes32 nullifier, bytes32 nonceNullifier, bytes32 newCommitment, address sellToken, address buyToken, uint128 sellAmount, uint128 buyAmount, uint16 maxFee, uint64 expiry, bytes32 claimsRoot, uint128 totalLocked, address relayer, bytes32 orderHash, uint8 tier) taker, uint96 feeTokenMaker, uint96 feeTokenTaker) p) external", "function scatterDirectAuth(((uint256[2] proofA, uint256[2][2] proofB, uint256[2] proofC, bytes32 pubKeyBind, uint256 commitmentRoot, bytes32 nullifier, bytes32 nonceNullifier, bytes32 newCommitment, address sellToken, address buyToken, uint128 sellAmount, uint128 buyAmount, uint16 maxFee, uint64 expiry, bytes32 claimsRoot, uint128 totalLocked, address relayer, bytes32 orderHash, uint8 tier) proof, uint96 fee) p) external", "event ScatterDirectAuthSettled(bytes32 indexed nullifier, bytes32 indexed nonceNullifier, bytes32 claimsRoot, address indexed relayer, uint96 fee)", "function claimWithProof(uint256[2] proofA, uint256[2][2] proofB, uint256[2] proofC, bytes32 claimsRoot, bytes32 claimNullifier, uint256 amount, address token, address recipient, uint256 releaseTime) external", "function claimWithProofBatch((uint256[2] proofA, uint256[2][2] proofB, uint256[2] proofC, bytes32 claimsRoot, bytes32 claimNullifier, uint256 amount, address token, address recipient, uint256 releaseTime)[] claims) external", "event PrivateClaim(bytes32 indexed claimsRoot, bytes32 indexed nullifier, address indexed recipient, address token, uint256 amount)", "event PrivateCancel(bytes32 indexed escrowNullifier, bytes32 indexed nonceNullifier, bytes32 newCommitment, address indexed relayer)", "event PrivateSettledAuth(bytes32 indexed makerNullifier, bytes32 indexed takerNullifier, bytes32 claimsRootMaker, bytes32 claimsRootTaker, address indexed makerRelayer, address takerRelayer, address submitter, uint96 feeTokenMaker, uint96 feeTokenTaker)", "event SettledWithDex(bytes32 indexed nullifier, bytes32 indexed claimsRoot, address sellToken, address buyToken, uint128 sellAmount, uint256 amountOut, uint128 totalLocked, address indexed submitter)"];COMMITMENT_POOL_ABI
const COMMITMENT_POOL_ABI: readonly ["function deposit(uint256[2] proofA, uint256[2][2] proofB, uint256[2] proofC, uint256 commitment, address token, uint256 amount) external", "function withdraw(uint256[2] proofA, uint256[2][2] proofB, uint256[2] proofC, uint256 root, uint256 nullifierHash, uint256 newCommitment, address token, uint256 amount, address recipient, address relayer) external", "function isKnownRoot(uint256 root) view returns (bool)", "function getWhitelistedTokens() external view returns (address[])", "function nullifiers(uint256) view returns (bool)", "function getLastRoot() view returns (uint256)", "function nextIndex() view returns (uint32)", "event CommitmentInserted(uint256 indexed commitment, uint32 leafIndex, uint256 timestamp)", "event Withdrawal(address indexed recipient, uint256 nullifierHash, uint256 newCommitment, uint256 amount)"];FEE_VAULT_ABI
const FEE_VAULT_ABI: readonly ["function balances(address relayer, address token) view returns (uint256)", "function claim(address token) external", "function platformFeeBps() view returns (uint256)", "function pendingFeeBps() view returns (uint256)", "function pendingFeeEffectiveTime() view returns (uint256)", "function treasury() view returns (address)", "function totalTracked(address token) view returns (uint256)", "function platformRevenue(address token) view returns (uint256)", "event FeeDeposited(address indexed relayer, address indexed token, uint256 amount)", "event FeeClaimed(address indexed relayer, address indexed token, uint256 amount, uint256 platformFee)", "event PlatformFeeFromDex(address indexed token, uint256 amount)", "event PlatformSurplusFromDex(address indexed token, uint256 amount)", "event PlatformFeeFromRelayerClaim(address indexed token, uint256 amount, address indexed relayer)", "event PlatformRevenueWithdrawn(address indexed token, uint256 amount, address indexed to)", "error ZeroAddress()", "error FeeTooHigh()", "error NotAuthorized()", "error NothingToClaim()", "error InsufficientTokenBalance()", "error NoFeeChangePending()", "error FeeChangeNotReady()"];ISSUANCE_APPROVAL_REGISTRY_ABI
const ISSUANCE_APPROVAL_REGISTRY_ABI: readonly ["function approve(address operator, string commonName, string organization, string country, uint32 validityDays, uint64 expiresAt) external", "function revoke(address operator, string reason) external", "function approvals(address operator) external view returns (tuple(string commonName, string organization, string country, uint32 validityDays, address approvedBy, uint64 approvedAt, uint64 expiresAt, bool revoked, string revokeReason, uint64 revokedAt))", "function isApproved(address operator) external view returns (bool)", "function owner() external view returns (address)", "function pendingOwner() external view returns (address)", "function transferOwnership(address newOwner) external", "function acceptOwnership() external", "event ApprovalRecorded(address indexed operator, string commonName, string organization, string country, uint32 validityDays, address indexed approvedBy, uint64 approvedAt, uint64 expiresAt)", "event ApprovalRevoked(address indexed operator, address indexed revokedBy, uint64 revokedAt, string reason)", "event ApprovalReplaced(address indexed operator, address indexed approvedBy, uint64 priorApprovedAt, bool priorRevoked, string priorRevokeReason)", "error ZeroOperator()", "error EmptyCommonName()", "error EmptyOrganization()", "error CountryMustBeISO3166Alpha2()", "error ValidityOutOfRange()", "error ExpiresAtMustBeFutureOrZero()", "error NoApprovalToRevoke()", "error AlreadyRevoked()", "error RenounceOwnershipDisabled()"];RELAYER_REGISTRY_IFACE
const RELAYER_REGISTRY_IFACE: Interface;IDENTITY_GATE_IFACE
const IDENTITY_GATE_IFACE: Interface;ERC20_IFACE
const ERC20_IFACE: Interface;PRIVATE_SETTLEMENT_IFACE
const PRIVATE_SETTLEMENT_IFACE: Interface;COMMITMENT_POOL_IFACE
const COMMITMENT_POOL_IFACE: Interface;FEE_VAULT_IFACE
const FEE_VAULT_IFACE: Interface;MULTICALL3_ADDRESS
const MULTICALL3_ADDRESS: "0xcA11bde05977b3631167028862bE2a173976CA11" = "0xcA11bde05977b3631167028862bE2a173976CA11";MULTICALL3_ABI
const MULTICALL3_ABI: string[];KNOWN_CHAIN_NAMES
const KNOWN_CHAIN_NAMES: Record<number, string>;Display names for chains zkScatter cares about. Unknown chains
fall through to Chain <id> so the UI never blanks out.
KNOWN_EXPLORER_BASES
const KNOWN_EXPLORER_BASES: Record<number, string>;Block-explorer roots for chains zkScatter actually deploys to.
Polygon / Arbitrum / Optimism appear in KNOWN_CHAIN_NAMES for
display only; they intentionally have no explorer entry here so
callers can show plain text instead of a broken link.
KNOWN_DEFAULT_RPC_URLS
const KNOWN_DEFAULT_RPC_URLS: Record<number, string>;Reliable, keyless public RPC endpoints for chains zkScatter deploys to.
Used as the default read provider when no NEXT_PUBLIC_RPC_URL is set:
pre-connect reads, wrong-network fallback, and the write gas pre-flight all
run here, while transactions are still signed and sent through the user’s
wallet. A dead default is what we must avoid — the old rpc.sepolia.org
now serves an Apache 404 HTML page, which ethers can’t parse into a typed
error and surfaces as the opaque “could not coalesce error” on every
estimateGas/read. The publicnode endpoint below answers JSON-RPC (including
eth_estimateGas) and tolerates request bursts without rate-limiting.
LAUNCH_TOKENS
const LAUNCH_TOKENS: Record<string, WhitelistedToken>;Launch-token whitelist by symbol. Apps resolve to per-network
addresses via NetworkConfig.tokens; this map stays the
symbol-keyed source of marketing + UX metadata.
LAUNCH_PAIRS
const LAUNCH_PAIRS: readonly WhitelistedPair[];Curated launch pair list. Pair listing is explicit (not all-pairs-of-tokens) so we control which markets exist on day 1.
3 quote markets (USDC / USDT / ETH) × base tokens minus self-pair and minus stable/stable (USDC/USDT and USDT/USDC excluded — they are the same trade in two listings, with negligible price movement; not worth the orderbook noise). Total: 7 pairs.
Functions
isConfiguredAddress()
function isConfiguredAddress(addr): addr is string;Is this address slot actually wired to a deployed contract?
Returns true when addr is a non-empty string that is not the
zero address. Returns false for undefined, null, the empty
string, or the zero address — which is what placeholder
NetworkConfig entries use while the network is still on mocks.
This helper does not validate address format (no length / hex / checksum check); it only checks presence and zero-address inequality. Format validation belongs at the input boundary (config loader, RPC response decoder), not on every call site.
Parameters
| Parameter | Type |
|---|---|
addr | string | null | undefined |
Returns
addr is string
multicall()
function multicall(provider, requests): Promise<MulticallResult[]>;Batch multiple read-only contract calls into a single RPC request via Multicall3. Automatically chunks large batches. Falls back to individual calls if Multicall3 is unavailable (e.g. a local chain without the predeploy).
All calls use allowFailure=true semantics — a failed sub-call returns
{ success: false } instead of reverting the whole batch. Callers must
check result.success per item.
Promoted from the legacy frontend/app/lib/multicall.ts so every app
(and the wallet-backed InjectedMulticallProvider) shares one
implementation.
Parameters
| Parameter | Type |
|---|---|
provider | Provider |
requests | MulticallRequest[] |
Returns
Promise<MulticallResult[]>
encodeCall()
function encodeCall(
iface,
functionName,
args): string;Encode a contract function call for multicall batching.
Parameters
| Parameter | Type |
|---|---|
iface | Interface |
functionName | string |
args | unknown[] |
Returns
string
decodeResult()
function decodeResult(
iface,
functionName,
data): Result;Decode a multicall sub-call result.
Parameters
| Parameter | Type |
|---|---|
iface | Interface |
functionName | string |
data | string |
Returns
Result
defaultRpcUrl()
function defaultRpcUrl(chainId): string;Default read RPC for a chain, or "" when none is known (callers then rely on a wallet-injected provider).
Parameters
| Parameter | Type |
|---|---|
chainId | number |
Returns
string
chainName()
function chainName(chainId): string;Parameters
| Parameter | Type |
|---|---|
chainId | number |
Returns
string
explorerLink()
function explorerLink(
network,
entity,
value): string | undefined;Build an explorer URL for a tx / address / block on the given
network. Returns undefined when the network has no known
explorer (e.g. localhost), which signals callers to render plain
text instead of a link.
Parameters
| Parameter | Type |
|---|---|
network | Pick<NetworkConfig, "chainId" | "explorerBase"> |
entity | ExplorerEntity |
value | string |
Returns
string | undefined
loadCommitmentInsertedHistory()
function loadCommitmentInsertedHistory(
provider,
poolAddress,
options?): Promise<CommitmentInsertedRow[]>;Read CommitmentInserted events the contract has emitted,
ordered by leafIndex (i.e. insertion order). The pool inserts
monotonically, so this is also the order an
IncrementalMerkleTree should be fed.
The [fromBlock, toBlock] range is queried in sequential
chunkSize-block windows (preserving ascending order) so a wide
scan never exceeds a provider’s block-range cap.
Throws on RPC failure — callers can decide whether to retry or fall back to a degraded “empty tree” mode.
Parameters
| Parameter | Type |
|---|---|
provider | Provider |
poolAddress | string |
options? | CommitmentInsertedHistoryOptions |
Returns
Promise<CommitmentInsertedRow[]>
fetchCommitmentLeaves()
function fetchCommitmentLeaves(
serverUrl,
chainId,
options?): Promise<CommitmentInsertedRow[]>;Fetch the full commitment history for chainId from a shared-orderbook
indexer (GET /api/commitments), paging by fromLeaf until a short page.
Returns rows in loadCommitmentInsertedHistory’s shape so callers can treat
the two sources identically. Throws on any non-2xx, network error, or
malformed payload — the caller falls back to getLogs and re-verifies the
root, so a bad/incomplete server response is never silently trusted.
Parameters
| Parameter | Type |
|---|---|
serverUrl | string |
chainId | number | bigint |
options? | FetchCommitmentLeavesOptions |
Returns
Promise<CommitmentInsertedRow[]>
isKnownPoolRoot()
function isKnownPoolRoot(
provider,
poolAddress,
root): Promise<boolean>;True iff root is in the pool’s on-chain root history ring buffer.
This is exactly the check PrivateSettlement runs against a proof’s
root at settle time, so a locally-hydrated tree whose root passes here
is guaranteed to yield proofs the chain will accept — and one that fails
was built from an incomplete, inconsistent, or tampered leaf set. The
ring tolerates being a few inserts behind head (default
ROOT_HISTORY_SIZE = 30), so a slightly-stale client still matches a
recent historical root.
Parameters
| Parameter | Type |
|---|---|
provider | Provider |
poolAddress | string |
root | bigint |
Returns
Promise<boolean>
getPoolNextIndex()
function getPoolNextIndex(provider, poolAddress): Promise<number>;On-chain leaf count — CommitmentPool.nextIndex(). The index the next
inserted commitment will occupy, i.e. the current number of leaves.
Parameters
| Parameter | Type |
|---|---|
provider | Provider |
poolAddress | string |
Returns
Promise<number>
subscribeCommitmentInserted()
function subscribeCommitmentInserted(
provider,
poolAddress,
onInserted): () => void;Subscribe to live CommitmentInserted events. Returns an
unsubscribe function — callers should detach in their effect
cleanup. The callback receives the same { commitment, leafIndex }
shape as the historical loader for symmetry.
Parameters
| Parameter | Type |
|---|---|
provider | Provider |
poolAddress | string |
onInserted | (row) => void |
Returns
() => void
getReadProvider()
function getReadProvider(rpcUrl): JsonRpcProvider;Build a read-only JsonRpcProvider for a chain’s RPC.
No singleton/cache here — caller decides lifetime. The React wallet
hook caches one per NetworkConfig so React renders share an
instance, but Node scripts and tests usually want fresh providers.
This is the fallback read path: it’s used when no wallet is
connected (or the wallet is on the wrong chain). A JsonRpcProvider
already auto-batches same-tick calls into one HTTP POST, so it needs
no Multicall help. Once a wallet is connected, reads route through
InjectedMulticallProvider instead so they run on the user’s own
node — see useWallet in @zkscatter/sdk/react.
Parameters
| Parameter | Type |
|---|---|
rpcUrl | string |
Returns
JsonRpcProvider
parseTokenList()
function parseTokenList(raw): TokenInfo[];Parse the compact address:symbol:decimals,address:symbol:decimals,…
token list format used by env vars and config files.
Whitespace and trailing commas are tolerated. Entries are skipped when any of address / symbol / decimals is missing or when decimals does not parse to a non-negative integer (decimals = 0 is allowed — some tokens use it). Skipped entries are dropped silently; surface config errors at the env-validation layer upstream of the SDK.
Parameters
| Parameter | Type |
|---|---|
raw | string | null | undefined |
Returns
withNativeEthAlias()
function withNativeEthAlias(tokens, wethAddress): TokenInfo[];Insert a synthetic “ETH” alias before the WETH entry, pointing at the same address. Returns a new array; the input is not mutated.
Decimals are inherited from the matched WETH entry rather than hardcoded — if the host’s token-list config ever ships WETH with non-standard decimals, the alias stays consistent.
This is the convention every zkScatter surface uses to let users pick “ETH” in a token picker even though the backing entry is always WETH on chain.
Parameters
| Parameter | Type |
|---|---|
tokens | TokenInfo[] |
wethAddress | string |
Returns
curatedErc20View()
function curatedErc20View(tokens): TokenInfo[];ERC-20 view of a curated token list: relabel the synthetic native “ETH” entry to “WETH” (its on-chain identity, sharing the address) and drop the native flag. Used as the on-chain whitelist’s overlay + fallback so the WETH row isn’t mislabelled “ETH”. Pure.
Parameters
| Parameter | Type |
|---|---|
tokens | TokenInfo[] |
Returns
overlayOnchainTokens()
function overlayOnchainTokens(
curated,
onchain,
wethAddress): TokenInfo[];Overlay on-chain whitelist addresses + decimals onto a curated token
list, preserving the curated order + display metadata (name, markets,
native-ness). The native “ETH” entry resolves via the WETH address
(on-chain it is “WETH”, sharing the address); when the whitelist has
no WETH entry the native address falls back to wethAddress (the env
WETH slot), so a caller can always read the resolved native entry’s
.address as a usable ERC-20 address without re-deriving the
fallback itself. Other tokens match by symbol; tokens absent from
onchain keep their curated entry (possibly a zero address → render
as “not configured”).
The single source of truth for “curated metadata + on-chain
addr/decimals”, shared by the React hook (useCuratedNetworkTokens)
and the lib-side resolver (resolveCuratedTokensCached). Pure.
Parameters
| Parameter | Type |
|---|---|
curated | TokenInfo[] |
onchain | TokenInfo[] |
wethAddress | string |
Returns
eqAddr()
function eqAddr(a, b): boolean;Lowercased-address comparison. Returns false when either side is
null/undefined/empty so callers can pass optional config fields
without a separate guard. Matches the existing eqAddr helper
used by frontend/mobile/zk-relayer.
Parameters
| Parameter | Type |
|---|---|
a | string | null | undefined |
b | string | null | undefined |
Returns
boolean
tokenMap()
function tokenMap(tokens): Record<string, TokenInfo>;Map of lowercase address → non-native TokenInfo, for fast lookup in orderbook / history rows where you have an address and need the symbol+decimals. Native ETH alias is intentionally excluded so address-keyed lookups always resolve to the ERC-20 entry.
Parameters
| Parameter | Type |
|---|---|
tokens | TokenInfo[] |
Returns
Record<string, TokenInfo>
formatTokenLabel()
function formatTokenLabel(symbol): string;Display string for a token symbol shown in the UI. Currently
promotes TON to Tokamak(TON) so the project’s full name is
visible alongside the ticker — internal code paths (storage,
ABI, RPC) keep using the bare symbol so this is purely a render
helper. Add other promotions here as the launch lineup grows.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
Returns
string
pairsByMarket()
function pairsByMarket(pairs?): Record<QuoteMarket, WhitelistedPair[]>;Group pairs by quote market for Upbit-style tabs. The returned map has stable insertion order matching the original pair list.
Parameters
| Parameter | Type | Default value |
|---|---|---|
pairs | readonly WhitelistedPair[] | LAUNCH_PAIRS |
Returns
Record<QuoteMarket, WhitelistedPair[]>
findPair()
function findPair(display, pairs?): WhitelistedPair | undefined;Find a pair entry by its display string.
Parameters
| Parameter | Type | Default value |
|---|---|---|
display | string | undefined |
pairs | readonly WhitelistedPair[] | LAUNCH_PAIRS |
Returns
WhitelistedPair | undefined
tokensBySymbol()
function tokensBySymbol(tokens): Record<string, TokenInfo>;Resolve a {symbol → on-chain address} map from a network’s
configured tokens. Apps thread this through the trade form so
decimals + addresses come from real per-chain entries, not the
placeholder LAUNCH_TOKENS defaults.
Parameters
| Parameter | Type |
|---|---|
tokens | readonly TokenInfo[] |
Returns
Record<string, TokenInfo>
fetchWhitelistedTokens()
function fetchWhitelistedTokens(
provider,
poolAddress,
settlementAddress,
options?): Promise<TokenInfo[]>;Build the live token list from on-chain whitelist state, so a team
deployment can add tokens via setTokenWhitelist and have every app
pick them up with no NEXT_PUBLIC_TOKENS edit.
A token must be whitelisted on both the CommitmentPool (deposit) and the PrivateSettlement (settle/claim) to be usable end-to-end, so the result is the intersection of the two contracts’ lists.
The on-chain order is NOT stable — EnumerableSet removal does a
swap-and-pop, so a token list can reshuffle when any token is
removed. The result is therefore sorted deterministically: overlay
tokens first in overlay (NEXT_PUBLIC_TOKENS / launch) order so the
curated lineup keeps its intended ordering, then any on-chain-only
tokens by symbol then address. This keeps picker order — and thus
the default trading pair — stable across reads.
Each token’s symbol and decimals are read on-chain. decimals is
always taken from the chain (so non-standard tokens like 27-decimals
WTON are exact); the optional FetchWhitelistedTokensOptions.overlay
can override symbol (label) and provides a fallback if a read
reverts. Tokens whose symbol/decimals can be resolved from neither
the chain nor the overlay are dropped (an unreadable ERC-20 is
unusable in a picker).
Returns [] (not a throw) when either address is unconfigured —
callers treat that as “fall back to the env list”. A getter revert
(e.g. a contract predating the whitelist getter) throws so the
caller’s catch can fall back rather than silently showing nothing.
The native-ETH alias is intentionally not applied here; callers
layer it via withNativeEthAlias(list, wethAddress).
Parameters
| Parameter | Type |
|---|---|
provider | Provider |
poolAddress | string |
settlementAddress | string |
options | FetchWhitelistedTokensOptions |
Returns
Promise<TokenInfo[]>
fetchWhitelistMembership()
function fetchWhitelistMembership(
provider,
poolAddress,
settlementAddress,
options?): Promise<WhitelistMembership[]>;Admin view of the whitelist: every token listed on either
contract (the union of the two getWhitelistedTokens() sets),
each tagged with its per-contract membership so an operator can spot
and fix a pool/settlement mismatch (inPool !== inSettlement).
This is the counterpart to fetchWhitelistedTokens, which returns the intersection for end-user pickers. The union is the right set for a management UI: a token whitelisted on only one contract is exactly what the admin needs to see (and fix), but it would be invisible in the intersection.
symbol/decimals are read on-chain (overlay overrides the label
and backstops a reverted read — see FetchWhitelistedTokensOptions).
Unlike fetchWhitelistedTokens, a token whose metadata can’t be
resolved is not dropped — it’s whitelisted, so the admin must see
it; it’s kept with an address-labelled placeholder symbol.
Result is sorted deterministically (overlay order first, then
symbol/address). Returns [] when either address is unconfigured; a
getter revert throws so the caller can fall back.
Parameters
| Parameter | Type |
|---|---|
provider | Provider |
poolAddress | string |
settlementAddress | string |
options | FetchWhitelistedTokensOptions |
Returns
Promise<WhitelistMembership[]>
runWrite()
function runWrite(
contract,
fn,
args,
opts?): Promise<WriteTx>;Submit a contract write with the gas/fee/nonce preflight done up-front on a reliable provider, so ethers performs no fragile estimate through the wallet’s RPC.
This is the shared fix for the admin “could not coalesce error”: the
wallet only ever does eth_sendTransaction, and a genuine revert is
surfaced with its real reason (estimateGas throws it) instead of being
wrapped by a throttled-RPC response.
Parameters
| Parameter | Type |
|---|---|
contract | Contract |
fn | string |
args | readonly unknown[] |
opts | RunWriteOpts |
Returns
Promise<WriteTx>
buildWriteOverrides()
function buildWriteOverrides(
contract,
fn,
args,
opts?): Promise<Overrides>;Pre-resolve { gasLimit, fees, nonce } so the wallet skips its own
preflight. Each piece degrades gracefully; only a real revert throws.
Parameters
| Parameter | Type |
|---|---|
contract | Contract |
fn | string |
args | readonly unknown[] |
opts | RunWriteOpts |
Returns
Promise<Overrides>