Skip to Content
SDK ReferenceTypeScript APIcore
SDK reference (auto)

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
ParameterType
eip1193Eip1193Provider
network?Networkish
opts?{ stallMs?: number; }
opts.stallMs?number
Returns

InjectedMulticallProvider

Overrides
ethers.BrowserProvider.constructor

Accessors

provider
Get Signature
get provider(): this;

Returns this, to allow an AbstractProvider to implement the [[ContractRunner]] interface.

Returns

this

Inherited from
ethers.BrowserProvider.provider
plugins
Get Signature
get plugins(): AbstractProviderPlugin[];

Returns all the registered plug-ins.

Returns

AbstractProviderPlugin[]

Inherited from
ethers.BrowserProvider.plugins
disableCcipRead
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
ParameterType
valueboolean
Returns

void

Inherited from
ethers.BrowserProvider.disableCcipRead
destroyed
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.destroyed
paused
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
ParameterType
pauseboolean
Returns

void

Inherited from
ethers.BrowserProvider.paused
providerInfo
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._network
ready
Get Signature
get ready(): boolean;

Returns true only if the [[_start]] has been called.

Returns

boolean

Inherited from
ethers.BrowserProvider.ready
pollingInterval
Get Signature
get pollingInterval(): number;

The polling interval (default: 4000 ms)

Returns

number

Set Signature
set pollingInterval(value): void;
Parameters
ParameterType
valuenumber
Returns

void

Inherited from
ethers.BrowserProvider.pollingInterval

Methods

call()
call(tx): Promise<string>;
Parameters
ParameterType
txTransactionRequest
Returns

Promise<string>

Overrides
ethers.BrowserProvider.call
attachPlugin()
attachPlugin(plugin): this;

Attach a new plug-in.

Parameters
ParameterType
pluginAbstractProviderPlugin
Returns

this

Inherited from
ethers.BrowserProvider.attachPlugin
getPlugin()
getPlugin<T>(name): T | null;

Get a plugin by name.

Type Parameters
Type ParameterDefault type
T extends AbstractProviderPluginAbstractProviderPlugin
Parameters
ParameterType
namestring
Returns

T | null

Inherited from
ethers.BrowserProvider.getPlugin
ccipReadFetch()
ccipReadFetch( tx, calldata, urls): Promise<string | null>;

Resolves to the data for executing the CCIP-read operations.

Parameters
ParameterType
txPerformActionTransaction
calldatastring
urlsstring[]
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
ParameterType
valueBlockParams
networkNetwork
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
ParameterType
valueLogParams
networkNetwork
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
ParameterType
valueTransactionReceiptParams
networkNetwork
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
ParameterType
txTransactionResponseParams
networkNetwork
Returns

TransactionResponse

Inherited from
ethers.BrowserProvider._wrapTransactionResponse
getBlockNumber()
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
ParameterType
addressAddressLike
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
ParameterType
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
ParameterType
filterFilter | 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
ParameterType
_requestTransactionRequest
Returns

PerformActionTransaction | Promise<PerformActionTransaction>

Inherited from
ethers.BrowserProvider._getTransactionRequest
getNetwork()
getNetwork(): Promise<Network>;

Get the connected [[Network]].

Returns

Promise<Network>

Inherited from
ethers.BrowserProvider.getNetwork
getFeeData()
getFeeData(): Promise<FeeData>;

Get the best guess at the recommended [[FeeData]].

Returns

Promise<FeeData>

Inherited from
ethers.BrowserProvider.getFeeData
estimateGas()
estimateGas(_tx): Promise<bigint>;

Estimates the amount of gas required to execute %%tx%%.

Parameters
ParameterType
_txTransactionRequest
Returns

Promise<bigint>

Inherited from
ethers.BrowserProvider.estimateGas
getBalance()
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
ParameterType
addressAddressLike
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.getBalance
getTransactionCount()
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
ParameterType
addressAddressLike
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.getTransactionCount
getCode()
getCode(address, blockTag?): Promise<string>;

Get the bytecode for %%address%%.

Parameters
ParameterType
addressAddressLike
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.getCode
getStorage()
getStorage( address, _position, blockTag?): Promise<string>;

Get the storage slot value for %%address%% at slot %%position%%.

Parameters
ParameterType
addressAddressLike
_positionBigNumberish
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.getStorage
broadcastTransaction()
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
ParameterType
signedTxstring
Returns

Promise<TransactionResponse>

Inherited from
ethers.BrowserProvider.broadcastTransaction
getBlock()
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
ParameterType
blockBlockTag
prefetchTxs?boolean
Returns

Promise<Block | null>

Inherited from
ethers.BrowserProvider.getBlock
getTransaction()
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
ParameterType
hashstring
Returns

Promise<TransactionResponse | null>

Inherited from
ethers.BrowserProvider.getTransaction
getTransactionReceipt()
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
ParameterType
hashstring
Returns

Promise<TransactionReceipt | null>

Inherited from
ethers.BrowserProvider.getTransactionReceipt
getTransactionResult()
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
ParameterType
hashstring
Returns

Promise<string | null>

Inherited from
ethers.BrowserProvider.getTransactionResult
getLogs()
getLogs(_filter): Promise<Log[]>;

Resolves to the list of Logs that match %%filter%%

Parameters
ParameterType
_filterFilter | FilterByBlockHash
Returns

Promise<Log[]>

Inherited from
ethers.BrowserProvider.getLogs
_getProvider()
_getProvider(chainId): AbstractProvider;
Parameters
ParameterType
chainIdnumber
Returns

AbstractProvider

Inherited from
ethers.BrowserProvider._getProvider
getResolver()
getResolver(name): Promise<EnsResolver | null>;
Parameters
ParameterType
namestring
Returns

Promise<EnsResolver | null>

Inherited from
ethers.BrowserProvider.getResolver
getAvatar()
getAvatar(name): Promise<string | null>;
Parameters
ParameterType
namestring
Returns

Promise<string | null>

Inherited from
ethers.BrowserProvider.getAvatar
resolveName()
resolveName(name): Promise<string | null>;

Resolves to the address configured for the %%ensName%% or null if unconfigured.

Parameters
ParameterType
namestring
Returns

Promise<string | null>

Inherited from
ethers.BrowserProvider.resolveName
lookupAddress()
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
ParameterType
addressstring
Returns

Promise<string | null>

Inherited from
ethers.BrowserProvider.lookupAddress
waitForTransaction()
waitForTransaction( hash, _confirms?, timeout?): Promise<TransactionReceipt | null>;

Waits until the transaction %%hash%% is mined and has %%confirms%% confirmations.

Parameters
ParameterType
hashstring
_confirms?number | null
timeout?number | null
Returns

Promise<TransactionReceipt | null>

Inherited from
ethers.BrowserProvider.waitForTransaction
waitForBlock()
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
ParameterType
blockTag?BlockTag
Returns

Promise<Block>

Inherited from
ethers.BrowserProvider.waitForBlock
_clearTimeout()
_clearTimeout(timerId): void;

Clear a timer created using the [[_setTimeout]] method.

Parameters
ParameterType
timerIdnumber
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
ParameterType
_func() => void
timeout?number
Returns

number

Inherited from
ethers.BrowserProvider._setTimeout
_forEachSubscriber()
_forEachSubscriber(func): void;

Perform %%func%% on each subscriber.

Parameters
ParameterType
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
ParameterType
oldSubSubscriber
newSubSubscriber
Returns

void

Inherited from
ethers.BrowserProvider._recoverSubscriber
on()
on(event, listener): Promise<InjectedMulticallProvider>;

Registers a %%listener%% that is called whenever the %%event%% occurs until unregistered.

Parameters
ParameterType
eventProviderEvent
listenerListener
Returns

Promise<InjectedMulticallProvider>

Inherited from
ethers.BrowserProvider.on
once()
once(event, listener): Promise<InjectedMulticallProvider>;

Registers a %%listener%% that is called the next time %%event%% occurs.

Parameters
ParameterType
eventProviderEvent
listenerListener
Returns

Promise<InjectedMulticallProvider>

Inherited from
ethers.BrowserProvider.once
emit()
emit(event, ...args): Promise<boolean>;

Triggers each listener for %%event%% with the %%args%%.

Parameters
ParameterType
eventProviderEvent
argsany[]
Returns

Promise<boolean>

Inherited from
ethers.BrowserProvider.emit
listenerCount()
listenerCount(event?): Promise<number>;

Resolves to the number of listeners for %%event%%.

Parameters
ParameterType
event?ProviderEvent
Returns

Promise<number>

Inherited from
ethers.BrowserProvider.listenerCount
listeners()
listeners(event?): Promise<Listener[]>;

Resolves to the listeners for %%event%%.

Parameters
ParameterType
event?ProviderEvent
Returns

Promise<Listener[]>

Inherited from
ethers.BrowserProvider.listeners
off()
off(event, listener?): Promise<InjectedMulticallProvider>;

Unregister the %%listener%% for %%event%%. If %%listener%% is unspecified, all listeners are unregistered.

Parameters
ParameterType
eventProviderEvent
listener?Listener
Returns

Promise<InjectedMulticallProvider>

Inherited from
ethers.BrowserProvider.off
removeAllListeners()
removeAllListeners(event?): Promise<InjectedMulticallProvider>;

Unregister all listeners for %%event%%.

Parameters
ParameterType
event?ProviderEvent
Returns

Promise<InjectedMulticallProvider>

Inherited from
ethers.BrowserProvider.removeAllListeners
addListener()
addListener(event, listener): Promise<InjectedMulticallProvider>;

Alias for [[on]].

Parameters
ParameterType
eventProviderEvent
listenerListener
Returns

Promise<InjectedMulticallProvider>

Inherited from
ethers.BrowserProvider.addListener
removeListener()
removeListener(event, listener): Promise<InjectedMulticallProvider>;

Alias for [[off]].

Parameters
ParameterType
eventProviderEvent
listenerListener
Returns

Promise<InjectedMulticallProvider>

Inherited from
ethers.BrowserProvider.removeListener
pause()
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
ParameterType
dropWhilePaused?boolean
Returns

void

Inherited from
ethers.BrowserProvider.pause
resume()
resume(): void;

Resume the provider.

Returns

void

Inherited from
ethers.BrowserProvider.resume
send()
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
ParameterType
methodstring
paramsany[] | 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
ParameterType
payloadJsonRpcPayload | JsonRpcPayload[]
Returns

Promise<(JsonRpcResult | JsonRpcError)[]>

Inherited from
ethers.BrowserProvider._send
getRpcError()
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
ParameterType
payloadJsonRpcPayload
errorJsonRpcError
Returns

Error

Inherited from
ethers.BrowserProvider.getRpcError
hasSigner()
hasSigner(address): Promise<boolean>;

Resolves to true if the provider manages the %%address%%.

Parameters
ParameterType
addressstring | number
Returns

Promise<boolean>

Inherited from
ethers.BrowserProvider.hasSigner
getSigner()
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
ParameterType
address?string | number
Returns

Promise<JsonRpcSigner>

Inherited from
ethers.BrowserProvider.getSigner
discover()
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
ParameterType
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
ParameterType
keyK
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
ParameterType
reqPerformActionRequest
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._waitUntilReady
getRpcTransaction()
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
ParameterType
txTransactionRequest
Returns

JsonRpcTransactionRequest

Inherited from
ethers.BrowserProvider.getRpcTransaction
getRpcRequest()
getRpcRequest(req): | { method: string; args: any[]; } | null;

Returns the request method and arguments required to perform %%req%%.

Parameters
ParameterType
reqPerformActionRequest
Returns

| { method: string; args: any[]; } | null

Inherited from
ethers.BrowserProvider.getRpcRequest
listAccounts()
listAccounts(): Promise<JsonRpcSigner[]>;
Returns

Promise<JsonRpcSigner[]>

Inherited from
ethers.BrowserProvider.listAccounts
destroy()
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
ParameterType
subSubscription
Returns

Subscriber

Inherited from
ethers.BrowserProvider._getSubscriber

Interfaces

MulticallRequest

Properties

PropertyType
targetstring
callDatastring

MulticallResult

Properties

PropertyType
successboolean
returnDatastring

ContractAddresses

Addresses of every core zkScatter contract on a given chain.

Properties

PropertyTypeDescription
privateSettlementstringPrivateSettlement: settles matched private orders + DEX swaps.
commitmentPoolstringCommitmentPool: holds escrowed funds, anchors the merkle tree.
identityGatestringIdentityGate: zk-X509 verification status.
relayerRegistrystringRelayerRegistry: public relayer directory.
issuanceApprovalRegistry?stringIssuanceApprovalRegistry: admin-recorded approvals that gate the operators app’s “Get your cert” CTA. Optional — apps that don’t surface the cert-issuance flow leave this unset.
feeVault?stringFeeVault (optional in test environments).
wethstringWETH address on the chain (also used as the native-ETH token slot).

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

PropertyTypeDescription
chainIdnumber-
name?stringDisplay name; falls back to chainName(chainId) when omitted.
rpcUrlstring-
explorerBase?stringBlock explorer base URL (e.g. https://sepolia.etherscan.io).
contractsContractAddresses-
tokensTokenInfo[]-
relayer?{ url: string; }Default relayer URL used when the user hasn’t picked one.
relayer.urlstring-
sharedOrderbookUrl?stringShared orderbook service URL (cross-relayer order discovery).
zkX509Url?stringzk-X509 verification flow URL.
deployBlock?numberBlock 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

PropertyType
commitmentbigint
leafIndexnumber

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

PropertyTypeDescription
fromBlock?string | number | bigintBlock tag (number, decimal/hex string, or bigint). Env-derived values like NEXT_PUBLIC_PAY_DEPLOY_BLOCK arrive as strings, so a number-only type would silently drop them — accept all three.
toBlock?string | number | bigint-
chunkSize?numberMax blocks per eth_getLogs window (default 50 000).

FetchCommitmentLeavesOptions

Properties

PropertyTypeDescription
fetchImpl?{ (input, init?): Promise<Response>; (input, init?): Promise<Response>; (input, init?): Promise<Response>; }Injectable for tests; defaults to the global fetch.
pageSize?numberOverride the page size (defaults to SERVER_PAGE_SIZE).

TokenInfo

A token an app can offer in pickers, balances, orders.

Extended by

Properties

PropertyTypeDescription
addressstringOn-chain ERC-20 address. For native ETH this is the WETH slot.
symbolstring-
decimalsnumber-
isNativebooleanTrue for the synthetic “ETH” entry that wraps/unwraps via WETH.

WhitelistedToken

A token an app can offer in pickers, balances, orders.

Extends

Properties

PropertyTypeDescriptionInherited from
addressstringOn-chain ERC-20 address. For native ETH this is the WETH slot.TokenInfo.address
symbolstring-TokenInfo.symbol
decimalsnumber-TokenInfo.decimals
isNativebooleanTrue for the synthetic “ETH” entry that wraps/unwraps via WETH.TokenInfo.isNative
namestringDisplay 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?booleanTrue 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?booleanTrue when launch-event 0% fee applies. Today: all four tokens.-

WhitelistedPair

Properties

PropertyTypeDescription
displaystring${baseSymbol}/${quoteSymbol} — the canonical display string (also the key used by the shared orderbook).
basestring-
quotestring-
featured?booleanFeatured pairs render at the top of the picker and are the default selection for new sessions.

FetchWhitelistedTokensOptions

Options for fetchWhitelistedTokens.

Extended by

Properties

PropertyTypeDescription
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

PropertyTypeDescription
tokenTokenInfo-
inPoolbooleanWhitelisted on the CommitmentPool (deposit side).
inSettlementbooleanWhitelisted on the PrivateSettlement (settle/claim side).

WriteTx

Minimal shape returned by a contract write — hash plus wait().

Properties

PropertyType
hashstring

Methods

wait()
wait(): Promise< | { hash?: string; } | null>;
Returns

Promise< | { hash?: string; } | null>


RunWriteOpts

Properties

PropertyTypeDescription
estimateProvider?Provider | nullProvider used for the gas/fee/nonce preflight. Prefer a reliable endpoint (e.g. the public-RPC fallback) here: when the user’s wallet RPC is throttled, letting ethers run its own preflight through the wallet is exactly what surfaces as the opaque “could not coalesce error”. Pre-computing the overrides on a reliable provider and handing them to the wallet means the wallet only has to broadcast. Defaults to the signer’s own provider.
fallbackGasLimit?bigintGas ceiling used when estimation fails for a transient reason (RPC throttle/timeout). A genuine revert is rethrown instead, so the caller sees the real reason. Default 1_000_000.

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

ParameterType
addrstring | 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

ParameterType
providerProvider
requestsMulticallRequest[]

Returns

Promise<MulticallResult[]>


encodeCall()

function encodeCall( iface, functionName, args): string;

Encode a contract function call for multicall batching.

Parameters

ParameterType
ifaceInterface
functionNamestring
argsunknown[]

Returns

string


decodeResult()

function decodeResult( iface, functionName, data): Result;

Decode a multicall sub-call result.

Parameters

ParameterType
ifaceInterface
functionNamestring
datastring

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

ParameterType
chainIdnumber

Returns

string


chainName()

function chainName(chainId): string;

Parameters

ParameterType
chainIdnumber

Returns

string


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

ParameterType
networkPick<NetworkConfig, "chainId" | "explorerBase">
entityExplorerEntity
valuestring

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

ParameterType
providerProvider
poolAddressstring
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

ParameterType
serverUrlstring
chainIdnumber | 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

ParameterType
providerProvider
poolAddressstring
rootbigint

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

ParameterType
providerProvider
poolAddressstring

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

ParameterType
providerProvider
poolAddressstring
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

ParameterType
rpcUrlstring

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

ParameterType
rawstring | null | undefined

Returns

TokenInfo[]


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

ParameterType
tokensTokenInfo[]
wethAddressstring

Returns

TokenInfo[]


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

ParameterType
tokensTokenInfo[]

Returns

TokenInfo[]


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

ParameterType
curatedTokenInfo[]
onchainTokenInfo[]
wethAddressstring

Returns

TokenInfo[]


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

ParameterType
astring | null | undefined
bstring | 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

ParameterType
tokensTokenInfo[]

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

ParameterType
symbolstring

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

ParameterTypeDefault value
pairsreadonly WhitelistedPair[]LAUNCH_PAIRS

Returns

Record<QuoteMarket, WhitelistedPair[]>


findPair()

function findPair(display, pairs?): WhitelistedPair | undefined;

Find a pair entry by its display string.

Parameters

ParameterTypeDefault value
displaystringundefined
pairsreadonly 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

ParameterType
tokensreadonly 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

ParameterType
providerProvider
poolAddressstring
settlementAddressstring
optionsFetchWhitelistedTokensOptions

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

ParameterType
providerProvider
poolAddressstring
settlementAddressstring
optionsFetchWhitelistedTokensOptions

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

ParameterType
contractContract
fnstring
argsreadonly unknown[]
optsRunWriteOpts

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

ParameterType
contractContract
fnstring
argsreadonly unknown[]
optsRunWriteOpts

Returns

Promise<Overrides>

Last updated on