Skip to Content
SDK ReferenceTypeScript APIrelayer
SDK reference (auto)

relayer

Classes

RelayerClient

Thin HTTP client for one relayer’s API. No retry, no caching; callers compose those concerns. Errors throw with the relayer’s error body field when present, falling back to the HTTP status line. Every method accepts an optional signal so callers can cancel from a UI’s AbortController.

Constructors

Constructor
new RelayerClient(baseUrl, opts?): RelayerClient;
Parameters
ParameterType
baseUrlstring
optsClientOpts
Returns

RelayerClient

Methods

getInfo()
getInfo(signal?): Promise<RelayerApiInfo>;
Parameters
ParameterType
signal?AbortSignal
Returns

Promise<RelayerApiInfo>

getStats()
getStats(signal?): Promise<RelayerStatsResponse>;

Public stats from /api/relayer/stats — operational counters (totalOrders, settledOrders, avgSettleTimeMs, …). No auth, no PII; surfaces for cross-relayer comparison on the leaderboard.

Parameters
ParameterType
signal?AbortSignal
Returns

Promise<RelayerStatsResponse>

submitOrder()
submitOrder( order, signature, feeMode?, signal?): Promise<{ status: string; txHash?: string; nonce?: string; }>;
Parameters
ParameterType
orderOrderData
signaturestring
feeMode?"cover_taker"
signal?AbortSignal
Returns

Promise<{ status: string; txHash?: string; nonce?: string; }>

getOrders()
getOrders(address, signal?): Promise<RelayerOrder[]>;
Parameters
ParameterType
addressstring
signal?AbortSignal
Returns

Promise<RelayerOrder[]>

getOrderHistory()
getOrderHistory(address, opts?): Promise<OrderHistoryResponse>;
Parameters
ParameterType
addressstring
opts{ status?: string; limit?: number; offset?: number; signal?: AbortSignal; }
opts.status?string
opts.limit?number
opts.offset?number
opts.signal?AbortSignal
Returns

Promise<OrderHistoryResponse>

getOrderDetail()
getOrderDetail( address, nonce, signal?): Promise<RelayerOrder>;
Parameters
ParameterType
addressstring
noncestring
signal?AbortSignal
Returns

Promise<RelayerOrder>

cancelOrder()
cancelOrder( address, nonce, signature, signal?): Promise<void>;
Parameters
ParameterType
addressstring
noncenumber
signaturestring
signal?AbortSignal
Returns

Promise<void>

submitClaim()
submitClaim(body, signal?): Promise<{ status: string; txHash: string; }>;

Submit a recipient’s claim for the relayer to dispatch. Pairs with POST /api/private-claim on zk-relayer (route validates the proof + the claimsRoot the relayer settled). The relayer pays gas in exchange for having earned the settle fee.

Parameters
ParameterType
bodyGaslessClaimBody
signal?AbortSignal
Returns

Promise<{ status: string; txHash: string; }>

submitAuthorizeOrder()
submitAuthorizeOrder(body, signal?): Promise<AuthorizeOrderStatus>;

Submit a same-token scatter authorize proof for the relayer to dispatch via scatterDirectAuth. Pairs with POST /api/authorize-orders on zk-relayer; the order is queued and the relayer’s settlement worker calls the contract once the pre-flight checks pass. The endpoint returns a 202 with the nullifier, which the caller polls via pollAuthorizeOrder until settleTxHash lands.

Parameters
ParameterType
bodyAuthorizeOrderBody
signal?AbortSignal
Returns

Promise<AuthorizeOrderStatus>

pollAuthorizeOrder()
pollAuthorizeOrder(nullifier, signal?): Promise<AuthorizeOrderStatus>;

Poll the order status. Used after submitAuthorizeOrder to wait for the relayer to actually broadcast the scatterDirectAuth tx.

Parameters
ParameterType
nullifierstring
signal?AbortSignal
Returns

Promise<AuthorizeOrderStatus>

Interfaces

AuthorizeOrderBody

Wire-format body for POST /api/authorize-orders — same shape the legacy frontend sends. publicSignals is the named-field view; publicSignalsArray mirrors the raw circom output that the relayer re-verifies.

Properties

PropertyType
proof{ a: [string, string]; b: [[string, string], [string, string]]; c: [string, string]; }
proof.a[string, string]
proof.b[[string, string], [string, string]]
proof.c[string, string]
publicSignals{ pubKeyBind: string; commitmentRoot: string; nullifier: string; nonceNullifier: string; newCommitment: string; sellToken: string; buyToken: string; sellAmount: string; buyAmount: string; maxFee: string; expiry: string; claimsRoot: string; totalLocked: string; relayer: string; orderHash: string; }
publicSignals.pubKeyBindstring
publicSignals.commitmentRootstring
publicSignals.nullifierstring
publicSignals.nonceNullifierstring
publicSignals.newCommitmentstring
publicSignals.sellTokenstring
publicSignals.buyTokenstring
publicSignals.sellAmountstring
publicSignals.buyAmountstring
publicSignals.maxFeestring
publicSignals.expirystring
publicSignals.claimsRootstring
publicSignals.totalLockedstring
publicSignals.relayerstring
publicSignals.orderHashstring
publicSignalsArrayreadonly string[]
tiernumber
pubKeyAxstring
pubKeyAystring

AuthorizeOrderStatus

Properties

PropertyTypeDescription
statusstring-
submittedAt?number-
updatedAt?number-
attempt?number-
settleTxHashstring | nullSet once the relayer broadcasts the scatterDirectAuth tx.
error?string | null-
expiresAt?number-
nullifier?string-
pollUrl?string-

GaslessClaimBody

Wire-format request body for POST /api/private-claim. The relayer revalidates every field on-chain so the recipient page doesn’t have to sign anything; submitting through a relayer is purely a gas-payment relationship.

Properties

PropertyTypeDescription
proofA[string, string]Decimal-string scalars to keep BigInts JSON-safe.
proofB[[string, string], [string, string]]-
proofC[string, string]-
claimsRootstringBytes32 hex.
claimNullifierstring-
amountstringDecimal-string bigint.
tokenstringAddress.
recipientstring-
releaseTimestringDecimal-string bigint.

FeeVaultBalance

Properties

PropertyTypeDescription
tokenTokenInfo-
balancebigintOperator’s claimable balance in the token’s smallest unit.

PendingFeeChange

A scheduled platform-fee change waiting on the timelock. Returns null when no change is pending (the contract zeros both fields once a change is applied or cancelled). effectiveAt is the unix second when applyFeeChange() becomes callable.

Properties

PropertyType
bpsnumber
effectiveAtnumber

IdentityVerification

Properties

PropertyTypeDescription
isVerifiedboolean-
verifiedUntilnumberUnix seconds the verification expires at; 0 when not verified.

IdentityGateAdminSnapshot

Properties

PropertyTypeDescription
ownerstringContract owner — the only address that can call addRegistry / removeRegistry. UIs gate admin actions on this.
registriesstring[]All IdentityRegistry contracts trusted by this gate. The gate ORs their isVerified() results.

UpdateRelayerInfoParams

Properties

PropertyTypeDescription
urlstring-
name?stringOn-chain display name. Optional — defaults to empty when omitted.
feeBpsnumber-

OperatorRow

Properties

PropertyTypeDescription
idnumberStable on-chain id — index of this wallet in relayerList. -1 when the wallet has never registered (status “unregistered”).
addressstringThe wallet address this row belongs to (== the account passed to loadOperatorRow).
urlstring-
namestringOn-chain display name (may be empty for legacy registrations).
feeBpsnumber-
bondbigint-
bondEthstring-
registeredAtnumberUnix seconds the operator first registered, 0 when never registered.
exitRequestedAtnumberUnix seconds the operator requested exit, 0 when not in the cool-down window.
activeboolean-
statusOperatorStatus-
bondTokenstringBond token address, or ZeroAddress for native (msg.value) mode. Lets bond top-up UIs decide whether an approve step is needed before addBond.

ForceRemoval

Details of an admin-initiated removal (adminRemoveRelayer).

Properties

PropertyTypeDescription
reasonstringThe reason the admin recorded with the removal (may be empty).
exitAfternumberUnix seconds the bond becomes withdrawable (exitRequestedAt + EXIT_COOLDOWN), straight from the event.

RegistrationStatus

Properties

PropertyTypeDescription
isVerifiedboolean-
verifiedUntilnumberUnix seconds the identity verification expires at; 0 when not verified.
alreadyRegisteredboolean-
minBondbigint-
minBondEthstringminBond rendered as a decimal string for display, formatted with the bond token’s own bondTokenDecimals (so it’s correct for ERC20 bonds that don’t use 18 decimals, not just native ETH/TON).
bondTokenstringERC20 bond token address, or NATIVE_BOND_TOKEN (zero address) when the registry is in native mode.
isErc20BondbooleanConvenience: true iff bondToken !== NATIVE_BOND_TOKEN.
bondTokenSymbolstringBond token symbol for display — "ETH" in native mode, else the ERC20 token’s symbol() (e.g. "TON"). The admin sets the bond token on-chain; the UI must surface whatever it actually is rather than assuming ETH.
bondTokenDecimalsnumberBond token decimals — 18 in native mode, else the ERC20 decimals(). Use this to parse/format bond amounts.
bondAllowancebigintERC20 allowance the operator has already granted the registry, in token base units. 0n in native mode (no approval needed).
bondBalancebigintOperator’s current balance of the bond token (native ETH balance in native mode), in token base units. Lets the UI warn before a wallet prompt when the operator can’t cover the bond.
bondBalanceFormattedstringbondBalance rendered with bondTokenDecimals for display.

RegisterRelayerParams

Properties

PropertyTypeDescription
urlstring-
name?stringOn-chain display name surfaced via relayers() and consumed by Pay/Operators UIs. Optional — defaults to empty when omitted.
feeBpsnumber-
bondEthstringBond as a decimal string (e.g. "0.1"). Parsed internally with bondDecimals so callers don’t need their own ethers dependency.
bondToken?stringRequired when the registry is in ERC20 mode. Use the value from RegistrationStatus.bondToken. Pass NATIVE_BOND_TOKEN (or omit) for native mode.
bondDecimals?numberDecimals to parse bondEth with. Defaults to 18 (native ETH and standard ERC20 TON); pass RegistrationStatus.bondTokenDecimals for an ERC20 bond token with non-18 decimals.

BondMeta

Bond token metadata used to render the InsufficientBond minimum in the operator’s actual bond token rather than assuming ETH.

Properties

PropertyType
symbol?string
decimals?number

LoadOpts

Properties

PropertyTypeDescription
probeTimeoutMs?numberPer-relayer probe timeout. Defaults to 3 s — long enough for a healthy node, short enough that one stuck node doesn’t drag the whole list.
withStats?booleanWhen true, also probe /api/relayer/stats per relayer in parallel with /api/info. Info-success / stats-failure leaves stats: undefined (older relayer build, transport error).

RelayerSettlement

Properties

PropertyTypeDescription
txHashstring-
blockNumbernumber-
transactionIndexnumberPosition within the block — together with blockNumber and logIndex it forms a globally unique identity for the settlement. Lets React keys stay stable when several settlements share a block, and gives generalized event-feed consumers a deterministic tiebreaker.
logIndexnumber-
roleSettlementRole-
feebigintFee accrued to the relayer in this settlement, in the fee-token’s smallest unit.

LoadSettlementsOpts

Properties

PropertyTypeDescription
fromBlock?BlockTagBlock to start scanning from. Defaults to 0 (full history) but callers should always pass an explicit lower bound — use NetworkConfig.deployBlock, or compute a reorg-safe window via the host app’s provider helper — to keep RPC traffic bounded on busy relayers. Accepts the full ethers BlockTag range.
toBlock?BlockTagBlock to end the scan at. Defaults to "latest". Pair with fromBlock to scan a rolling window when only the most recent N events matter. Accepts the full ethers BlockTag range ("latest" / "finalized" / "safe" / a block number / hex string / bigint).
limit?numberCap on the number of events returned, sorted newest-first. Default: no cap.

RelayerOnChain

Relayer info as recorded in the on-chain RelayerRegistry.

Extended by

Properties

PropertyTypeDescription
idnumber0-based index in the registry’s relayerList — the relayer’s stable on-chain id, assigned at first registration.
addressstring-
urlstring-
namestringOperator-set display name from the registry. May be the empty string for legacy entries that registered before the name field was added.
feenumberPer-trade fee in basis points (100 = 1%).
bondbigintBond posted to register, in wei.
registeredAtnumber-
exitRequestedAtnumber-
activeboolean-

RelayerProfile

Optional metadata a relayer publishes via its /api/info. We trust nothing inside profile: see sanitizeProfile.

Properties

PropertyType
name?string
description?string
logoUrl?string
contact?string
socialX?string
website?string
updatedAt?number

RelayerApiInfo

Live response from a relayer’s /api/info.

Properties

PropertyTypeDescription
namestring-
versionstring-
addressstring-
feenumber-
orderCountnumber-
commitmentPoolstringAddress of the on-chain CommitmentPool the relayer reads from. Mirrors commitmentPool in zk-relayer/src/routes/info.ts — the older single settlement field was inaccurate (the response has always returned the two contracts separately).
privateSettlementstringAddress of the PrivateSettlement contract the relayer submits to.
profile?RelayerProfile-
gasless_fees?Record<string, string>Per-token gasless-transfer fee policy. Symbol → decimal-string amount in token-units, e.g. { USDC: "0.10", USDT: "0.10", TON: "1.0" }. Empty / missing when the relayer hasn’t configured a policy, in which case its /api/transfer-7702/relay rejects with token not supported.
claim_fees?Record<string, string>Per-recipient claim-gasless reserve policy. Symbol → decimal- string amount in token-units, e.g. { USDC: "0.05", USDT: "0.05", TON: "0.5" }. Multiplied by the run’s recipient count and added to the bps service fee at settle time. Empty / missing when the platform hasn’t published a policy — operator UI falls back to legacy service-fee-only behavior.

RelayerSettledVolume

Per-token settled volume (one row per sell_token). totalVolume is a wei-string (BigInt-safe) so callers can BigInt() it back.

Properties

PropertyType
sellTokenstring
countnumber
totalVolumestring

RelayerRuntimeMetrics

In-memory metrics shape returned alongside DB-derived counters. Optional because older relayer builds don’t compute it.

Properties

PropertyType
gas{ avgCostEth: number | null; minCostEth: number | null; maxCostEth: number | null; lastCostEth: number | null; totalSpentEth: number; }
gas.avgCostEthnumber | null
gas.minCostEthnumber | null
gas.maxCostEthnumber | null
gas.lastCostEthnumber | null
gas.totalSpentEthnumber
settlement{ avgDurationMs: number | null; minDurationMs: number | null; maxDurationMs: number | null; lastDurationMs: number | null; totalCount: number; perMinute: number; }
settlement.avgDurationMsnumber | null
settlement.minDurationMsnumber | null
settlement.maxDurationMsnumber | null
settlement.lastDurationMsnumber | null
settlement.totalCountnumber
settlement.perMinutenumber
orders{ submittedPerMinute: number; }
orders.submittedPerMinutenumber
sampleSizenumber

RelayerStatsResponse

Public stats from a relayer’s /api/relayer/stats. Surfaced for cross-relayer comparison (leaderboard performance columns).

  • avgSettleTimeMs is null when there are no confirmed settlements in the window (the SQL AVG returns null).
  • uptimeSince is null when the started_at meta key is missing or unparseable — independent of settlement count.

Properties

PropertyTypeDescription
addressstring-
totalOrdersnumber-
settledOrdersnumber-
successRatenumber-
crossRelayerSettlednumber-
totalTradeOffersnumber-
settledTradeOffersnumber-
avgSettleTimeMsnumber | null-
uptimeSincenumber | null-
pendingOrdersnumber-
settledVolume?RelayerSettledVolume[]-
feeTotals?{ token: string; count: number; totalWei: string; }[]Per-token fee revenue across this relayer’s lifetime. Sum of fee_history rows grouped by token, exposed publicly so the leaderboard can rank “who earned the most” without each visitor needing peer admin keys. Same shape as the operator analytics page’s /history/fees aggregate.
metrics?RelayerRuntimeMetrics-
byApp?{ pay: RelayerStatsByApp; pro: RelayerStatsByApp; }Per-app (Pay = scatterDirectAuth, Pro = settleAuth) breakdown of counts / volume / fees. Optional: older relayers omit this field and consumers degrade to the aggregate view for that row.
byApp.payRelayerStatsByApp-
byApp.proRelayerStatsByApp-

RelayerStatsByApp

Per-app subset of RelayerStatsResponse. Mirrors the aggregate fields the leaderboard ranks on (orders / volume / fees) so the segmented control can re-rank using the same comparator logic.

Properties

PropertyType
totalOrdersnumber
settledOrdersnumber
settledVolume?RelayerSettledVolume[]
feeTotals?{ token: string; count: number; totalWei: string; }[]

RelayerInfo

Combined view: on-chain registry data + live /api/info probe. api is undefined when the relayer is offline / unreachable. stats is undefined when the stats probe failed (older relayer build, network error, or feature not enabled).

Extends

Properties

PropertyTypeDescriptionInherited from
idnumber0-based index in the registry’s relayerList — the relayer’s stable on-chain id, assigned at first registration.RelayerOnChain.id
addressstring-RelayerOnChain.address
urlstring-RelayerOnChain.url
namestringOperator-set display name from the registry. May be the empty string for legacy entries that registered before the name field was added.RelayerOnChain.name
feenumberPer-trade fee in basis points (100 = 1%).RelayerOnChain.fee
bondbigintBond posted to register, in wei.RelayerOnChain.bond
registeredAtnumber-RelayerOnChain.registeredAt
exitRequestedAtnumber-RelayerOnChain.exitRequestedAt
activeboolean-RelayerOnChain.active
api?RelayerApiInfo--
stats?RelayerStatsResponse--
onlineboolean--

RelayerOrder

A single submitted order as the relayer reports it.

Properties

PropertyType
makerstring
sellTokenstring
buyTokenstring
sellAmountstring
buyAmountstring
noncestring
maxFeestring
expirystring
feeMode?string
statusstring
submittedAtnumber
settleTxHash?string
claims?{ claimHash: string; amount: string; releaseDelay: string; }[]

OrderHistoryResponse

Properties

PropertyType
ordersRelayerOrder[]
totalnumber
limitnumber
offsetnumber

OrderData

Order payload as the relayer expects it on submit.

Properties

PropertyType
makerstring
sellTokenstring
buyTokenstring
sellAmountstring
buyAmountstring
maxFeenumber
expirynumber
noncenumber
claims{ claimHash: string; amount: string; releaseDelay: number; }[]

Type Aliases

OperatorStatus

type OperatorStatus = "active" | "cooldown" | "offline" | "unregistered";

UI-friendly status derived from the on-chain relayers() row.

  • unregistered: never registered on this registry
  • active: registered, not in the exit cool-down
  • cooldown: requested exit, waiting out the exit cool-down
  • offline: registered + exit executed (the row’s active flag is false but registeredAt is non-zero)

SettlementRole

type SettlementRole = "maker" | "taker";

AppSegment

type AppSegment = "pay" | "pro";

One of the two app flows the relayer surfaces in byApp: Pay maps to scatterDirectAuth (single-party direct payouts) and Pro maps to settleAuth (half-proof order matches). Callers model the “All” / aggregate view at the UI layer, not via this type — the aggregate stats already live on RelayerStatsResponse itself, so no null member is needed here.


FeeMode

type FeeMode = "cover_taker";

Fee modes the relayer accepts on submitOrder.

Variables

EXIT_COOLDOWN_SECONDS

const EXIT_COOLDOWN_SECONDS: number;

The registry’s default exit cool-down (7 days). The live value is governance-settable via setExitCooldown and read back from exitCooldown(), so this is only a fallback for the brief window before the live read resolves — UIs that render the countdown or compute the withdrawable time MUST prefer loadExitCooldownSeconds and not bake this constant into either calculation.


NATIVE_BOND_TOKEN

const NATIVE_BOND_TOKEN: string = ethers.ZeroAddress;

Sentinel for native (msg.value) bond mode — bondToken() returns the zero address on registries deployed in native mode (e.g. on Tokamak L2 where TON is the native gas token).


MAX_RELAYER_FEE_BPS

const MAX_RELAYER_FEE_BPS: 500 = 500;

Maximum per-trade fee a relayer may register, in basis points. Mirrors RelayerRegistry.MAX_FEE (50 bps) — kept in sync here so the SDK can reject invalid input before a wallet prompt and so consumer apps don’t redeclare the magic number.

Functions

callExceptionErrorName()

function callExceptionErrorName(err): string | null;

Read the named error off ethers v6 contract-call exceptions when the ABI carries the matching error fragment. Falls back to null so callers can substring-match the message instead. Shared by every per-contract explainXxxError in the relayer module.

Parameters

ParameterType
errunknown

Returns

string | null


unwrapEthersError()

function unwrapEthersError(err): string;

Best-effort unwrap of an ethers v6 error to a human-readable string. v6 surfaces the user-facing summary on shortMessage, the decoded revert reason on reason, and the underlying provider error on info.error.message. Fall through these in priority order before landing on the raw Error.message so callers (read-side error banners, write-side explainXxxError) always have the most descriptive string available.

Parameters

ParameterType
errunknown

Returns

string


loadFeeVaultBalances()

function loadFeeVaultBalances( feeVaultAddress, operator, tokens, provider): Promise<FeeVaultBalance[]>;

Read every passed token’s claimable balance for operator in one shot. Caller decides which tokens to query — typically the network’s tokens whitelist — so this stays a pure batched read with no contract-side enumeration assumed. Tokens whose address is the zero sentinel (unconfigured slot in a partially deployed network config) are skipped.

Parameters

ParameterType
feeVaultAddressstring
operatorstring
tokensTokenInfo[]
providerProvider

Returns

Promise<FeeVaultBalance[]>


loadPlatformFeeBps()

function loadPlatformFeeBps(feeVaultAddress, provider): Promise<number>;

Read the platform-fee cut (in basis points) that FeeVault skims off the top of every relayer claim(). 0 means no platform cut. Returned as a plain number because the contract caps it at MAX_PLATFORM_FEE (≤ 10_000), well inside safe integer range.

Parameters

ParameterType
feeVaultAddressstring
providerProvider

Returns

Promise<number>


loadPendingFeeChange()

function loadPendingFeeChange(feeVaultAddress, provider): Promise<PendingFeeChange | null>;

Parameters

ParameterType
feeVaultAddressstring
providerProvider

Returns

Promise<PendingFeeChange | null>


claimRelayerFees()

function claimRelayerFees( feeVaultAddress, tokenAddress, signer): Promise<TransactionResponse>;

Submit claim(token) to pull the operator’s accrued balance for a single token. Reverts with NothingToClaim when the balance is zero — gate the button on a non-zero balance read so the wallet prompt never lands on a guaranteed-fail tx.

Parameters

ParameterType
feeVaultAddressstring
tokenAddressstring
signerSigner

Returns

Promise<TransactionResponse>


explainFeeVaultError()

function explainFeeVaultError(err): string;

Map FeeVault custom-error reverts to user-facing copy. Falls back to the unwrapped ethers v6 message so unexpected errors still surface a useful string instead of [object Object].

Parameters

ParameterType
errunknown

Returns

string


loadIdentityGateAdmin()

function loadIdentityGateAdmin(gateAddress, provider): Promise<IdentityGateAdminSnapshot>;

One-shot admin read for the IdentityGate management UI. Pure read — no mutation.

Parameters

ParameterType
gateAddressstring
providerProvider

Returns

Promise<IdentityGateAdminSnapshot>


loadIdentityVerification()

function loadIdentityVerification( gateAddress, account, provider): Promise<IdentityVerification>;

Read an account’s verification status from an arbitrary IdentityGate contract. zkScatter’s Dual-CA architecture deploys one gate per CA (User CA = privacy-preserving, Relayer CA = full-disclosure), so callers pass the gate address explicitly rather than letting the SDK guess one. Pure read.

Parameters

ParameterType
gateAddressstring
accountstring
providerProvider

Returns

Promise<IdentityVerification>


loadExitCooldownSeconds()

function loadExitCooldownSeconds(registryAddress, provider): Promise<number>;

Read the live exit cool-down (in seconds) from the registry’s exitCooldown() getter. Governance can rewrite it via setExitCooldown, so the displayed cool-down and the bond withdrawable time must both derive from this value rather than the EXIT_COOLDOWN_SECONDS fallback. Pure read.

Parameters

ParameterType
registryAddressstring
providerProvider

Returns

Promise<number>


updateRelayerInfo()

function updateRelayerInfo( registryAddress, params, signer): Promise<TransactionResponse>;

Submit updateInfo(url, name, fee) — operator-self-service edit of endpoint URL, display name, and per-trade fee. Validates the fee range up front for the same UX reason registerRelayer does.

Parameters

ParameterType
registryAddressstring
paramsUpdateRelayerInfoParams
signerSigner

Returns

Promise<TransactionResponse>


addRelayerBond()

function addRelayerBond( registryAddress, bondEth, signer, bondToken?): Promise<TransactionResponse>;

Submit addBond(bondAmount).

  • Native mode: top-up paid via msg.value.
  • ERC20 mode: caller MUST approve the registry for at least bondEth first (see approveBondToken); this helper just submits the addBond call.

When bondToken is omitted, the helper reads bondToken() from the registry itself — convenient for simple top-up UIs that already hold the registry address but not its mode.

Rejects zero / negative amounts before a wallet prompt.

Parameters

ParameterType
registryAddressstring
bondEthstring
signerSigner
bondToken?string

Returns

Promise<TransactionResponse>


requestRelayerExit()

function requestRelayerExit(registryAddress, signer): Promise<TransactionResponse>;

Submit requestExit() — flips the operator into the cool-down window. New orders stop routing immediately; bond becomes withdrawable via executeRelayerExit after EXIT_COOLDOWN_SECONDS.

Parameters

ParameterType
registryAddressstring
signerSigner

Returns

Promise<TransactionResponse>


executeRelayerExit()

function executeRelayerExit(registryAddress, signer): Promise<TransactionResponse>;

Submit executeExit() — finalises the exit and returns the bond. Will revert with CooldownNotPassed until the cool-down window has elapsed; gate the button on cooldownReadyAt.

Parameters

ParameterType
registryAddressstring
signerSigner

Returns

Promise<TransactionResponse>


loadOperatorRow()

function loadOperatorRow( registryAddress, account, provider): Promise<OperatorRow>;

Read the on-chain registry row for account. Returns the full set of operator-scoped state every dashboard / profile / treasury page needs, plus a derived status for UI gating. Pure read.

Issues one RPC after the first call per registry: the row read. bondToken is fetched once and memoised because it’s immutable.

Parameters

ParameterType
registryAddressstring
accountstring
providerProvider

Returns

Promise<OperatorRow>


loadForceRemoval()

function loadForceRemoval( registryAddress, relayer, provider, fromBlock?): Promise<ForceRemoval | null>;

Whether relayer was removed by an admin (vs a voluntary exit). Returns the most recent RelayerForceRemoved event’s details, or null when the relayer exited on their own (no such event).

An admin removal sets the same exitRequestedAt cool-down as a self requestExit, so a forced relayer’s row is indistinguishable from a voluntary exit by state alone — the event is the only signal. Only meaningful while the operator is in the cooldown status; call it there, not on every row read.

Uses queryFilter (not contract.on) — event subscriptions stop firing on anvil, and this is a one-shot read anyway.

Parameters

ParameterType
registryAddressstring
relayerstring
providerProvider
fromBlock?BlockTag

Returns

Promise<ForceRemoval | null>


sanitizeProfile()

function sanitizeProfile(input): RelayerProfile | undefined;

Sanitize the profile block returned by an arbitrary relayer’s /api/info. We trust nothing here: keep only known string fields, enforce a length cap, reject URL fields whose scheme isn’t on the allowlist. Guards against:

  • UI crashes from non-string fields breaking .replace etc.
  • rendered-link XSS via javascript: / data: schemes
  • DOS via huge strings

Returns undefined when the input isn’t a plain object.

Parameters

ParameterType
inputunknown

Returns

RelayerProfile | undefined


loadRegistrationStatus()

function loadRegistrationStatus( registryAddress, account, provider): Promise<RegistrationStatus>;

Read the prerequisite state for relayer registration: identity verification, prior active-relayer status, the registry’s current minimum bond, and (in ERC20 mode) the operator’s existing allowance.

Parameters

ParameterType
registryAddressstring
accountstring
providerProvider

Returns

Promise<RegistrationStatus>


registerRelayer()

function registerRelayer( registryAddress, params, signer): Promise<TransactionResponse>;

Submit register(url, name, fee, bondAmount).

  • Native mode (bondToken omitted or zero): bond paid via msg.value.
  • ERC20 mode: caller MUST approve the registry for at least bondAmount first (see approveBondToken); this helper just submits the register call.

Validates fee range and bond format up front so the user sees a clean error before a wallet prompt. Returns the transaction response; caller awaits .wait().

Parameters

ParameterType
registryAddressstring
paramsRegisterRelayerParams
signerSigner

Returns

Promise<TransactionResponse>


needsBondApproval()

function needsBondApproval(status, bondEth): boolean;

True when the registry is in ERC20 mode AND the operator’s current allowance is below the desired bond amount, i.e. an approve is required before register / addBond can succeed. Returns false in native mode regardless of the input.

Parameters

ParameterType
statusRegistrationStatus
bondEthstring

Returns

boolean


hasEnoughBondBalance()

function hasEnoughBondBalance(status, bondEth): boolean;

True when the operator holds enough of the bond token to cover bondEth — i.e. bondBalance >= parse(bondEth). In native mode bondBalance is the account’s ETH balance, so this only checks the bond amount, not the extra gas the register tx needs. Returns true on an unparseable amount so a transient input state never blocks the form (the on-chain transfer/msg.value still guards the bond).

Parameters

ParameterType
statusRegistrationStatus
bondEthstring

Returns

boolean


loadBondAllowance()

function loadBondAllowance( registryAddress, bondToken, account, provider): Promise<bigint>;

Read the operator’s current ERC20 bond-token allowance to the registry. Returns 0n in native mode (no token to query). Useful for top-up UIs that already know the bond token (e.g. via OperatorRow.bondToken) but only need the live allowance.

Parameters

ParameterType
registryAddressstring
bondTokenstring
accountstring
providerProvider

Returns

Promise<bigint>


approveBondToken()

function approveBondToken( bondToken, registryAddress, bondEth, signer, bondDecimals?): Promise<TransactionResponse>;

Submit ERC20.approve(registry, amount) so the operator can subsequently register or addBond in ERC20 mode. Native-mode registries never need this. Returns the transaction response; caller awaits .wait() before submitting the register call.

Parameters

ParameterTypeDefault value
bondTokenstringundefined
registryAddressstringundefined
bondEthstringundefined
signerSignerundefined
bondDecimalsnumber18

Returns

Promise<TransactionResponse>


explainRegistryError()

function explainRegistryError( err, minBond, bond?): string;

Map known registry custom errors (decoded by ethers from the ABI fragments on RELAYER_REGISTRY_ABI) and local validation errors thrown from any registry write helper to user-friendly copy. Falls back to the raw message when no rule matches so callers don’t swallow unexpected errors. minBond is only used when the error is InsufficientBond; pass 0n if unknown.

Parameters

ParameterType
errunknown
minBondbigint
bond?BondMeta

Returns

string


loadActiveRelayers()

function loadActiveRelayers(registryAddress, provider): Promise<RelayerOnChain[]>;

Read the registry contract’s active list and return the full on-chain row for each. Pure read; no side effects.

Parameters

ParameterType
registryAddressstring
providerProvider

Returns

Promise<RelayerOnChain[]>


loadRelayersWithApiInfo()

function loadRelayersWithApiInfo( registryAddress, provider, opts?): Promise<RelayerInfo[]>;

Combine on-chain registry data with a live /api/info probe per relayer. Probes run in parallel; offline relayers come back with online: false and api: undefined.

When withStats is set, also probes /api/relayer/stats in parallel with /api/info. The two probes are independent — a relayer can be online: true (info ok) but have stats: undefined if it’s an older build that doesn’t expose the endpoint.

Parameters

ParameterType
registryAddressstring
providerProvider
optsLoadOpts

Returns

Promise<RelayerInfo[]>


loadRelayersWithSharedOrderbookStats()

function loadRelayersWithSharedOrderbookStats( registryAddress, provider, sharedOrderbookUrl, opts?): Promise<RelayerInfo[]>;

Combine on-chain registry + live /api/info (per-peer health probe)

  • per-relayer stats aggregated from the shared orderbook indexer instead of each peer’s local DB.

Why prefer shared-OB over peer /api/relayer/stats?

  • Survives relayer DB wipe. Peer local DBs reset whenever the relayer is restarted with RESET_STATE=1 or rm’d manually; the shared-OB indexer is the durable source of truth.
  • No double-count. Each on-chain settle is one row in shared-OB with explicit maker_relayer / taker_relayer / fee_maker / fee_taker columns, so per-relayer attribution doesn’t depend on whether the peer’s local writer happened to be sell-only or both-leg. Volume here is built sell-side per role (maker_relayer sells sellToken, taker_relayer sells buyToken).
  • Revenue parity for counterparty. Fees are attributed by the relayer that brought each order (maker_relayer earns fee_maker in buyToken, taker_relayer earns fee_taker in sellToken), regardless of which peer actually submitted on-chain.

Parameters

ParameterType
registryAddressstring
providerProvider
sharedOrderbookUrlstring
optsLoadOpts

Returns

Promise<RelayerInfo[]>


fetchRelayerStatsFromSharedOrderbook()

function fetchRelayerStatsFromSharedOrderbook( sharedOrderbookUrl, address, timeoutMs?): Promise<RelayerStatsResponse | null>;

Fetch + build per-relayer stats from the shared orderbook for ONE address. Used by the relayer detail page so its numbers don’t drift from the leaderboard (which already reads from shared-OB). Returns null on fetch failure so the caller can fall back to the peer’s local /api/relayer/stats.

Parameters

ParameterTypeDefault value
sharedOrderbookUrlstringundefined
addressstringundefined
timeoutMsnumber3_000

Returns

Promise<RelayerStatsResponse | null>


loadRelayerSettlements()

function loadRelayerSettlements( settlementAddress, relayer, provider, opts?): Promise<RelayerSettlement[]>;

Read recent PrivateSettledAuth events where the given relayer was the maker-side counterparty. The contract only indexes makerRelayer, so taker-side settlements require either an indexer or a full-event scan with post-hoc filtering — out of scope for this helper. Returns events sorted newest-first.

Parameters

ParameterType
settlementAddressstring
relayerstring
providerProvider
optsLoadSettlementsOpts

Returns

Promise<RelayerSettlement[]>

Last updated on