Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

API Index

Every public export of the two packages, one line each, with a link to the page that covers it. The index is built from the packages’ sources (packages/sdk/src/index.ts, packages/keeper/src/index.ts and every module they re-export), so it lists exactly what an import can reach. The descriptions come from each export’s own documentation comment; the TSDoc in the source, which your editor shows on hover, has the full text.

How to Read This Index

  • Export is the name as you import it. A dotted name lives in a namespace: history.trades is import { history } from "@liberta-labs/bazaar-sdk", then history.trades(ctx, ...). The link goes to the page that explains it.
  • Kind is what the export is. const + type is a value and a type of the same name (OrderType, Status, the keeper’s zod schemas). bz marks a function that is also on the Bazaar object with the connection bound: bz.history.trades(...) is history.trades(bz.ctx, ...).
  • Amounts are bigint in 18 decimals (BAZAAR precision) unless a name says USDC (6 decimals); times, blocks and counts are number. See Units & Constants.

A namespace keeps the area’s names from colliding: orders.OrderInput and previews.OrderInput are two different types, and so are SubgraphError (the low-level client’s) and history.SubgraphError (the history queries’).

@liberta-labs/bazaar-sdk

import { Bazaar, OrderType, parseUnits18, errorMessage } from "@liberta-labs/bazaar-sdk"; // flat exports
import { history, termination } from "@liberta-labs/bazaar-sdk";                          // namespaces

The Bazaar Object

Bazaar.connect(options) returns one object with the connection bound to every context-first function of every area. Its members:

MemberWhat it is
Bazaar.connect(options)Connect to a deployment: reads its wiring from the factory and checks the chain. options is BazaarOptions.
Bazaar.from(ctx)Wrap a context you already have (from connect).
bz.ctxThe BazaarContext: chain, chain id, deployment addresses, price source, subgraph, integrator.
bz.chainIdThe connected chain’s id.
bz.deployment{ factory, lens, terminator, oracle, usdc }.
bz.simulate(call, opts?)Run a prepared call as the user without sending it (simulate); opts.from, opts.estimateGas.
bz.send(wallet, call, opts?)Send through an EIP-1193 wallet (sendCall); returns the transaction hash.
bz.waitForReceipt(hash, opts?)Poll for the receipt (waitForReceipt); throws CallError if it reverted.
bz.livePrices(opts?)Live prices for the listed markets (livePrices).
bz.markets, bz.account, bz.live, bz.orders, bz.trade, bz.insurance, bz.signing, bz.permits, bz.allowance, bz.relay, bz.batching, bz.history, bz.previews, bz.termination, bz.listings, bz.governance, bz.umaEach area’s context-first functions, bound: the rows marked bz below. The pure helpers stay on the namespaces.

The list of bound functions is generated from the modules (npm run gen-bindings, see Development), so a new context-first function appears on bz once the bindings are regenerated.

The Facade and the Connection

ExportKindWhat it is
BazaarclassThe SDK bound to one connection: Bazaar.connect(options), then bz.<area>.<function>(...) with the context already passed.
BazaarOptionsinterfaceWhat Bazaar.connect takes: ConnectOptions, with prices also accepted as Pyth Pro client options or a ProClient, and subgraph as a URL or { url, apiKey }.
requirePairfunctionpair, checksummed, once the context’s factory confirms it is one of its pairs (factory.isPair); an InputError on pair otherwise.
NetworkPresetinterfaceA built-in network: name, chain id, factory (null until launch), start block, subgraph URL, whether official, and the sequencer URL.
NETWORKSconstThe built-in networks: arbitrum-one, arbitrum-sepolia and anvil.
PRICE_ENDPOINTSconstprices.endpoint shortcuts, each a set of Pyth Pro endpoints (or null until the service exists).
ProEndpointsinterfaceWhere Pyth Pro is served: its stream endpoints, its request API, and its symbols registry.
PYTH_PROconstPyth’s own Pyth Pro endpoints.
PYTH_PRO_TOKEN_URLconstWhere a Pyth Pro API key is exchanged for a short-lived token.
connectfunctionRead the deployment’s wiring from its factory and return a context bound to it.
requirePricesfunctionThe context’s price source; throws ConnectError when the context was connected without one.
requireSubgraphfunctionThe context’s subgraph source; throws ConnectError when the context was connected without one.
PriceUpdateSourceinterfaceSigned Pyth Pro price updates, as the pair’s calls carry them: latest, and optionally atTick and useSignerCheck.
verifierSignerCheckfunctionA SignerCheck that asks a deployment’s Pyth verifier whether it trusts a signer, keeping each answer briefly.
VerifierSignerCheckOptionsinterfaceOptions of verifierSignerCheck: ttl, maxAge and clock.
VERIFIER_SIGNER_ABIconstThe verifier’s isValidSigner view.
SubgraphSourceinterfaceA GraphQL endpoint serving Bazaar’s subgraph.
BazaarContextinterfaceA connection: the Chain, the chain id, the deployment’s addresses (factory, lens, terminator, oracle, USDC), and the optional price source, subgraph and integrator.
ConnectOptionsinterfaceWhat connect takes: transport, factory, and the optional prices, subgraph, integrator, chainId and checkSigners.
ConnectErrorclassConnecting failed, or a call needs a price source or subgraph the context was connected without.

Calls, Price Updates and Units

ExportKindWhat it is
simulatefunctionRun the call as from (or call.from) without sending it.
toTransactionRequestfunctionThe call as a viem / wagmi transaction request.
sendCallfunctionSend through an EIP-1193 wallet (eth_sendTransaction).
waitForReceiptfunctionPoll for the receipt; throws CallError if it reverted or did not land in time.
buildAndSendfunctionBuild, then send at once: for calls carrying a price update, build as late as possible so the print is still inside the pair’s 3 s window when the transaction lands.
PreparedCallinterfaceA write ready to simulate and send: action, to, data, value, summary, pullsUsdc and the rest.
SimulationinterfaceWhat simulate returns: ok, the return data, the decoded error (with its user message) and the gas estimate.
InputErrorclassAn argument a builder refused before building anything: field names it.
CallErrorclassA send that reverted or was rejected, with the decoded reason when there is one.
pairFeedsfunctionThe pair’s feeds.
priceUpdateForfunctionThe freshest signed update for the pair’s feeds, and the ETH fee the oracle charges to verify it.
updateFeefunctionThe ETH fee the oracle charges to verify a price update (getUpdateFee); 0 for an empty update.
PairFeedsinterfaceA pair’s price id and its raw Pyth legs (one, or base then quote for a composite) and whether the quote is inverted.
FreshUpdateinterfaceWhat priceUpdateFor returns: the update bytes, the Pyth fee to send as value, and the oldest publish time among the legs.
toUsdcUnitsfunctionBAZAAR precision -> USDC units, floored as the pair floors it.
fromUsdcUnitsfunctionUSDC units -> BAZAAR precision.
toUsdcUnitsCeilfunctionBAZAAR precision rounded up to the next whole USDC unit (for allowances and permits that must cover it).
floorToUsdcfunctionFloor to what the pair actually moves: a multiple of 1e12 (one micro-USDC).
parseDecimalfunctionA decimal string (“12.5”, “1e-3” is refused) -> fixed point with decimals (default 18).
formatDecimalfunctionFixed point -> decimal string, trimming trailing zeros; maxDecimals rounds toward zero.
UnitErrorclassA decimal string or fixed-point value that cannot be converted (bad syntax, too many decimals).
parseUnits18const“12.34” dollars or units -> BAZAAR precision.
formatUnits18constBAZAAR precision -> “12.34”.
bpToFractionconstBasis points -> a fraction as a number (for display only).
toNumber18constA BAZAAR-precision value as a JS number (display only: loses precision past 2^53 / 1e18).

Errors and Messages

Also exported as the format namespace below, with the formatters.

ExportKindWhat it is
errorMessagefunctionThe text to show a user for any error a Bazaar call can throw.
installUserMessagesfunctionRegister USER_MESSAGES so DecodedError.message returns them.
userMessagefunctionThe user-facing message for a custom error by name, with its arguments; the name itself when unknown.
walletErrorMessagefunctionA message for a failure the wallet raised rather than the contract.
USER_MESSAGESconstEvery custom error’s user-facing message, by error name.
REASON_MESSAGESconstUser-facing messages for the plain reason strings Pyth’s verifier reverts with, by the string.

Live Prices

Also exported in the priceFeeds namespace below.

ExportKindWhat it is
proPriceSourcefunctionThe context’s price source over Pyth Pro (Pyth’s own endpoints, a proxy, or a local mock): latest, atTick, prints, and the client.
livePricesfunctionLive prices for every market of a context (listMarkets), or for the markets given.
LivePricesclassLive prices for a set of markets.

The Area Namespaces

One namespace per area of @liberta-labs/bazaar-sdk. Context-first functions take a BazaarContext (from connect, or bz.ctx) as their first argument.

markets

import { markets } from "@liberta-labs/bazaar-sdk". Market lists, snapshots, flags and the book.

ExportKindWhat it is
markets.readerForfunctionThe keeper’s batched Reader, wired to the context’s deployment (no factory read needed).
markets.listMarketsfunction, bzEvery market the context’s factory has deployed, in the factory’s order, with its static facts and a label for display (“BTC/USD”, “AAPL/USD”; a composite is labelled in USD).
markets.getMarketfunction, bzOne market, by its address, its pair id, or its label (case-insensitive; labels come from the feeds’ Pyth symbols, never from the subgraph’s description).
markets.resolvePricesfunctionEach market’s live price and venue state.
markets.pastTradingCutofffunctionWhether now is in limbo: a cutoff is scheduled and the block is within LIMBO_LEAD of it (BazaarPair._pastTradingCutoff).
markets.marketFlagsfunctionThe flags for a market state at now (a block timestamp), following the pair’s own gates.
markets.annualizedFundingfunctionA funding rate per hour (1e18 = 100%, as the lens reports it) as a yearly fraction for display (0.0876 = 8.76% a year).
markets.marketStatusAtfunctionThe snapshot’s status at another time (seconds), for countdowns without a new read.
markets.adlScoreThresholdAtfunctionThe ADL auction’s score threshold at another time, for a live display without a new read.
markets.headForfunctionThe block to read at: the caller’s, or the latest.
markets.marketSnapshotsfunction, bzSeveral markets’ live state at one block.
markets.marketSnapshotfunction, bzOne market’s live state at one block; see marketSnapshots.
markets.getBookDepthfunction, bzThe best levels price levels of one side of the book.
markets.getBookfunction, bzBoth sides of the book, read together; see getBookDepth.
markets.TradingHourstype“24/7” for a continuously traded market; “trading-hours” for one that follows its venue’s calendar (stocks, FX).
markets.MarketInfointerfaceWhat never changes about a market: what a market list and a market header show.
markets.MarketReftypeA market as callers name it: its info, its pair address, its pair id, or its label.
markets.SymbolSourceinterfaceWhere feed symbols come from: a symbols registry’s base URL, or anything that lists its entries (symbols()).
markets.ListMarketsOptionsinterfaceOptions of listMarkets: refresh (read the factory’s pair list again) and metadata (where feed symbols come from).
markets.VENUE_CLOSED_AFTERconstSeconds a trading-hours market’s feed may go without a print, while the price endpoint is otherwise delivering, before its venue counts as closed (PriceService.closed’s default).
markets.HeldPriceinterfaceA price a caller already holds, in BAZAAR precision.
markets.LivePriceQuoteinterfaceA composed live price for one market, as LivePrices.price returns it.
markets.LivePriceViewinterfaceWhat snapshots read live prices and the venue from: a LivePrices, or anything shaped like it.
markets.PriceQuoteinterfaceThe price a snapshot valued an account at, and where it came from.
markets.ResolvedPriceinterfaceWhat resolvePrices returns per market: the price quote (or null) and whether the venue is closed (null when unknown).
markets.ResolveOptionsinterfaceOptions of resolvePrices: live prices, a held price, whether to fetch from Pyth Pro, and whether a price is needed.
markets.MarketFlagReasonsinterfaceWhy something a trader may try is refused right now; null where it is not.
markets.MarketFlagsinterfaceWhat the pair refuses right now, as one set of flags a UI can gate its buttons on.
markets.StoredPriceinterfaceThe pair’s stored oracle price (lastPairPrice): what its next call falls back to without a fresh one.
markets.FundingViewinterfaceA snapshot’s funding: the current and accruing rates per hour (1e18 = 100%), the index and projected index, the last accrual and the cap.
markets.MarginViewinterfaceA snapshot’s margin rates in basis points: initial, maintenance, and the 24 h lagged maintenance rate.
markets.OpenInterestViewinterfaceA snapshot’s open interest: long and short sizes and notionals, and the liquidated inventory the vault holds.
markets.InsuranceViewinterfaceA snapshot’s insurance fund: its balance, free capital, the seizure earmarked against inventory, its target ratio and its ledgers.
markets.AdlViewinterfaceA snapshot’s ADL state: whether a window is pending, its epoch, when it opened, and the auction’s score threshold.
markets.TerminationViewinterfaceA snapshot’s termination state: the scheduled cutoff, when trading halts ahead of it, and when the settlement price was fixed.
markets.BookSummaryinterfaceA snapshot’s book heads: the best bid and ask order ids and the number of orders resting on each side.
markets.MarketSnapshotinterfaceA market’s live state at one block, with the one status and the flags a UI shows.
markets.SnapshotOptionsinterfaceOptions of marketSnapshot(s): the block to read at, live prices to judge the venue with, and whether to fetch prices.
markets.MAX_FUNDING_RATE_CONTINUOUSconstBazaarPairLens.fundingRate’s cap per hour, by calendar (FundingLib.MAX_FUNDING_RATE_*).
markets.MAX_FUNDING_RATE_SESSIONconstThe funding-rate cap per hour for a market with trading hours (1e18 = 100%).
markets.DepthLevelinterfaceOne price level of the book: every live resting order at that limit price.
markets.BookSidetype"bids" or "asks".
markets.BookDepthinterfaceWhat getBookDepth returns: the market, side and block, the levels best first, and whether every level is included.
markets.BookDepthOptionsinterfaceOptions of getBookDepth: the lens page size and the most orders to walk.

account

Accounts and portfolios.

ExportKindWhat it is
account.positionHealthfunctionThe position valued at spot with the state’s projected funding index and effective maintenance rate.
account.accountHealthfunctionThe snapshot’s position revalued at a new spot price (a live print), with no read: for a display that follows the price between snapshots.
account.accountSnapshotfunction, bzThe account user on one market.
account.portfoliofunction, bzEvery market where user has collateral, a position, live orders or claimable fees, as accountSnapshots, with totals.
account.accountSnapshotsfunctionSeveral accounts’ snapshots on chosen markets in one pass (used by watchAccount to refresh the markets an event touched).
account.AccountPositioninterfaceThe account’s position bucket on the pair (BazaarPairLens.getPositionBucket), BAZAAR precision.
account.PositionHealthinterfaceThe position valued at a price, by the pair’s own formula (BucketLib.calculateState) at the projected funding index (what a price stored now would accrue to) and the effective maintenance rate.
account.LensBucketStateinterfaceBazaarPairLens.checkBucketSolvency at the snapshot’s spot: the contract’s own view, at the stored funding index.
account.AccountOrderinterfaceOne of the account’s live orders, decoded from pair.orders(id).
account.OrderExposureinterfaceBazaarPairLens.outstandingOrderExposure: the live limit orders’ remaining notional (at their limits) and size per side.
account.TerminalPayoutinterfaceBazaarPairLens.getTerminalEntitlement: what a withdrawal pays on a market that is winding down.
account.WalletStateinterfaceThe wallet’s USDC balance and the allowance the pair may pull, in USDC units (6 decimals).
account.AccountSnapshotinterfaceOne account on one market at one block: position, health, orders, collateral, max withdrawable, fees and wallet state.
account.AccountOptionsinterfaceOptions shared by the account reads: the block to read at, live prices to value positions with, and whether to fetch prices.
account.AccountSnapshotOptionsinterfaceOptions of accountSnapshot: AccountOptions plus a held price and a market snapshot at the same block.
account.PortfolioTotalsinterfaceA portfolio’s totals across markets: collateral, equity, unrealized and funding PnL, claimable fees and max withdrawable.
account.PortfoliointerfaceWhat portfolio returns: one AccountSnapshot per market the account is active on, and the totals.

live

Watching markets and accounts through their events.

ExportKindWhat it is
live.decodeLiveLogfunctionA pair’s or the terminator’s log as a typed LiveEvent; null for a log that is neither (or a terminator event that names no pair).
live.watchMarketfunction, bzWatch one market: every pair event it emits (and terminator events about it) as typed LiveEvents, and a fresh MarketSnapshot at the head after events (at most one per minSnapshotMs).
live.watchAccountfunction, bzWatch one account on a set of markets.
live.OrderUpdatePayloadinterfaceOrderUpdated’s payload: the order’s stored state at the event.
live.PairEventArgsinterfaceEach pair event’s arguments, as the pair emits them (BAZAAR precision; timestamps, blocks and enums as numbers).
live.PairEventNametypeThe name of a pair event PairEventArgs describes.
live.LogPositioninterfaceWhere a log sits.
live.PairEventtypeA pair event; narrow on name for its typed args.
live.TerminatorEventinterfaceA terminator event about one market (proposals, schedules, settlement prices, insurer votes).
live.LiveEventtypeA PairEvent or a TerminatorEvent.
live.FollowOptionsinterfaceOptions of LogFollower and the watchers: the poll interval, the first block, and the rest.
live.FollowNoticetypeWhat a follower reports besides logs.
live.LogFollowerclassFollows the logs of a set of contracts from a block cursor.
live.WatchOptionsinterfaceOptions of watchMarket and watchAccount: FollowOptions plus live prices and price fetching for the snapshots.
live.SnapshotCausetypeWhy a watcher sent a snapshot: initial, events, timer or manual.
live.UndecodableLoginterfaceA log from a watched contract that could not be decoded (a malformed or unexpected event): it is reported here and skipped, and the rest of its batch is still delivered.
live.MarketUpdatetypeWhat watchMarket delivers: an event, a snapshot (with whether the book changed), an undecodable log or a follower notice.
live.AccountUpdatetypeWhat watchAccount delivers: an event, an account snapshot, an undecodable log or a follower notice.
live.WatchHandleinterfaceWhat a watcher returns: ready, refresh() and stop().

priceFeeds

Streamed prices and the price source over Pyth Pro (client/prices.ts).

ExportKindWhat it is
priceFeeds.updateFromPrintsfunctionThe signed updates a call attaches for these prints: each distinct update they came in, once.
priceFeeds.proPriceSourcefunctionThe context’s price source over Pyth Pro (Pyth’s own endpoints, a proxy, or a local mock): latest, atTick, prints, and the client.
priceFeeds.isProPriceSourcefunctionWhether a context’s price source is a proPriceSource (it then exposes its client).
priceFeeds.livePricesfunctionLive prices for every market of a context (listMarkets), or for the markets given.
priceFeeds.BROWSER_FUTURE_SKEWconstHow far ahead of this device’s clock a live print may be dated before it is ignored (seconds).
priceFeeds.ProPriceSourceinterfaceA PriceUpdateSource over Pyth Pro, with the client and parsed prints exposed.
priceFeeds.MarketPriceinterfaceOne market’s live price, composed as BazaarOracle composes it (BAZAAR precision).
priceFeeds.PriceListenertypeCalled with the markets whose price or flags changed (one map per batch; do not keep it).
priceFeeds.LivePricesOptionsinterfaceOptions of livePrices: the PriceService options plus pro (options for a client of its own) or client when no context source is given.
priceFeeds.LivePricesclassLive prices for a set of markets.

orders

Order specs, checks and packing, with no chain read except the read* functions.

ExportKindWhat it is
orders.joinsActiveSetfunctionWhether the order joins the account’s active set and its 32-order cap (OrderManagementLib._joinsActiveSet).
orders.canRestfunctionWhether the order can rest in the book and so wants an insertion hint: a Limit GTC, or a StopLimit once armed.
orders.packTriggerPricefunction(bounty << 128) | price: the OrderSpec.triggerPrice word of a trigger order.
orders.unpackTriggerPricefunctionSplit a triggerPrice word into its price (low 128 bits) and bounty (high 128 bits).
orders.specBountyfunctionThe bounty a spec carries: what createOrder pulls from the wallet on top of any relayer fee.
orders.blocksInfunctionL2 blocks in seconds (about four a second), for an expiry currentBlock + blocksIn(s).
orders.buildOrderSpecfunctionCheck an order the way OrderManagementLib.createOrder will, and return the spec to send or sign.
orders.checkOrderCapsfunctionThe per-user caps a UI must respect, against an account’s live orders: 32 active Limit (GTC) + StopLimit orders per pair, and one TakeProfit and one StopLoss per position.
orders.orderInputFromSpecfunctionThe order a spec describes, for re-validation (a relayer checking a signed spec) or display.
orders.validateOrderSpecfunctionCheck a spec built elsewhere (or received for relaying) against the same rules, including the one the builder enforces by construction: a non-trigger type must leave the bounty bits clear.
orders.describeOrderfunctionOne line for a confirmation screen: “Buy 1.5 at 2000 (limit, GTC, post-only)”.
orders.amendIdWordfunctionAn amendment’s id word, exactly as BazaarPairLens.amendIdWord / bestEffortAmendIdWord pack it: the order id in bits 0-63, hints in bits 64-127 and 128-191, the best-effort flag in bit 192.
orders.unpackAmendIdWordfunctionThe fields of an id word.
orders.encodeAmendsfunctionThe flat amends array amendOrders takes and AmendOrders signs: per amendment its id word, its new price, its new total size. 1 to MAX_AMENDS_PER_CALL amendments.
orders.decodeAmendsfunctionThe amendments a flat amends array holds (for a relayer showing or checking a signed batch).
orders.readOrderStatefunction, bzThe account facts the creation checks need, in one batched read.
orders.readTriggerBountyfunction, bzWhat a trigger order’s escrow still holds for whoever fires it (BAZAAR precision): lens.triggerBounty.
orders.readOrderLifetimeConstantsfunction, bzThe lifetime constants as the lens reports them (pure there; useful to confirm the SDK’s copy).
orders.TimeInForceconst + typeBazaarTypes.TimeInForce: what an arriving order does with the size the book could not fill.
orders.TIF_NAMESconstTime-in-force names by number: 0 GTC, 1 IOC, 2 FOK.
orders.MAX_SLIPPAGE_BPconstSlippage cap for Market, TakeProfit and StopLoss orders: 10%.
orders.MAX_PLACEMENT_DEVIATION_BPconstA Limit price must sit within ±50% of the oracle price at creation or amendment.
orders.MIN_ORDER_LIFETIME_BLOCKSconstMinimum life of an order that can rest, in Arbitrum L2 blocks (~1 minute at 4 blocks a second).
orders.MAX_ORDER_LIFETIME_BLOCKSconstMaximum life, in L2 blocks (~1 year); a later expiry is clamped to it by the pair.
orders.NEVER_EXPIRE_BLOCKconstThe expiry the pair stamps on TakeProfit and StopLoss orders: they never expire.
orders.MAX_ACTIVE_LIMIT_ORDERS_PER_USERconstActive Limit + StopLimit orders one account may hold on one pair.
orders.MAX_AMENDS_PER_CALLconstAmendments per amendOrders call (the per-user cap, so one batch can requote every order).
orders.MAX_CANCELS_PER_CALLconstOrder ids per cancelOrders call (BazaarPair.MAX_CANCELS_PER_CALL).
orders.AMEND_BEST_EFFORT_BITconstBit 192 of an amendment’s id word: skip the amendment instead of reverting the batch.
orders.CLOSE_POSITIONconstA TakeProfit or StopLoss of this size closes the whole position, whatever it is when it fires.
orders.L2_BLOCKS_PER_SECONDconstArbitrum produces about four L2 blocks a second; expiries are counted in them.
orders.EXPIRY_LANDING_MARGIN_BLOCKSconstBlocks of slack the SDK adds on top of the minimum lifetime when it checks an expiry: the pair measures the lifetime from the block the transaction lands in, a few seconds after it is built.
orders.OrderSpecinterfaceBazaarTypes.OrderSpec, field for field: what createOrder takes and the CreateOrder signature covers.
orders.MatchHintsinterfaceBazaarTypes.MatchHints: execution aids for the arrival walk and book insertion, outside every signature.
orders.NO_HINTSconstEmpty MatchHints: no predecessors, the default walk budget.
orders.OrderInputinterfaceAn order as a trader describes it.
orders.OrderEnvironmentinterfaceWhat the pair knows that an order is judged against.
orders.AccountOrderStateinterfaceThe account facts the creation checks need: its position and its order slots.
orders.isTriggerTypeconstWhether an order type is a trigger type (StopLimit, TakeProfit, StopLoss).
orders.AmendInputinterfaceOne amendment of a resting Limit (GTC) order: its new price and new TOTAL size (filled part included).
orders.bestEffortAmendIdWordconstBazaarPairLens.bestEffortAmendIdWord.

trade

Every trading write, and the price and hint helpers they use.

ExportKindWhat it is
trade.parsePriceUpdatefunctionThe live prices a priceUpdate: bytes[] carries, read from each Pyth Pro update’s signed payload.
trade.UpdatePriceinterfaceOne feed’s live price as a signed update carries it.
trade.pairPriceFromUpdatefunction, bzThe pair price an update proves, composed from the pair’s legs exactly as BazaarOracle composes it (formulas pairPrice).
trade.livePairPricefunction, bzThe live pair price from the context’s price source, with the update it came from.
trade.storedPairPricefunction, bzThe price the pair last stored (lastPairPrice): what it falls back to on a closed market.
trade.findPredecessorfunction, bzThe order a new entry at limitPrice on its side should rest directly behind (0 = the head).
trade.matchHintsForfunction, bzMatchHints for an order: the predecessor on its own side at its limit price when it can rest (a Limit GTC, or a StopLimit that arms on arrival), none otherwise.
trade.depositCollateralfunction, bzDeposit collateral: the pair floors amount (BAZAAR precision) to whole micro-USDC, adds it to the trader’s position bucket and pulls it from the wallet.
trade.terminalWithdrawalfunctionOn a terminated pair, what a withdrawal of amount (collateral, BAZAAR precision) pays out.
trade.withdrawCollateralfunction, bzWithdraw collateral (BAZAAR precision; the wallet receives it floored to micro-USDC).
trade.optionalUpdatefunction, bzA price update for a call that reads a price only sometimes: none when withPrice is false; attached when a price source is connected (the pair refunds the fee of an update it does not read).
trade.prepareOrderfunction, bzCheck an order against the account’s position and order slots, the current L2 block and the oracle price, and build its spec with the context’s integrator (orders.ts buildOrderSpec has the rules).
trade.createOrderfunction, bzCreate an order, matched against the book in the same transaction.
trade.prepareAmendsfunction, bzCheck amendments the way OrderManagementLib._amendOne will and fill in hints for the ones that move.
trade.amendOrdersfunction, bzAmend resting Limit (GTC) orders in place: each gets a new price and total size and keeps its id, expiry and integrator.
trade.checkCancelIdsfunction1 to 200 distinct order ids, as cancelOrders takes them.
trade.cancelOrdersfunction, bzCancel the trader’s orders (up to 200): each is unlinked from the book in the same write and its remaining keeper bounty returns to the trader’s claimable balance (claimFees).
trade.claimFeesfunction, bzPay the caller everything the pair owes it: refunded trigger bounties, keeper rewards, relayer and integrator fees.
trade.executeTriggeredOrdersfunction, bzFire the trader’s own trigger orders (StopLimit, TakeProfit, StopLoss) whose trigger the live price has reached: how a zero-bounty order is executed, by its owner.
trade.PriceUpdateErrorclassA price update that is not a Pyth Pro update, or does not cover the pair’s feeds.
trade.terminalPayoutNoteconstWhat a terminal payout of payout reads as on a confirmation screen.
trade.PreparedOrderinterfaceAn order checked against the chain: the spec to send or sign, and what it was checked against.
trade.CreateOrderOptionsinterfaceOptions of createOrder: hints to use instead of the ones the SDK finds, the walk budget maxSteps, and permitData.
trade.PreparedAmendsinterfaceAmendments checked against the orders, the book and the price, with insertion hints filled in.

insurance

Insurance deposits, the exit, quotes, budgets and locks.

ExportKindWhat it is
insurance.claimOpensAtfunctionBazaarPair.InsuranceVaultLib.claimOpensAt.
insurance.depositToInsurancefunction, bzDeposit USDC into the pair’s insurance fund for shares priced at the fund’s value at the mark.
insurance.requestInsuranceWithdrawalfunction, bzRequest to withdraw shareAmount insurance shares: starts the 13-day cooldown, after which the execution window opens (2 days, or 4 on a pair with trading hours).
insurance.executeInsuranceWithdrawalfunction, bzThe next step of a requested withdrawal.
insurance.getInsuranceSharePricefunction, bzWhat one share redeems for at the pair’s stored mark (BAZAAR precision; 1.0 while no shares exist).
insurance.getInsuranceDepositValuefunction, bzWhat user’s shares redeem for at the pair’s stored mark (BAZAAR precision).
insurance.insuranceSharesfunction, bzuser’s insurance shares (0 for a balance a fund recap wiped).
insurance.quoteInsuranceDepositfunction, bzShares a deposit of amount (BAZAAR precision, floored to micro-USDC as the pair floors it) would mint at the live price (or price): lens.quoteInsuranceDeposit, the pair’s own arithmetic.
insurance.quoteInsuranceWithdrawalfunction, bzUSDC (BAZAAR precision) a redemption of shareAmount would pay at the live price (or price): lens.quoteInsuranceWithdrawal.
insurance.getInsuranceWithdrawalLockfunction, bzlens.getInsuranceWithdrawalLock: where an LP’s two execute calls stand.
insurance.getInsuranceWithdrawalBudgetfunction, bzlens.getInsuranceWithdrawalBudget at the live price (or price): the number a paying call is checked against, as of now.
insurance.getInsuranceWithdrawalConstantsfunction, bzlens.getInsuranceWithdrawalConstants: durations in seconds, budget terms in bp.
insurance.insuranceExitPlanfunction, bzRead where user’s insurance exit on pair stands and when the next call can land.
insurance.MIN_INSURANCE_DEPOSITconstThe smallest insurance deposit: 5 USDC (BAZAAR precision).
insurance.MAX_INSURANCE_DEPOSITconstThe largest insurance deposit the pair accepts: 2^128 - 1 (BAZAAR precision).
insurance.INSURANCE_WITHDRAWAL_COOLDOWNconstSeconds between a withdrawal request and its execution window: 13 days.
insurance.INSURANCE_WITHDRAWAL_WINDOW_CONTINUOUSconstSeconds the execution window stays open on a 24/7 market: 2 days.
insurance.INSURANCE_WITHDRAWAL_WINDOW_SESSIONconstSeconds the execution window stays open on a market with trading hours: 4 days.
insurance.INSURANCE_WITHDRAWAL_CLAIM_DELAYconstThe paying call opens this long after the lock, and after the last stored 2% price jump.
insurance.INSURANCE_WITHDRAWAL_REOPEN_CLAIM_DELAYconstThe paying call also opens this long after the last stored price that ended a gap of an hour or more.
insurance.REOPEN_GAP_MIN_STALENESSconstRiskParamsLib.REOPEN_GAP_MIN_STALENESS: a store after this long without one ends a gap.
insurance.withdrawalWindowOfconstThe execution window for a market, by whether it trades continuously.
insurance.InsuranceQuoteinterfaceA deposit or redemption quote: the shares or USDC, the mark it was priced at, and the update’s publish time.
insurance.InsuranceWithdrawalLockinterfaceWhat getInsuranceWithdrawalLock returns: whether the request is locked, the locked amount, the lock time, when the claim opens and when the window ends.
insurance.InsuranceWithdrawalBudgetinterfaceWhat getInsuranceWithdrawalBudget returns: what the shared 6-hour budget still admits, its cap, and when it refills.
insurance.InsuranceWithdrawalConstantsinterfaceWhat getInsuranceWithdrawalConstants returns: the cooldown, the windows and the rate-limit terms.
insurance.InsuranceExitSteptypeWhere an LP’s exit stands: none, request, cooldown, lock, waitClaim, claim, redeem, expired or blocked.
insurance.InsuranceExitPlaninterfaceWhat insuranceExitPlan returns: the step, a message for the LP, the next action and when it can land.

signing

EIP-712 signing for gasless calls, deadlines and the clock-skew check.

ExportKindWhat it is
signing.pairDomainfunctionThe pair’s EIP-712 domain.
signing.domainSeparatorfunctionWhat pair.DOMAIN_SEPARATOR() should equal.
signing.typeHashfunctionkeccak256 of the primary type’s string: what lens.getTypehashes reports for it.
signing.typedDataForfunctionThe typed data a user signs for fields on pair.
signing.relayedDigestfunctionThe EIP-712 digest the pair recovers the signer from.
signing.typedDataJsonfunctionThe typed data as the JSON string eth_signTypedData_v4 takes (integers as decimal strings).
signing.floorRelayerFeefunctionCheck a relayer fee and floor it to USDC precision, as _resolveUser charges it: the signed fee is then exactly the USDC the user pays.
signing.readMetaTxNoncefunction, bzThe signer’s next nonce on the pair (pair.metaTxNonces(user)).
signing.eip712Limitsfunction, bzThe fee cap and deadline window the deployment enforces, from lens.getEip712Constants() (read once per context).
signing.chainTimefunction, bzThe latest block’s timestamp: the clock deadlines are judged against.
signing.checkClockSkewfunctionCheck the chain time an RPC reported against this device’s clock and return the lower of the two: the time every deadline the SDK signs is counted from.
signing.deadlineBasefunctionThe time a deadline is counted from: min(latest block’s timestamp, this device’s clock), checked by checkClockSkew.
signing.chainDeadlinefunction, bzA deadline windowSeconds (default: the whole window) past the lower of the latest block’s timestamp and this device’s clock, never more than the deployment’s maxDeadlineWindow (10 s).
signing.normalizeSignaturefunctionA wallet’s signature in the 65-byte r ‖ s ‖ v form OpenZeppelin’s ECDSA accepts: v as 27/28 (some wallets return 0/1), an EIP-2098 64-byte signature expanded, and a high-s signature refused.
signing.signTypedDataV4functionAsk an EIP-1193 wallet to sign typed data with eth_signTypedData_v4, so it shows the user every field it signs.
signing.takesPriceUpdatefunctionThe actions whose call takes priceUpdate: a relayer attaches a fresh one at submission.
signing.encodePairWritefunctionCalldata for one of the eight actions, direct (DIRECT_META) or relayed.
signing.verifyTypehashesfunction, bzConfirm that what the SDK signs is what the deployment verifies.
signing.BAZAAR_DOMAIN_NAMEconstThe pair’s EIP-712 domain name: "BazaarPair".
signing.BAZAAR_DOMAIN_VERSIONconstThe pair’s EIP-712 domain version: "1".
signing.MAX_RELAYER_FEEconstMetaTxLib.MAX_RELAYER_FEE: $1 per action, BAZAAR precision.
signing.MAX_DEADLINE_WINDOWconstMetaTxLib.MAX_DEADLINE_WINDOW: a deadline at most this many seconds past the block’s timestamp.
signing.EIP712_DOMAIN_TYPE_STRINGconstThe EIP-712 domain type string the pair uses (name, version, chainId, verifyingContract).
signing.TYPE_STRINGSconstThe primary types, verbatim from MetaTxLib (whose hashes lens.getTypehashes returns).
signing.PrimaryTypetypeThe name of one of the primary types in TYPE_STRINGS.
signing.EIP712_DOMAIN_FIELDSconstThe EIP-712 domain’s field list, as viem and eth_signTypedData_v4 take it.
signing.BAZAAR_TYPESconstThe same types as viem / eth_signTypedData_v4 field lists; they encode to TYPE_STRINGS.
signing.RELAYED_ACTIONSconstThe pair functions that take a signature.
signing.RelayedActiontypeOne of the pair functions in RELAYED_ACTIONS.
signing.PRIMARY_TYPEconstThe primary type each relayed action signs (depositCollateral signs DepositCollateral, …).
signing.SignedFieldstypeWhat each action signs besides (nonce, deadline, relayerFee): its own arguments.
signing.MetaFieldsinterfaceThe meta-transaction fields every signature covers: nonce, deadline and relayerFee.
signing.MetaArgsinterfaceThe (nonce, deadline, relayerFee, signature, permitData) tail of a pair call; all zero/empty for a direct call.
signing.DIRECT_METAconstThe all-zero meta tail of a direct (unsigned) pair call.
signing.TypedDataDomaininterfaceAn EIP-712 domain: name, version, chain id and verifying contract.
signing.PairTypedDatainterfaceTyped data as eth_signTypedData_v4 and viem take it.
signing.MAX_CLOCK_SKEWconstHow far, in seconds, the chain time the RPC reports may sit from this device’s clock before the SDK refuses to count a deadline from it.
signing.DEV_CHAIN_IDSconstLocal development chains (Anvil and Hardhat 31337, Ganache and geth –dev 1337), whose clocks tests move at will: their deadlines are counted from chain time unchecked.
signing.SigningErrorclassA signing step the wallet refused or could not do in the form Bazaar accepts.
signing.ClockSkewErrorclassThe RPC’s chain time and this device’s clock disagree too much to stamp a deadline (checkClockSkew, chainDeadline).
signing.TypehashReportinterfaceWhat verifyTypehashes returns: ok, one line per mismatch, and each type hash as the SDK and the lens compute it.

permits

USDC (ERC-2612) permits.

ExportKindWhat it is
permits.usdcPermitDomainfunction, bzUSDC’s EIP-712 domain: its name(), its version() (“2” on native Arbitrum USDC; “1” only when the token has no version()), the chain id, and its address.
permits.permitNoncefunction, bzThe owner’s current permit nonce on USDC.
permits.permitTypedDatafunctionThe typed data of a USDC permit.
permits.encodePermitDatafunctionabi.encode(uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s), as the pair decodes it.
permits.decodePermitDatafunctionDecode a permitData blob into its value, deadline, v, r and s.
permits.permitValueForfunctionThe permit value (USDC units, rounded up) that covers a pull of pullBazaar (BAZAAR precision).
permits.signPermitfunction, bzAsk the owner’s wallet (eth_signTypedData_v4) to sign a USDC permit for spender, which must be a pair of this deployment; valid 30 minutes by default.
permits.checkPermitfunction, bzCheck a permitData a relayer received: it decodes, it is signed by owner for spender at the owner’s current nonce, it has not expired, and it covers needUsdc.
permits.DEFAULT_PERMIT_WINDOWconstHow long a permit the SDK signs stays valid by default (seconds past the lower of chain time and the device’s clock).
permits.PERMIT_TYPESconstThe EIP-712 types of a USDC (ERC-2612) permit.
permits.PermitMessageinterfaceA permit’s message: owner, spender (the pair), value in USDC units, nonce and deadline.
permits.SignedPermitinterfaceA signed permit: the message, the signature and its parts, and the permitData a pair call takes.

allowance

USDC balance, allowance and approvals.

ExportKindWhat it is
allowance.erc20DatafunctionCalldata for one of the ERC-20 functions above.
allowance.usdcBalancefunction, bzThe owner’s USDC balance, in USDC units.
allowance.usdcAllowancefunction, bzWhat spender (a pair) may pull from owner, in USDC units.
allowance.approveUsdcfunction, bzApprove spender (a pair) to pull amountUsdc (USDC units) from owner’s wallet.
allowance.formatUsdcUnitsfunctionUSDC units -> “12.5”.
allowance.usdcFundingfunction, bzWhether owner can fund a pull of pullBazaar (BAZAAR precision, e.g. PreparedCall.pullsUsdc) to spender: balance and allowance in one read.
allowance.ERC20_ABIconstThe ERC-20 / ERC-2612 functions the SDK calls on USDC, hand-written (USDC is not a Bazaar ABI).
allowance.UsdcFundinginterfaceWhat usdcFunding returns: the USDC a call needs, the balance and allowance, and what to approve.

relay

Gasless requests: signing, checking, serializing and encoding them.

ExportKindWhat it is
relay.checkSignedFieldsfunctionThe bounds of each action that need no chain read, as the pair enforces them for a relayed call.
relay.relayedPullfunction, bzWhat a relayed call takes from the signer’s wallet, BAZAAR precision: a deposit plus the fee; the fee plus a trigger order’s bounty for createOrder.
relay.signRelayedfunction, bzHave the user sign a gasless request.
relay.verifyRelayedfunction, bzCheck a request before relaying it.
relay.encodeRelayedfunction, bzThe call a relayer sends for a request, from its own account (relayer).
relay.describeRelayedfunctionOne line describing what a request does.
relay.serializeRelayedfunctionThe request as JSON for the POST to a relayer: integers as decimal strings.
relay.parseRelayedfunctionA request from JSON (or an already-parsed body), every field checked for type and shape.
relay.RelayedRequesttypeA signed gasless request: every signed field, the signer, the signature and the permit.
relay.RelayedInputtypeWhat signRelayed takes: the signed fields themselves, or an order / amendments to check and build first.
relay.SignRelayedOptionsinterfaceOptions of signRelayed: the wallet, signer and pair, the relayer fee, the deadline window, and an optional nonce and permit.
relay.RelayCheckinterfaceWhat verifyRelayed returns: ok, the recovered signer, and every problem that would make the call revert.

batching

Several prepared calls in one transaction.

ExportKindWhat it is
batching.toBatchCallsfunctionThe calls in the generic shape, in order.
batching.batchValuefunctionETH the batch needs: the sum of the calls’ values (Pyth fees).
batching.shareOnePriceUpdatefunctionCarry the Pyth update once per pair: the first call that always stores a price (createOrder, amendOrders, executeTriggeredOrders, refreshPrice) keeps its update and fee.
batching.walletSendCallsRequestfunction, bzThe wallet_sendCalls request for these calls from from (the smart account).
batching.sendCallsfunctionSend the calls as one batch through an EIP-5792 wallet.
batching.getCallsStatusfunctionwallet_getCallsStatus for a batch id, as the wallet reports it.
batching.encodeTradingAccountExecutefunctionexecute(Call[] calls) calldata, each call as (target, value, data).
batching.tradingAccountExecutefunctionOne transaction through a BazaarTradingAccount: execute runs the calls in order as the account, with value the sum of their values.
batching.decodeTradingAccountResultsfunctionThe per-call return data execute returns.
batching.readTradingAccountOwnerfunction, bzThe account’s owner (who alone may call execute).
batching.BatchCallinterfaceThe generic call shape smart wallets take (ERC-4337 / Safe / EIP-5792).
batching.SendCallsOptionsinterfaceOptions of sendCalls and walletSendCallsRequest: whether the batch must be atomic, and wallet capabilities.
batching.TRADING_ACCOUNT_ABIconstThe example account’s interface, hand-written from examples/BazaarTradingAccount.sol.

history

Bazaar’s subgraph: every history query and its types.

ExportKindWhat it is
history.httpSubgraphfunctionA SubgraphSource over HTTP.
history.cancelReasonNamefunctionBazaarTypes.CancelReason’s code (as an OrderUpdated payload carries it) -> its name.
history.tradesfunction, bzThe trade tape: fills, newest first.
history.candlesfunction, bzOHLCV candles of one pair at one interval (seconds: 60, 300, 900, 3600, 14400 or 86400), oldest first; from/to bound the period start.
history.fillCandleGapsfunctionFill the periods between from and to (exclusive) that had no fills with flat candles at the previous close (zero volume), as a chart expects.
history.pairDayDatafunction, bzA pair’s daily figures (UTC days), oldest first.
history.protocolDayDatafunction, bzProtocol-wide daily figures, oldest first.
history.bookLevelsfunction, bzAggregated resting size per price on one side of a pair’s book, best price first (bids high to low, asks low to high).
history.ordersfunction, bzOrders, newest first by creation time (from/to bound the creation time).
history.orderfunction, bzOne order by pair and order id, or null when the subgraph has not seen it.
history.orderEventsfunction, bzOrder lifecycle events (created, triggered, canceled with its reason, amended, amend skipped), newest first.
history.positionsfunction, bzPositions (one per account and pair), by id.
history.positionChangesfunction, bzEach trade’s effect on a position, newest first.
history.positionSnapshotsfunction, bzThe full stored position after every change (PositionBucketUpdated), newest first.
history.collateralTransfersfunction, bzCollateral deposits and withdrawals, newest first.
history.feeBalancesfunction, bzClaimable balances per pair and recipient: an integrator’s or relayer’s revenue, a keeper’s rewards, refunded bounties.
history.feeAccrualsfunction, bzCredits to claimable balances (FeeAccrued), newest first.
history.feeClaimsfunction, bzClaims of claimable balances (FeesClaimed), newest first.
history.integratorStatsfunction, bzWhat an integrator address has routed, or null when it has carried no order.
history.accountStatsfunction, bzAn account’s lifetime totals, or null when the subgraph has not seen it.
history.accountDayDatafunction, bzAn account’s daily totals (UTC days), oldest first.
history.metaTransactionsfunction, bzRelayed (gasless) actions, newest first.
history.permitFailuresfunction, bzPermits the pair could not execute (the call went on with the existing allowance), newest first.
history.liquidationsfunction, bzLiquidations, newest first: account is the liquidated trader.
history.adlWindowsfunction, bzADL windows, newest first by opening time.
history.adlBatchesfunction, bzADL batches (executeAdl calls), newest first; window is an AdlWindow id.
history.adlFillsfunction, bzWinners ADL closed, newest first.
history.insuranceProvidersfunction, bzInsurance LPs per pair, by id; activeOnly keeps those holding shares.
history.insuranceEventsfunction, bzInsurance deposits, withdrawal requests, locks, payouts and levies, newest first.
history.pairTerminationsfunction, bzFinalized terminations with their payout figures, newest first.
history.terminalRatioUpdatesfunction, bzPayout ratios re-derived after finalize, newest first.
history.terminationProposalsfunction, bzUMA termination claims, newest first by submission.
history.insurerProposalsfunction, bzInsurer termination votes, newest first by creation.
history.insurerVotesfunction, bzYes-votes cast on insurer proposals, newest first.
history.insurerLeviesfunction, bzLevies charged on yes-voters’ redemptions after an insurer-vote termination, newest first.
history.listingProposalsfunction, bzListing (pair deployment) proposals, newest first.
history.identifierUpgradeProposalsfunction, bzUMA identifier-upgrade proposals, newest first.
history.subgraphLagfunction, bzHow far the subgraph’s history trails the chain: its _meta.block against the chain head, so a UI can say that trades and positions from the last moments may not be listed yet.
history.SubgraphErrorclassThe subgraph refused or failed a query.
history.HttpSubgraphOptionsinterfaceOptions of httpSubgraph: the per-request timeout, extra headers and the fetch to use.
history.ORDER_TYPESconstOrder type names as the subgraph stores them: Market, Limit, StopLimit, TakeProfit, StopLoss.
history.OrderTypeNametypeOne of ORDER_TYPES.
history.TIME_IN_FORCEconstTime-in-force names: GTC, IOC, FOK.
history.TimeInForceNametypeOne of TIME_IN_FORCE.
history.ORDER_STATUSESconstOrder statuses: Waiting, Pending, Resting, Fired, Filled, Canceled.
history.OrderStatustypeOne of ORDER_STATUSES.
history.OPEN_ORDER_STATUSESconstStatuses of an order that can still trade.
history.CANCEL_REASONSconstCancel reasons, in BazaarTypes.CancelReason order (None, Owner, Expired, … Deleveraged).
history.CancelReasontypeOne of CANCEL_REASONS.
history.AMEND_SKIP_REASONSconstWhy a best-effort amendment was skipped: Inactive, Expired, SizeFilled, BelowMinimum, WouldCross.
history.AmendSkipReasontypeOne of AMEND_SKIP_REASONS.
history.ORDER_EVENT_ACTIONSconstOrder event kinds: Created, Triggered, Canceled, Amended, AmendSkipped.
history.OrderEventActiontypeOne of ORDER_EVENT_ACTIONS.
history.PAIR_STATUSESconstPair statuses as the subgraph records them: Active, Scheduled, SettlementFixed, Terminated.
history.PairStatustypeOne of PAIR_STATUSES.
history.SETTLEMENT_SOURCESconstHow a settlement price was fixed: Cutoff, Stale, Insolvency.
history.SettlementSourcetypeOne of SETTLEMENT_SOURCES.
history.INSURANCE_EVENT_KINDSconstInsurance event kinds: Deposit, WithdrawalRequested, WithdrawalLocked, WithdrawalExecuted, LevyCharged, LevyReceived.
history.InsuranceEventKindtypeOne of INSURANCE_EVENT_KINDS.
history.LISTING_STATUSESconstListing statuses: Pending, Disputed, Deployed, Rejected, Expired, Voided.
history.ListingStatustypeOne of LISTING_STATUSES.
history.IDENTIFIER_UPGRADE_STATUSESconstIdentifier-upgrade statuses: Pending, Disputed, Queued, Upgraded, Canceled, Expired, Rejected.
history.IdentifierUpgradeStatustypeOne of IDENTIFIER_UPGRADE_STATUSES.
history.TERMINATION_PROPOSAL_STATUSESconstUMA termination claim statuses: Pending, Disputed, Accepted, ScheduleRefused, Superseded, Rejected.
history.TerminationProposalStatustypeOne of TERMINATION_PROPOSAL_STATUSES.
history.INSURER_PROPOSAL_STATUSESconstInsurer vote statuses: Open, Scheduled, Failed, Preempted, Voided, Rejected.
history.InsurerProposalStatustypeOne of INSURER_PROPOSAL_STATUSES.
history.CANCEL_REASON_TEXTconstWhy an order was canceled, in a sentence for its owner.
history.CANDLE_INTERVALSconstThe candle intervals the subgraph keeps, in seconds: 1m, 5m, 15m, 1h, 4h, 1d.
history.CandleIntervaltypeOne of CANDLE_INTERVALS (seconds).
history.TradeinterfaceOne fill.
history.CandleinterfaceOHLCV over fills.
history.PairDayDatainterfaceA pair’s figures for one UTC day: volume, trade count, fees and OHLC.
history.HistoryOrderinterfaceAn order as the subgraph records it: type, side, sizes and prices, status, integrator, cancel reason and times.
history.OrderEventinterfaceOne OrderUpdated, OrderAmended or OrderAmendSkipped log.
history.HistoryPositioninterfaceA position as the subgraph records it: side, size, entry value and price, collateral, funding index and totals.
history.PositionSnapshotinterfaceThe full stored position a PositionBucketUpdated log reported.
history.PositionChangeinterfaceA trade’s effect on one position: the maker’s per fill, the taker’s once per order walk at its VWAP.
history.CollateralTransferinterfaceOne collateral deposit or withdrawal.
history.FeeBalanceinterfaceA recipient’s claimable balance on one pair: integrator fees, keeper rewards, relayer fees, refunds.
history.FeeMovementinterfaceOne credit to a claimable balance (FeeAccrued), or one claim of it (FeesClaimed).
history.LiquidationinterfaceOne liquidation: the account, the liquidator, size, bankruptcy price, price, notional and collateral seized.
history.AdlWindowinterfaceOne ADL window, from the AdlTriggered that opened it to AdlResolved or the pair’s termination.
history.AdlBatchinterfaceOne executeAdl call.
history.AdlFillinterfaceOne winner an ADL batch closed, fully or in part.
history.InsuranceProviderinterfaceAn insurance LP on one pair: live shares, totals deposited and withdrawn, the pending request and lock, and levies.
history.InsuranceEventinterfaceOne insurance event: a deposit, request, lock, payout or levy, with amount and shares.
history.PairTerminationinterfaceA finalized termination: the settlement price, what is owed, bad debt, the pot and the payout ratios.
history.TerminalRatioUpdateinterfaceA post-finalize settlement re-derived the payout ratios on the entitlements still unpaid.
history.TerminationProposalinterfaceA UMA termination claim.
history.InsurerProposalinterfaceAn insurer termination vote: proposer, cutoff, window, whether a UMA claim backs it, the snapshot and the status.
history.InsurerVoteinterfaceOne yes-vote on an insurer proposal: voter, shares and the running total.
history.InsurerLevyinterfaceOne levy charged on a yes-voter’s shares after an insurer-vote termination.
history.ListingProposalinterfaceA listing proposal: pair id, deployer, feed, description, seed, status and times.
history.IdentifierUpgradeProposalinterfaceAn identifier-upgrade proposal: proposer, new identifier, status and times.
history.IntegratorStatsinterfaceWhat one integrator address has routed.
history.AccountStatsinterfaceAn account’s lifetime totals: trades, volumes, fees paid, realized PnL, liquidations and bounties.
history.AccountDayDatainterfaceAn account’s totals for one UTC day.
history.ProtocolDayDatainterfaceProtocol-wide totals for one UTC day: volume, trades, fees, liquidations and unique traders.
history.MetaTransactioninterfaceOne relayed (gasless) action: the user, the relayer, the action’s type hash, nonce and fee.
history.PermitFailureinterfaceAn ERC-2612 permit the pair could not execute; the call went on with the existing allowance.
history.BookLevelinterfaceResting size at one price on one side.
history.PageinterfaceA page of results; next is the cursor for the following page, null at the end.
history.PageOptionsinterfacePaging options every query takes: first (1 to 1000, default 100), after (a cursor) and atBlock.
history.TimeOptionsinterfacePageOptions plus from, to (seconds) and order.
history.TradeFilterinterfaceFilters of trades: pair, account, maker, taker, plus TimeOptions.
history.MAX_FILLED_CANDLESconstThe most candles fillCandleGaps returns: about 69 days of 1-minute candles, more than a chart shows.
history.BookLevelOptionsinterfaceOptions of bookLevels: the side ("bid" or "ask") plus PageOptions.
history.OrderFilterinterfaceFilters of orders: account, pair, status, openOnly, order type, integrator, plus TimeOptions.
history.OrderEventFilterinterfaceFilters of orderEvents: account, pair, order id (with pair), action, plus TimeOptions.
history.PositionFilterinterfaceFilters of positions: account, pair, openOnly, plus PageOptions.
history.AccountPairFilterinterfaceAn account and pair filter plus TimeOptions, used by several queries.
history.RecipientFilterinterfaceFilters of the fee queries: the recipient and pair, plus TimeOptions.
history.MetaTxFilterinterfaceFilters of metaTransactions: user, relayer, pair, plus TimeOptions.
history.SubgraphLaginterfaceWhat subgraphLag returns: the indexed block and time, the chain head, and how far behind the index is.

previews

What an order or a withdrawal would do, computed with the pair’s own arithmetic.

ExportKindWhat it is
previews.takerInsuranceFeeBasefunctionRiskParamsLib.getTakerInsuranceFeeBase: the taker’s base insurance rate (EBP) at a fund target ratio (bp).
previews.takerInsuranceFeeRatesfunctionRiskParamsLib.getInsuranceFeeRates: the taker insurance rates (EBP) from the fund’s coverage and its target ratio.
previews.takerFillFeefunctionOne taker fill’s fee (MatchingEngineLib._computePairFees, taker side).
previews.makerFillFeefunctionOne maker fill’s fee: a flat 0.25 bp insurance leg, plus 0.25 bp when the order carries an integrator.
previews.feeBreakdownfunctionWhere a fee goes (MatchingEngineLib._finalizeTx).
previews.applyFillfunctionMatchingEngineLib._applyFillCore: one fill’s effect on a position.
previews.positionStatefunctionBucketLib.calculateState for a bucket, at the effective maintenance rate.
previews.fillMarginOkfunctionMatchingEngineLib._checkMargin: whether a fill of fillSize at price (the maker’s limit) passes the account’s margin gate at the oracle mark.
previews.liquidationPricefunctionThe estimated liquidation price of a position.
previews.maxLeveragefunctionThe most leverage the pair allows a new position now: 1 / imrBp (25 at a 4% initial margin).
previews.worstCaseNotionalfunctionCollateralLib._worstCaseNotional: the position plus same-side orders, or the opposite orders’ overshoot into a flip.
previews.fillDebitfunctionCollateralLib._fillDebitOf.
previews.restingReservefunctionCollateralLib._sweepRestingReserve: the account’s live orders reserved at mark.
previews.creationGatefunctionOrderManagementLib._creationShortfall: what createOrder requires of the account’s collateral.
previews.simulateOrderfunctionRun an order through the pair’s arithmetic with every input given.
previews.previewOrderfunction, bzPreview an order for account on pair: the resulting position, the fills it meets in the current book with their fees, the collateral it requires, the liquidation price, the leverage allowed, and every reason the pair would refuse it.
previews.previewWithdrawalfunction, bzPreview a collateral withdrawal.
previews.MAKER_INSURANCE_FEE_EBPconstBazaarTypes.MAKER_INSURANCE_FEE_EBP: 0.25 bp, flat.
previews.MAKER_INTEGRATOR_FEE_EBPconstBazaarTypes.MAKER_INTEGRATOR_FEE_EBP: 0.25 bp, only on orders that carry an integrator.
previews.TAKER_INTEGRATOR_FEE_EBPconstBazaarTypes.TAKER_INTEGRATOR_FEE_EBP: 0.25 bp, only on orders that carry an integrator.
previews.TAKER_INSURANCE_FEE_MIN_EBPconstRiskParamsLib taker insurance curve: 0.75 bp at the 2% target, 4.25 bp at 10%, x(1 + 49 d^2) below target, 50 bp cap.
previews.TAKER_INSURANCE_FEE_MAX_EBPconstThe taker insurance rate at the 10% target ratio: 4.25 bp (EBP).
previews.TAKER_INSURANCE_FEE_MULTIPLIERconstThe below-target multiplier of the taker insurance curve: 49.
previews.TAKER_INSURANCE_FEE_CAP_EBPconstThe taker insurance rate’s cap: 50 bp (EBP).
previews.INSURANCE_TARGET_BASE_BPconstBazaarTypes.INSURANCE_TARGET_BASE / _MAX, in bp of open-interest notional.
previews.INSURANCE_TARGET_MAX_BPconstThe insurance fund’s largest target ratio: 10% of open-interest notional (bp).
previews.BUG_BOUNTY_TAX_BPconstBazaarTypes.BUG_BOUNTY_TAX_BP: 1% of the insurance and integrator fee streams.
previews.MAX_SLIPPAGE_BPconstBazaarTypes.MAX_SLIPPAGE_BP: 10%.
previews.MAX_PLACEMENT_DEVIATION_BPconstBazaarTypes.MAX_PLACEMENT_DEVIATION_BP: a Limit must sit within 50% of the price.
previews.MAX_STALE_DEVIATION_BPconstBazaarTypes.MAX_STALE_DEVIATION_BP: fills under the stale fallback stay within 10% of it.
previews.MAX_ACTIVE_LIMIT_ORDERSconstBazaarTypes.MAX_ACTIVE_LIMIT_ORDERS_PER_USER.
previews.TakerFeeRatesinterfaceTaker insurance rates (EBP): the dynamic rate for risk-adding notional and the base rate for risk-reducing notional.
previews.FillFeeinterfaceOne fill’s fee: the insurance leg, the integrator leg and the total.
previews.FeeBreakdowninterfaceA fee split into what goes to the insurance fund, the integrator and the bug bounty.
previews.BucketinterfaceA position bucket as the pair stores it (BAZAAR precision; entryFundingIndex signed).
previews.MarginRatesinterfaceMargin rates in bp: initial, maintenance and the lagged maintenance rate.
previews.FillResultinterfaceWhat applyFill returns: the new bucket, the realized price PnL and the funding settled.
previews.RestingOrderinterfaceA live resting order as the reservation reads it.
previews.RestingReserveinterfaceWhat restingReserve returns: the long and short exposure the live orders are reserved at, and the fill debit.
previews.CreationGateinterfaceWhat creationGate returns: the collateral createOrder requires and whether the account has it.
previews.OrderInputinterfaceAn order as the preview takes it.
previews.BookMakerinterfaceA resting order on the opposite side of the book, in book order.
previews.SimulateInputinterfaceWhat simulateOrder takes: the order, account, bucket, mark, funding index, margin rates, book and the rest.
previews.PreviewFillinterfaceOne fill in a preview: price, size, notional, role, fee, and whether it is a resting remainder assumed filled later.
previews.PositionViewinterfaceA position in a preview: side, size, entry value and price, collateral, PnL and margin at the mark.
previews.PreviewIssueinterfaceA reason the contract would refuse the call (or the walk would cancel the order), with its user message.
previews.OrderPreviewinterfaceA preview’s position before, after everything fills and after this transaction, with fills, fees and issues.
previews.PriceInputinterfaceA price to judge at: the spot (and bracket) of the update the call will carry.
previews.PreviewOptionsinterfaceOptions of previewOrder: the price the call will carry, walkBook, and the fillPrice to assume without the book.
previews.OrderPreviewResultinterfaceWhat previewOrder returns: the OrderPreview plus the mark, the venue, the fee rates and the margin rates.
previews.WithdrawalPreviewinterfaceWhat previewWithdrawal returns: the most that can be withdrawn now, and every freeze that applies.

termination

Ending a market, fixing its settlement price, finalizing it and withdrawing after.

ExportKindWhat it is
termination.terminatorConstantsfunction, bzThe terminator’s public constants (categories, outcomes, verdicts, settlement rules, bonds, liveness, reason length, sample count and spacing).
termination.requiredTerminationBondfunction, bzThe USDC bond (6 decimals) a UMA termination claim posts now: max(1,000 USDC, UMA’s minimum).
termination.settlementRulefunction, bzHow terminateScheduledPair would settle the market if called now, and what it needs.
termination.terminationProposalfunction, bzA UMA termination claim by its assertion id, or null when the terminator has none.
termination.insurerProposalfunction, bzAn insurer-termination proposal by id (a claim’s assertion id, or a bare proposal’s id), or null when none exists.
termination.getInsurerVotefunction, bzShares voter has voted into proposal id on pair (0 when the record is dead or absent); after the fix, the voted stake the levy still draws on.
termination.getLockedSharesfunction, bzShares user has voted into live proposals on pair: what the insurance withdrawal gate refuses to release.
termination.getTerminalEntitlementfunction, bzThe lens’s terminal entitlement for account on pair.
termination.openProposalsfunction, bzThe open proposals on pair: UMA claims not yet resolved and insurer votes not yet resolved.
termination.terminationStatusfunction, bzA market’s termination status in one call.
termination.reasonProblemfunctionWhy a termination reason would be refused, or null when the terminator accepts it (1 to 1,000 bytes of a restricted character set).
termination.unjudgedLevyBpfunctionThe levy (basis points) an unjudged outcome charges with yes of snapshot voted: 50% × dissent, at least 10%.
termination.proposeTerminationfunction, bzPropose ending a market through UMA.
termination.settleTerminationProposalfunction, bzSettle a UMA termination claim once UMA can resolve it.
termination.insurerProposalIdfunctionkeccak256(abi.encode(pair, proposer, timestamp)): a bare insurer proposal’s id, fixed by the second it is filed.
termination.proposeInsurerTerminationfunction, bzPropose that a market stop trading at cutoffTs with no UMA claim behind it (a bare insurer proposal).
termination.voteForInsurerTerminationfunction, bzVote yes on insurer proposal id by locking shares of your insurance shares.
termination.executeInsurerTerminationfunction, bzResolve insurer proposal id (anyone may).
termination.terminateStalePairfunction, bzEnd a market that has stored no price for more than 21 days, at its last stored price (or at a nominal price of 1 when it never stored one, aged from its creation).
termination.tickFetcherfunctionA TickFetcher over the context’s price source (its atTick).
termination.settlementPrintfunctionOne feed as a one-second update carries it; throws SettlementPrintError where the oracle would refuse the update for that feed.
termination.generatedAtOrAfterfunctionWhether a settlement print carries a price generated at or after a target second (BazaarOracle._pricedSince).
termination.tickPrintsfunctionUMA’s rule: Pyth’s one-second update stamped at the cutoff for every leg, one update for a composite when its legs can be asked for together.
termination.chainSamplefunctionOne leg of one chain sample: the earliest one-second update carrying a price generated at or after the target, with the quiet update before it when it is not the target’s own.
termination.chainPrintsfunctionThe chain rule’s sample set.
termination.terminateScheduledPairfunction, bzBuild terminateScheduledPair(pair, priceUpdate).
termination.chainLastResortfunctionThe chain rule’s last resort (BazaarPairTerminator._insurerSettlementBounds): 21 days after the cutoff, or 12 hours after a capping UMA cutoff when sooner.
termination.finalizeTerminationfunction, bzFinalize a terminated market (stage 2, on the pair).
termination.decodeTerminatorLogfunctionDecode a terminator log, or null for another contract’s.
termination.proposalIdsFromReceiptfunction, bzThe proposal ids a proposeTermination or proposeInsurerTermination receipt created.
termination.TERMINATION_PROPOSAL_BOND_USDCconstThe UMA termination bond’s floor (USDC units); the bond posted is requiredTerminationBond(), which tracks UMA’s own minimum upward.
termination.TERMINATION_PROPOSAL_LIVENESSconstUMA liveness of a termination claim (seconds).
termination.MAX_REASON_LENGTHconstLongest reason a termination claim takes, in bytes.
termination.MIN_CUTOFF_LEADconstA cutoff sooner than this after acceptance is moved to this far after it (BazaarTypes.MIN_CUTOFF_LEAD: limbo lead + 1 s).
termination.INSURER_TERMINATION_MIN_LEADconstEarliest a proposed cutoff may sit after the proposal, for a UMA claim and a bare insurer proposal alike (seconds).
termination.INSURER_TERMINATION_LATCH_LEADconstVoting and the latch close this long before a proposal’s cutoff (seconds).
termination.INSURER_TERMINATION_MAX_LEADconstVotes open this long before the cutoff (or at filing if later), and a bare cutoff may sit no further out (seconds).
termination.INSURER_TERMINATION_THRESHOLD_BPconstShare of the snapshot that must vote yes (basis points).
termination.INSURER_TERMINATION_BOND_USDCconstThe bond a bare insurer proposal posts (USDC units), a fixed figure.
termination.INSURER_SHARE_MATURITY_PERIODconstShares must be held this long before the vote window opens to vote (seconds).
termination.INSURER_MAX_LIVE_VOTESconstMost live proposals one voter may back on a pair.
termination.INSURER_LEVY_BPconstLevy on each yes-voted share when the claim behind the vote is rejected (basis points).
termination.INSURER_LEVY_FLOOR_BPconstThe least an unjudged outcome levies on each yes-voted share (basis points).
termination.CLAIM_VERDICT_GRACEconstHow long after a claim is filed its vote-scheduled pair waits for the verdict (seconds).
termination.INSURER_POST_FIX_LOCKconstYes-voters of a costed outcome stay locked this long after the price fix: the insurance withdrawal cooldown (seconds).
termination.SCHEDULED_TERMINATION_GRACEconstUnder UMA’s rule only the precise print settles for this long after the cutoff (or the verdict); then an empty call settles at the stored price (seconds).
termination.NEVER_PRICED_SETTLEMENT_PRICEconstThe settlement price (BAZAAR precision) a pair that never stored a price settles at under the stored-price paths (NEVER_PRICED_SETTLEMENT_PRICE).
termination.PAIR_SLOT_SHARE_EPOCHconstBazaarPair storage slot of shareEpoch, which the terminator reads with extsload (PAIR_SLOT_SHARE_EPOCH).
termination.TerminationCategoryconst + typeThe four grounds a UMA termination claim may declare.
termination.TERMINATION_CATEGORY_INFOconstWhat each category means, condensed from the claim text the terminator writes into UMA’s assertion.
termination.SettlementRuleKeytypeA settlement rule’s name: nothing, window, chain or awaitVerdict.
termination.SETTLEMENT_RULE_KEYSconstsettlementRule’s answers, by number.
termination.SETTLEMENT_RULE_TEXTconstWhat each settlement rule means.
termination.VerdictNametypeA UMA verdict’s name: pending, true or false.
termination.VERDICT_NAMESconstVerdict names by the terminator’s number.
termination.OutcomeNametypeAn insurer-vote outcome’s name: none, true, false or unjudged.
termination.OUTCOME_NAMESconstOutcome names by the terminator’s number.
termination.OUTCOME_TEXTconstWhat each insurer-vote outcome means for its yes-voters.
termination.TerminatorConstantsinterfaceThe terminator’s public constants, read from the chain, plus the live bond.
termination.SettlementRuleInfointerfacesettlementRule(pair), decoded.
termination.TerminationProposalInfointerfaceA UMA termination claim, from terminationProposals(assertionId).
termination.InsurerProposalStatetypeWhere an insurer vote stands at the chain’s time.
termination.InsurerProposalInfointerfaceAn insurer-termination proposal, from insurerProposals(id).
termination.TerminalEntitlementinterfaceWhat a terminated market pays an account.
termination.TerminationPhasetypeWhere a market is on its way to termination.
termination.OpenProposalsinterfaceProposals still open on a market, and where their ids came from.
termination.TerminationStatusinterfaceA market’s termination state in one call.
termination.ProposalSearchinterfaceWhere to look for a market’s open proposals.
termination.MAX_OPEN_PROPOSALSconstThe most open proposals of each kind (UMA claims, insurer votes) openProposals takes from the subgraph for one market.
termination.maturityCutoffconstThe maturity cutoff for a vote whose window opened at windowOpenTs: shares deposited at or before it vote.
termination.voteWindowOpensconstWhen a claim’s vote window opens: 14 days before its cutoff, or at filing (now) when that is later.
termination.InsurerExecutionOutcometypeWhat executing an insurer vote would do now.
termination.SettlementPrintinterfaceOne of Pyth’s one-second updates, read for one feed, as settlement evidence.
termination.TickFetchertypePyth’s one-second update stamped on a second, carrying the feeds asked for, or null when the archive has none.
termination.SettlementPrintErrorclassA settlement update that could not be fetched, or a sample that cannot be proven.
termination.TickProofinterfaceWhat UMA’s rule settles a market with: the cutoff’s update for every leg.
termination.ChainProofinterfaceWhat the chain rule settles a market with: the updates in calldata order, the targets and the samples’ seconds.
termination.ChainSearchBoundsinterfaceHow far a chain sample may be searched for: the latest second allowed, and the present.
termination.SettleUndertypeWhich rule a terminateScheduledPair call settles under: UMA’s cutoff update (tick), the chain’s median, or the stored-price last resort.
termination.SettlementAttemptinterfaceOne candidate the builder tried.
termination.ScheduledSettlementPlaninterfaceWhat terminateScheduledPair needs now.
termination.TERMINATOR_EVENT_TEXTconstWhat each terminator event means, for an activity feed.

listings

Proposing and settling new markets.

ExportKindWhat it is
listings.descriptionProblemfunctionWhy a listing description would be refused, or null when the factory accepts it: 1 to 200 bytes of letters, digits, space and . , & / -.
listings.compositeIdfunctionkeccak256(baseId ‖ quoteId ‖ invertQuote): the id a composite is registered and listed under (BazaarOracle.getCompositeId).
listings.asFeedIdfunctionThe bytes32 feed ID for a Pyth Pro feed number, decimal digits, or a bytes32; an InputError for anything else.
listings.FeedIdInputtypeA feed ID as a caller may give it: the Pyth Pro feed number or the bytes32 that holds it.
listings.getCompositefunction, bzThe legs id resolves to on the oracle, or null when it is not a registered composite (a plain feed id, or an unregistered one).
listings.registerCompositefunction, bzRegister a composite feed on Bazaar’s oracle, so compositeId(baseId, quoteId, invertQuote) can be listed.
listings.deploymentConstantsfunction, bzMIN_DEPLOYMENT_AMOUNT, DEPLOYMENT_BOND_USDC, the live requiredDeploymentBond, DEPLOYMENT_LIVENESS and DVM_DISPUTE_GRACE.
listings.requiredDeploymentBondfunction, bzThe USDC bond (6 decimals) a listing posts now: max(1,000 USDC, UMA’s minimum).
listings.deploymentProposalfunction, bzA listing proposal by its UMA assertion id, or null when the factory has none.
listings.rawBaseFeedfunction, bzThe raw Pyth feed a listing prices: the feed itself, or a composite’s base leg (the key one-market-per-asset is enforced on).
listings.pendingDeploymentfunction, bzThe listing proposal pending for an asset, or null.
listings.openListingsfunction, bzThe listing proposals not yet resolved, found through the subgraph, the factory’s logs or given ids, each read on chain.
listings.seedRefundOwedfunction, bzUSDC (6 decimals) account may collect with claimSeedRefund from listings that did not deploy.
listings.proposePairDeploymentfunction, bzPropose listing a market.
listings.settleDeploymentProposalfunction, bzSettle a listing once UMA can resolve it.
listings.expireStuckDeploymentProposalfunction, bzRelease an asset’s listing slot when its assertion cannot settle on UMA’s oracle (a blacklisted payee, a dispute the DVM never resolves).
listings.claimSeedRefundfunction, bzWithdraw the seed credited back to the caller by listings that did not deploy (rejected, voided or released).
listings.decodeFactoryLogfunctionDecode a factory log, or null for another contract’s.
listings.listingFromReceiptfunction, bzThe assertion id and pair id a proposePairDeployment receipt created, or null.
listings.MIN_DEPLOYMENT_AMOUNTconstLeast totalAmount a listing takes (BAZAAR precision): $1,000 bond + $3,000 seed.
listings.DEPLOYMENT_BOND_USDCconstThe listing bond’s floor (USDC units); the bond posted is requiredDeploymentBond(), which tracks UMA’s minimum upward.
listings.DEPLOYMENT_LIVENESSconstUMA liveness of a listing (seconds).
listings.DVM_DISPUTE_GRACEconstExtra wait before a disputed listing that cannot settle may be released (seconds).
listings.MIN_INSURANCE_SEEDconstLeast insurance seed a pair is deployed with (BAZAAR precision): what remains of totalAmount after the bond.
listings.MAX_DESCRIPTION_LENGTHconstLongest listing description, in bytes.
listings.PAIR_DEPLOYMENT_PROPOSAL_VOIDEDconstWhat PairDeploymentProposalVoided means.
listings.LISTING_EVENT_TEXTconstWhat each factory listing event means, for an activity feed.
listings.CompositeFeedinterfaceA composite feed’s legs.
listings.DeploymentConstantsinterfaceThe factory’s listing constants, read from the chain, plus the live bond.
listings.DeploymentStatustypeWhere a listing stands.
listings.DeploymentProposalInfointerfaceA listing proposal, from getDeploymentProposal(assertionId).
listings.ListingSearchinterfaceWhere openListings looks for listing proposals.
listings.OpenListingsinterfaceThe unresolved listing proposals and where their ids came from.
listings.MAX_OPEN_LISTINGSconstThe most open listings openListings takes from the subgraph.
listings.MAX_LISTING_IDSconstThe most listing ids openListings reads on chain in one call.

governance

UMA identifier upgrades.

ExportKindWhat it is
governance.isAssertTruthIdentifierfunctionTrue when identifier’s first 12 bytes are ASCII “ASSERT_TRUTH” (the factory’s truth-identifier rule).
governance.parseIdentifierfunctionAn identifier given as bytes32 hex or as its text (“ASSERT_TRUTH2”).
governance.identifierUpgradeConstantsfunction, bzIDENTIFIER_UPGRADE_BOND_USDC, the live requiredIdentifierUpgradeBond, LIVENESS, TIMELOCK, MIN_NOTICE and DVM_DISPUTE_GRACE.
governance.requiredIdentifierUpgradeBondfunction, bzThe USDC bond (6 decimals) an identifier-upgrade proposal posts now: max(5,000 USDC, UMA’s minimum).
governance.umaIdentifierfunction, bzThe identifier Bazaar’s assertions are made under, as bytes32.
governance.umaIdentifierIsLivefunction, bzWhether Bazaar’s identifier is on UMA’s live whitelist.
governance.identifierUpgradeProposalfunction, bzAn identifier-upgrade proposal by its assertion id, or null when the factory has none.
governance.identifierGovernancefunction, bzThe identifier in force, whether it is live on UMA’s whitelist, the pending upgrade (with where its UMA assertion stands) and the queued one (with when it may activate).
governance.proposeUmaIdentifierUpgradefunction, bzPropose switching Bazaar to newIdentifier.
governance.settleIdentifierUpgradeProposalfunction, bzSettle an identifier-upgrade proposal once UMA can resolve it: UMA pays the bond to the winning side, and an approved upgrade is queued behind the timelock.
governance.expireStuckIdentifierUpgradeProposalfunction, bzRelease the single pending-upgrade slot when its assertion cannot settle on UMA’s oracle.
governance.activateIdentifierUpgradefunction, bzActivate the queued identifier upgrade once its timelock has run (or 4 days after approval while the incumbent is off UMA’s whitelist).
governance.IDENTIFIER_UPGRADE_BOND_USDCconstThe identifier-upgrade bond’s floor (USDC units); the bond posted is requiredIdentifierUpgradeBond().
governance.IDENTIFIER_UPGRADE_LIVENESSconstUMA liveness of an identifier-upgrade proposal (seconds).
governance.IDENTIFIER_UPGRADE_TIMELOCKconstDelay between approval and activation (seconds).
governance.IDENTIFIER_UPGRADE_MIN_NOTICEconstDelay between approval and activation once the incumbent identifier is off UMA’s live whitelist (seconds).
governance.ASSERT_TRUTH_PREFIXconstEvery adjudication identifier begins with these 12 ASCII bytes.
governance.IdentifierUpgradeConstantsinterfaceThe governance track’s constants, read from the factory, plus the live bond.
governance.IdentifierUpgradeProposalInfointerfaceAn identifier-upgrade proposal.
governance.QueuedIdentifierUpgradeinterfaceAn approved upgrade waiting out its timelock.
governance.IdentifierGovernanceStatusinterfaceThe governance track in one call.
governance.IDENTIFIER_UPGRADE_EVENT_TEXTconstWhat each governance event means, for an activity feed (decode them with listings’ decodeFactoryLog).

uma

UMA assertions, disputes and settlement, and the shared helpers the costed builders use.

ExportKindWhat it is
uma.optimisticOracleCodecfunctionCodec for the Optimistic Oracle V3 fragment.
uma.erc20CodecfunctionCodec for ERC-20 (USDC’s approve, allowance, balanceOf, decimals).
uma.readManyfunction, bzSeveral reads in as few eth_calls as the node allows (Chain.batch), decoded.
uma.readOnefunction, bzOne read.
uma.chainNowfunction, bzThe latest block’s timestamp: what the contracts’ block.timestamp checks are judged against.
uma.usdcTextfunctionUSDC units (6 decimals) as “1,000 USDC”, exactly (“1,000.009999 USDC”).
uma.sharesTextfunctionInsurance shares (18 decimals) as “1,234.5678 shares”, exactly.
uma.ethTextfunctionETH in wei as “0.000001 ETH”, exactly (7 wei is “0.000000000000000007 ETH”).
uma.timeTextfunctionA unix time (seconds) as “2026-11-08 14:00:00 UTC”.
uma.durationTextfunctionA duration in seconds as “12 hours”, “14 days”, “7 seconds”.
uma.asBytes32functionA bytes32 field the caller typed, checked.
uma.asAddressfunctionAn address the caller typed, checked and checksummed.
uma.requireBondFloorfunctionThrows BondQuoteError when quoted (USDC units) is below floor, the contract’s own minimum for what.
uma.approveCallfunctionAn ERC-20 approve as a PreparedCall.
uma.bondApprovalsfunction, bzThe approvals owner must send before a call that pulls pulls, and what to tell them.
uma.identifierFromTextfunction“ASSERT_TRUTH2” -> its bytes32 (ASCII, right-padded with zeros), as UMA stores identifiers.
uma.identifierTextfunctionA bytes32 identifier as its ASCII text (“ASSERT_TRUTH2”), or null when it is not printable ASCII.
uma.optimisticOraclefunction, bzThe deployment’s Optimistic Oracle: factory.oo(), immutable.
uma.assertionOraclefunction, bzThe oracle assertionId was made on: factory.assertionOo(id) or terminator.assertionOo(id), falling back to factory.oo() when the record is empty (an id neither contract made).
uma.getAssertionfunction, bzThe assertion record on oo, or null for an unknown id (OOv3 returns an all-zero record).
uma.assertionPhasefunctionThe phase of an assertion at chain time now.
uma.statusOffunctionThe status of an assertion judged at now.
uma.assertionStatusfunction, bzWhere an assertion stands: pending its liveness (with the time it can settle), settleable, disputed (waiting on the DVM), or settled true or false.
uma.getMinimumBondfunction, bzThe smallest bond OOv3 accepts in currency (USDC by default), in its units; 0 when OOv3 has never cached it.
uma.defaultIdentifierfunction, bzOOv3’s default identifier.
uma.burnedBondPercentagefunction, bzThe share of a disputed bond UMA burns as its fee, 1e18 = 100% (50% on the live OOv3), or null if the oracle does not report it.
uma.identifierWhitelistedfunction, bzWhether identifier is on UMA’s live IdentifierWhitelist, resolved as the factory and OOv3 resolve it: oracle -> finder -> IdentifierWhitelist -> isIdentifierSupported.
uma.previewSettlementfunction, bzSimulate OOv3’s settleAndGetAssertionResult(assertionId) without sending it.
uma.previewSettlementOnfunctionpreviewSettlement on an oracle the caller already resolved with assertionOracle (no check of oo, so never pass one a user gave).
uma.decodeAssertionLogfunctionDecode an OOv3 log (AssertionMade, AssertionDisputed, AssertionSettled), or null for another contract’s.
uma.disputeAssertionfunction, bzDispute an assertion: you match its bond, and UMA’s DVM votes on the claim.
uma.settleAssertionfunction, bzSettle an assertion on the oracle directly.
uma.requireSettleablefunctionThrows the InputError a settle attempt deserves when the assertion cannot settle yet.
uma.optimisticOracleV3AbiconstThe slice of UMA’s OptimisticOracleV3Interface these flows need.
uma.isZero32constTrue for the all-zero bytes32 the contracts use as “none”.
uma.ContractReadinterfaceOne read for readMany.
uma.ReadErrorclassA read that reverted, with its decoded reason.
uma.CostKindtypeWhat a cost is: a bond (returned or forfeited by a verdict), an insurance seed, an ETH fee, a levy on shares, or shares locked.
uma.CostinterfaceOne thing a call costs or puts at risk, for a confirmation screen.
uma.CostedCallinterfaceA prepared write that posts a bond, moves money or locks shares, with what it costs.
uma.TokenPullinterfaceA bond or seed an ERC-20 transferFrom will pull from the caller.
uma.MIN_ASSERTION_BOND_USDCconstThe least bond any Bazaar assertion posts (USDC units): the listing and termination floors; an identifier upgrade’s is 5,000 USDC.
uma.BondQuoteErrorclassA bond quote read from the chain that cannot be right: below the floor the contract itself enforces (an RPC answering 0, say).
uma.AssertionHometypeWhere an assertion was made: the factory (listings, identifier upgrades) or the terminator (termination claims).
uma.UmaAssertioninterfaceAn OOv3 assertion record.
uma.AssertionPhasetypeWhere an assertion stands, for a UI.
uma.AssertionStatusinterfaceWhat assertionStatus returns: the phase, the assertion record, and when it can be settled.
uma.ASSERTION_PHASE_TEXTconstText for each assertion phase.
uma.SettlementPreviewinterfaceWhat settling an assertion would do right now.
uma.ASSERTION_EVENT_TEXTconstWhat each OOv3 event means, for an activity feed.

format

The error messages and the display formatters (errors/messages.ts).

ExportKindWhat it is
format.formatUsdfunctionA BAZAAR-precision amount as dollars: “$1,234.56”; amounts under a cent keep six decimals.
format.formatPricefunctionA BAZAAR-precision price: “$3,012.5”, “$1.08765”, “$0.00001234”.
format.formatAmountfunctionA BAZAAR-precision quantity (size, shares): “1.25”, “12,000”.
format.formatBpfunctionBasis points as percent: 250 -> “2.5%”.
format.formatEthfunctionWei as ETH: “0.0001 ETH”.
format.formatDurationfunctionA duration in seconds, roughly: “45 s”, “12 min”, “3 h”, “13 days”.
format.formatTimefunctionA Unix time (seconds) as “2026-11-08 14:00 UTC (in 3 h)”.
format.installUserMessagesfunctionRegister USER_MESSAGES so DecodedError.message returns them.
format.userMessagefunctionThe user-facing message for a custom error by name, with its arguments; the name itself when unknown.
format.walletErrorMessagefunctionA message for a failure the wallet raised rather than the contract.
format.errorMessagefunctionThe text to show a user for any error a Bazaar call can throw.
format.USER_MESSAGESconstEvery custom error’s user-facing message, by error name.

Low-Level Exports

The chain, ABI, price, formula and market layers the keeper and the areas are built on. See Low-Level Building Blocks.

Protocol Constants

ExportKindWhat it is
BAZAAR_SCALEconst1e18: BAZAAR precision, $1 or one unit.
BP_SCALEconst10,000: basis points in 100%.
EBP_SCALEconst1,000,000: EBP (1/100 bp) in 100%.
USDC_DECIMALSconst6.
USDC_TO_BAZAARconstBAZAAR precision carries twelve more decimals than USDC.
MAX_PRICE_STALENESSconstSeconds a print may sit from the block’s timestamp: 3.
LIMBO_LEADconstSeconds before a scheduled cutoff that trading halts: 6.
MIN_ORDER_AMOUNTconstThe smallest order notional: $5 (BAZAAR precision).
MIN_COLLATERAL_DEPOSITconstThe smallest collateral deposit: $5 (BAZAAR precision).
MAX_WALK_STEPSconstThe default and largest walk budget of an arriving order: 32.
MAX_TRIGGER_EXECS_PER_CALLconstTrigger orders one executeTriggeredOrders call fires at most: 20.
LIQUIDATION_FEE_EBPconstThe liquidation fee: 2 bp (EBP).
MIN_LIQUIDATOR_REWARDconstThe least a liquidation pays its caller: $0.05.
TERMINAL_SETTLEMENT_TIPconstThe tip for settling someone else’s position at the fixed settlement price: up to $0.05.
TERMINAL_SETTLEMENT_ESCAPEconstSeconds after the settlement price is fixed before finalizeTermination stops waiting for every position to be settled: 14 days.
UNLOAD_BOUNTY_MINconstThe floor of an unload’s reward: $0.25.
UNLOAD_BOUNTY_MIN_NOTIONALconstThe unload size at which the $0.25 floor applies, and the inventory notional for the fast refresh cadence: $1,250.
UNLOAD_FLOOR_DECAYconstSeconds over which the unload floor slides from the band edge to the fund-neutral price: 180.
ADL_AUCTION_DURATIONconstSeconds the ADL score threshold takes to decay: 600.
ADL_MAX_SCOREconstThe ADL score threshold at the start of the auction: 25 (BAZAAR precision).
ADL_TERMINATION_GRACEconstSeconds after the first price stored past an ADL timeout before the market winds down: 1,800.
MAX_LIQUIDATION_PRICE_AGEconstOldest stored price (seconds) liquidate judges solvency against without a fresh priceUpdate: 600.
ADL_TIMEOUT_DURATIONconstSeconds after which an open ADL window times out: 1 day.
MAX_ADL_WINNERS_PER_BATCHconstMost entries each winner list of an ADL batch may hold: 25.
REFRESH_BOUNTYconstWhat a paid refreshPrice earns: $0.10.
REFRESH_BOUNTY_MIN_GAPconstThe fast refresh cadence: a paid refresh at most every 300 seconds.
REFRESH_BOUNTY_HEARTBEATconstThe slow refresh cadence: a paid refresh at most every day.
REFRESH_BOUNTY_FAST_MIN_INSURANCEconstFree capital above which the fast cadence applies: $5,000.
REFRESH_BOUNTY_HEARTBEAT_MIN_INSURANCEconstFree capital the fund must exceed for a refresh to pay: $1,000.
MAX_CONFIDENCE_BPconstThe widest confidence interval a leg may carry: 2% of its price (bp).
BAZAAR_EXPONENTconst-18: the exponent the oracle converts prices to.
ORACLE_DEAD_THRESHOLDconstSeconds without a stored price after which a market can be terminated as stale: 21 days.
SETTLEMENT_SAMPLE_COUNTconstSamples the chain settlement rule takes: 5.
SETTLEMENT_SAMPLE_SPACINGconstSeconds between the chain rule’s samples: 600.
SETTLE_NOTHINGconstSettlement rule 0: nothing to settle.
SETTLE_TICKconstSettlement rule 1: UMA’s rule, the update stamped at the cutoff.
SETTLE_CHAINconstSettlement rule 2: the chain rule’s median of samples.
SETTLE_AWAIT_VERDICTconstSettlement rule 3: waiting for a UMA verdict.
OrderTypeconst + typeOrder types by name (OrderType.Limit is 1), and the type of their values.
MARKETconstOrder type 0.
LIMITconstOrder type 1.
STOP_LIMITconstOrder type 2.
TAKE_PROFITconstOrder type 3.
STOP_LOSSconstOrder type 4.
TRIGGER_TYPESconstThe trigger order types: StopLimit, TakeProfit, StopLoss.
ORDER_TYPE_NAMESconstOrder type names by number.
TRIGGER_PRICE_MASKconstAn order’s trigger price sits in the low 128 bits; its keeper bounty in the high 128.
ETH_USD_FEEDconstPyth Pro ETH/USD (feed 2) as a bytes32 feed id, used to price gas.
ZERO_ADDRESSconstThe zero address.
MAX_UINT256const2^256 - 1.

Typed ABIs

ExportKindWhat it is
bazaarFactoryAbiconstBazaarFactory’s ABI, typed as const for viem.
bazaarOracleAbiconstBazaarOracle’s ABI, typed as const for viem.
bazaarPairAbiconstBazaarPair’s ABI (with the events and errors of the libraries it links), typed as const for viem.
bazaarPairLensAbiconstBazaarPairLens’s ABI, typed as const for viem.
bazaarPairTerminatorAbiconstBazaarPairTerminator’s ABI, typed as const for viem.
ABI_SOURCEconstThe Bazaar commit and date the ABIs were synced from, and whether that tree was dirty.
ABISconstThe five ABIs by contract name.
ContractNametype"BazaarFactory", "BazaarOracle", "BazaarPair", "BazaarPairLens" or "BazaarPairTerminator".
CONTRACT_NAMESconstThe five contract names.

Chain, JSON-RPC and the Probe

ExportKindWhat it is
readTextCappedfunctionA response’s body as text, holding at most maxBytes of it.
toRpcErrorfunctionNormalize whatever a transport threw into an RpcError when it carries a JSON-RPC error.
sleepfunctionA promise that resolves after ms milliseconds.
RequestArgsinterfaceA JSON-RPC request: method and params.
TransportinterfaceEIP-1193’s request method: what a browser wallet, a viem client and JsonRpc all provide.
RpcErrorclassA JSON-RPC error: its code, the node’s message and data, and the revert payload when there is one.
HttpErrorclassA non-2xx HTTP response.
ResponseTooLargeErrorclassA response body over the reader’s byte limit.
JsonRpcOptionsinterfaceOptions of JsonRpc: requests per second, timeout, retries, headers, response size cap and fetch.
RequestOptionsinterfacePer-request options of JsonRpc.request.
NEVER_RETRIEDconstMethods JsonRpc sends at most once, whatever retries says.
JsonRpcclassA small JSON-RPC client over HTTP(S): rate limited, retried on transient failures except for sends, with response bodies capped.
SendErrorclassA send whose outcome is unknown: the signed transaction left this process, but nothing settled whether the node took it.
BlockinterfaceA block’s number, timestamp, hash, parent hash and base fee.
ProbeResultinterfaceA probe simulation’s result: ok, return data, claimable balance before and after, gas, and the state flags after.
ReadinterfaceOne call in a batched read.
ReceiptinterfaceA transaction receipt: hash, block, status, gas, sender, target and logs.
BlockTagtypeA block number, or latest, pending, safe, finalized or earliest.
ChainOptionsinterfaceOptions of Chain: send, a separate transport to submit transactions through.
ChainclassChain access over any Transport: reads, batched reads, probe simulations, gas, logs, receipts and raw sends.
findDeploymentBlockfunctionThe first block whose state holds code at address.
DeploymentBlockErrorclassfindDeploymentBlock could not find the block (no code at the head, or the node cannot read old state).
FindDeploymentOptionsinterfaceOptions of findDeploymentBlock: the block range to search.
probeCodecfunctionThe simulation probe’s codec (execute, aggregate).
stateOverridefunctionThe eth_call state override that places the probe at PROBE_ADDRESS.
PROBE_ADDRESSconstWhere the probe’s code is placed by state override.
PROBE_BALANCEconstETH the override gives the probe, to pay Pyth fees inside simulations.
runtimeCodeconstruntimeCode(): the probe’s runtime bytecode.
StateOverridetypeThe eth_call state override that places the probe.

Codecs and Revert Decoding

ExportKindWhat it is
canonicalTypefunctionAn ABI parameter’s canonical type string (tuples expanded).
signaturefunctionA function or event signature string, as hashed for selectors and topics.
codecfunctionThe cached ContractCodec for one of the five contracts.
allErrorsfunctionEvery custom error the five contracts declare, by selector.
FunctionSpecinterfaceA function in a codec: name, inputs, outputs, selector.
EventSpecinterfaceAn event in a codec: name, inputs, topic0.
ErrorSpecinterfaceA custom error in a codec: name, inputs, selector.
RawLoginterfaceA log as Chain.logs and Chain.receipt return it.
DecodedLoginterfaceA decoded log: name, address, args, and where it sits.
ContractCodecclassEncode and decode one contract’s calls, return values, logs and errors (encode, decode, decodeLog, …).
factoryconstfactory(): the BazaarFactory codec.
pairconstpair(): the BazaarPair codec.
lensconstlens(): the BazaarPairLens codec.
terminatorconstterminator(): the BazaarPairTerminator codec.
oracleconstoracle(): the BazaarOracle codec.
registerUserMessagesfunctionRegister user-facing messages by error name for DecodedError.message (what installUserMessages calls).
decodeErrorfunctionRevert data as a DecodedError: the error’s name, arguments and hint.
KEEPER_HINTSconstWhat each error means for a keeper, and what to do about it.
VERIFIER_REASON_HINTSconstWhat each reason string Pyth’s verifier reverts with means for a keeper.
registerReasonMessagesfunctionRegister user-facing messages for plain revert reasons, by the reason string.
DecodedErrorclassA decoded revert: name, args, hint, data, message (the user text), and opensAt() for a too-early error.

Reader, Models and Formulas

ExportKindWhat it is
freeCapitalfunctionThe insurance balance less the seizure earmarked against inventory the vault holds.
inventorySizefunctionThe vault’s liquidated inventory size on both sides of a MarketState.
marketStatusfunctionA MarketState’s Status at a time: terminated, settling, limbo, adl or live.
marketStaticfunctionThe part of a Market that never changes.
marketFromStaticfunctionA Market rebuilt from its static part, with no state read yet.
orderRemainingfunctionAn order’s unfilled size.
Statusconst + typeA market’s status (Status.Live is "live"; also adl, limbo, settling, terminated), and the type of its values.
InventoryinterfaceThe vault’s liquidated inventory on one side: size, entry and bankruptcy notional, seized collateral, funding index.
emptyInventoryconstAn Inventory with every field zero.
MarketStateinterfaceOne read of a market’s on-chain state (Reader.marketStates).
MarketinterfaceA market as the keeper and Reader track it: address, pair id, feeds, calendar, label, and its last state read.
MarketStaticinterfaceThe part of a Market that never changes, as stored in snapshots.
PositioninterfaceAn open position as the keeper indexes it.
OrderinterfaceA live order as the keeper indexes it.
mulDivfunctionOpenZeppelin Math.mulDiv for non-negative operands: floor(x * y / d).
signedMulDivfunctionBazaarMathLib.signedMulDiv: (x * y) / d rounded toward zero.
effectiveMmrBpfunctionBucketLib.effectiveMmrBp: the lower of the current rate and a non-zero lagged one.
bucketStatefunctionBucketLib.calculateState, with mmrBp already the effective rate.
marginRatiofunctionEquity over the maintenance requirement: below 1 is liquidatable.
triggerReachedfunctionMatchingEngineLib._triggerReached, inclusive at the trigger.
adlThresholdfunctionAdlLib._getAdlScoreThreshold: quadratic decay from ADL_MAX_SCORE to 1 over the auction.
adlScorefunctionPnL over the collateral less this window’s tagged deposit, floored at 1 (AdlLib._scoreCollateral).
refreshBountyGapfunctionThe minimum gap between paid refreshes for a market (fast or heartbeat cadence).
refreshBountyDuefunctionWhether refreshPrice would pay its bounty when it stores a print published at newPublishTs.
refreshBountyDueAtfunctionThe first block time at which the bounty is payable, or null while the fund is too small.
convertExponentfunctionBazaarMathLib.convertExponent (division truncates toward zero).
legConfOkfunctionWhether a leg’s confidence interval is within 2% of its price.
pairPricefunctionThe price BazaarOracle composes from one or two legs, and whether it clears the 2% cap.
BucketStateinterfaceWhat bucketState returns: PnL, funding PnL, notional, the maintenance requirement and available equity.
MAX_EXPONENT_SHIFTconstThe largest exponent difference convertExponent takes: 10^77 is the largest power of ten a uint256 holds, so the contract reverts past it (and an unbounded one would stall the caller).
LeginterfaceOne Pyth leg of a price: price, confidence, exponent, publish time.
PairPriceinterfaceWhat pairPrice returns: spot, the confidence bracket, the publish time, and whether confidence is within the cap.
DeploymentinterfaceThe contracts a factory is wired to.
OrderRecordinterfaceorders(id) on a pair, with the lens’s triggerBounty for it.
PositionBucketinterfacepositionBuckets(account) on a pair: an account’s position as the chain holds it now.
ReaderclassBatched chain reads: the deployment’s wiring, market discovery, per-block market state, positions and orders.

Subgraph Client

ExportKindWhat it is
SUBGRAPH_PAGEconstRows per page: the most a hosted graph-node returns for one first:.
SubgraphClientclassA GraphQL client for Bazaar’s subgraph: queries, the indexer’s head, and paging pinned to a block.
SubgraphErrorclassA SubgraphClient query the subgraph refused or failed (not the same class as history.SubgraphError).
SubgraphMetatypeThe indexer’s head: the block it has indexed, its hash, and whether it hit indexing errors.
SubgraphOptionsinterfaceOptions of SubgraphClient: timeoutMs, fetch, maxResponseBytes and maxPages.

Prices: Pyth Pro, PriceService and Signed Updates

The lazer namespace holds the whole update codec; its types, its error and the feed id helpers are also at the top level.

ExportKindWhat it is
lazer.parseUpdatefunctionReads a Pyth Pro update and recovers its signer: { signer, timestampUs, channel, feeds, payload }.
lazer.readUpdatefunctionReads an update without recovering its signer.
lazer.parsePayloadfunctionReads a signed payload as LazerPayloadLib.readFeeds does; throws where the contract reverts as malformed.
lazer.splitUpdatefunctionSplits an update into its signature and its payload, as Pyth’s verifier does.
lazer.recoverSignerfunctionThe address that signed an update.
lazer.encodePayloadfunctionEncodes a payload from feed fields (tests, local chains).
lazer.signPayloadfunctionWraps a payload in the EVM envelope, signed with a private key.
lazer.buildUpdatefunctionencodePayload, then signPayload.
lazer.localSignerKeyfunctionThe private key Bazaar’s local deployments sign updates with: public by construction.
lazer.LOCAL_SIGNER_LABELconstThe label the local signing key is derived from.
lazer.normalizeHexfunctionLowercase, 0x-prefixed form of hex given with or without 0x, or null when it is not whole bytes of hex.
lazer.channelNamefunctionA payload channel number’s name, or null.
lazer.ENVELOPE_MAGICconstThe first four bytes of an update in the EVM envelope.
lazer.PAYLOAD_MAGICconstThe first four bytes of a payload.
lazer.ENVELOPE_HEADER_BYTESconstEnvelope bytes before the payload: 71.
lazer.MAX_PAYLOAD_BYTESconstThe longest payload an envelope can frame.
lazer.MICROS_PER_SECONDconst1,000,000n.
lazer.HAS_PRICEconstBit of LazerFeed.included: the payload carries the price.
lazer.HAS_EXPONENTconstBit of LazerFeed.included: the payload carries the exponent.
lazer.HAS_CONFIDENCEconstBit of LazerFeed.included: the payload carries the confidence.
lazer.HAS_FEED_UPDATE_TIMESTAMPconstBit of LazerFeed.included: the payload carries the feed update timestamp.
lazer.LIVE_PROPERTIESconstWhat a feed must carry to price a live call.
lazer.TICK_PROPERTIESconstWhat a one-second update must carry for a feed to settle a pair at it.
lazer.CHAIN_PROPERTIESconstWhat a one-second update must carry to prove a chain sample.
lazer.EnvelopeinterfaceAn update’s envelope, split: r, s, the recovery id and the payload.
CHANNEL_IDSconstEach channel’s number in a payload.
CHANNEL_FIXED_RATE_1000constThe number of the channel whose updates are stamped once per second, on whole seconds.
ChanneltypeThe channels Pyth Pro produces updates on: real_time, fixed_rate@50ms, fixed_rate@200ms, fixed_rate@1000ms.
LazerFeedinterfaceOne feed’s fields in one payload, with which properties the payload carries (included).
LazerFeedInputinterfaceOne feed to encode; a property left undefined is left out of the payload.
LazerPayloadinterfaceA payload’s contents: timestamp, channel, feeds.
LazerPayloadInputinterfaceWhat encodePayload takes.
LazerUpdateinterfaceAn update, read from its bytes: the payload’s contents, the signer, the payload.
LazerErrorclassAn update or feed id that is not valid.
feedIdHexfunctionThe bytes32 feed id that holds a Pyth Pro feed number (1 → 0x00…01).
proFeedIdfunctionThe Pyth Pro feed number a raw bytes32 feed id holds; throws on anything else.
isRawFeedIdfunctionWhether an id has the form of a raw Pyth Pro feed id (BazaarOracle.isRawFeedId).
ProClientclassA client for Pyth Pro: latest, latestUpdate, atTick, stream, symbols and close.
ProClientOptionsinterfaceOptions of ProClient: the token, the endpoints, the channel, headers, timeout, fetch, WebSocket, streamAuth and isTrustedSigner.
ProErrorclassA Pyth Pro request or stream that failed; its message never shows a token.
ProUpdateinterfaceA signed update as the client read it: the blob, the signer, the timestamp, the channel, every feed’s entry, and the live prints.
ProSymbolinterfaceOne entry of Pyth Pro’s symbols registry.
PrintinterfaceOne feed’s price and the signed update that carries it.
SignerChecktypeSays whether updates signed by a signer may be used.
TokenProvidertypeReturns the token to present: an API key (servers only) or a short-lived token minted from one.
MintedTokeninterfaceA short-lived token minted from an API key: the token, when it expires, its type.
mintProTokenfunctionExchange a Pyth Pro API key for a short-lived token (server side).
cachedTokenfunctionA token provider that mints only when the token it holds is about to expire.
UNKNOWN_EXPIRY_LIFETIMEconstSeconds a token whose expiry is unknown is reused for by cachedToken.
WebSocketConstructortypeA WebSocket constructor: the global one, or a package’s.
WebSocketLikeinterfaceThe parts of a WebSocket the client uses.
AUTH_SUBPROTOCOLconstThe subprotocol that marks the next entry of a WebSocket’s subprotocol list as the token.
DEFAULT_CHANNELconstThe channel a client streams and reads the latest price on unless told otherwise.
PRO_PROPERTIESconstThe properties every request asks for.
MAX_RESPONSE_BYTESconstThe largest response body a request may return, in bytes (16 MiB).
MAX_STREAM_MESSAGEconstThe longest message a price stream may send, in characters (1 MiB).
MAX_STREAM_NOTICESconstHow many distinct notices one stream passes to its onNotice before it drops the rest.
STREAM_IDLE_TIMEOUTconstSeconds a price stream may bring no new update before it is abandoned and reconnected.
StreamOptionsinterfaceOptions of ProClient.stream: idleTimeout and onNotice.
isLivePrintfunctionWhether a feed entry holds a price a live call could use.
whyNotLivefunctionWhy a feed entry holds no price a live call could use, or null when it holds one.
printsOffunctionThe prints a parsed update carries: one per feed that holds a live price.
ETH_USD_BOUNDSconstDefault PriceServiceOptions.ethUsdBounds.
ETH_USD_MAX_AGEconstDefault PriceServiceOptions.ethUsdMaxAge.
MAX_FUTURE_SKEWconstDefault PriceServiceOptions.maxFutureSkew.
PriceLoggerinterfaceWhere a PriceService reports warnings.
PriceServiceclassLive prints for every watched feed (streamed, or polled as a fallback), and per-market prices and updates.
PriceServiceOptionsinterfaceOptions of PriceService: streaming, idle timeout, poll interval, clock, send margin, future skew, ETH/USD age and bounds, and logger.
PriceSourceinterfaceWhere a PriceService gets its prints: a ProClient, or anything shaped like one (latest, and stream over sets of feeds).
PrintListenertypeCalled after each batch of prints with the feeds that got a newer print in it.
distinctBlobsfunctionThe distinct signed updates a list of prints came in, in the prints’ order.
feedLabelfunction‘Crypto.BTC/USD’ -> ‘BTC/USD’, ‘Equity.US.AAPL/USD’ -> ‘AAPL/USD’.
fetchFeedInfofunctionPyth Pro’s registry entries for feeds, by feed id; empty when the registry cannot be read.
fetchSymbolsfunctionPyth symbols for feeds, from the symbols registry; empty when it cannot be read.
marketLabelfunctionA market’s label from its legs’ Pyth symbols; a composite (with a quote leg) is priced in USD.

URLs

ExportKindWhat it is
isUrlfunctionWhether value is an http(s) or ws(s) URL, as fetch would read it.
urlCredentialfunctionWhere a URL may carry a credential, as a phrase (a key in its path, …), or null when it carries none.
redactUrlfunctionThe URL with every part not known to be public replaced by mask, safe to print or log (see the module’s rules).
PATH_WORDSconstPath segments that are never secret (compared without case).
PUBLIC_PARAMSconstQuery parameters whose (plain) values are never secret (compared without case).

@liberta-labs/bazaar-keeper

import { Keeper, loadConfig, jobs } from "@liberta-labs/bazaar-keeper";

See The Keeper as a Library for how the pieces fit.

The Keeper Engine

ExportKindWhat it is
VERSIONconstThe keeper package’s version.
CATCH_UP_BLOCKSconstA sync step that starts this many blocks behind the head is a catch-up (after a restart or an outage): the print path waits for it, so it does not plan from an index still being replayed.
JobStatusEntryinterfaceOne job in the status file.
KeeperclassThe keeper: Keeper.create(config), start(), stop(), close(), on(event), and run for one-shot operations.
KeeperEventtypeThe name of a KeeperEvents event.
KeeperEventsinterfaceWhat Keeper.on delivers, by event.
KeeperListenertypeA listener for one KeeperEvents event.
KeeperOptionsinterfaceOptions of Keeper.create: loadWallets (false for a watch-only keeper).
KeeperStatusinterfacestatus.json, as the Python keeper writes it (the same keys), for bazaar keeper status.
MarketStatusEntryinterfaceOne market in the status file.
SignalclassA settable event: set, clear, and wait until set.
StopOptionsinterfaceOptions of Keeper.stop: whether to collect first, and the timeout.
listMarketsfunctionThe factory’s markets with their labels, without indexing anything (for setup and listings).
stateDirForfunctionWhere a keeper for this network and factory keeps its snapshot, ledger and status.

Configuration

ExportKindWhat it is
ConfigErrorclassA configuration problem, phrased for the person fixing it.
DEFAULT_CONFIGconstThe default config file name: bazaar-keeper.yaml.
SECRET_KEYSconstKeys whose values are secrets.
expandHomefunctionA path with a leading ~ expanded to the home directory.
loadConfigfunctionRead a config file, its sibling .env, and the environment.
parseConfigfunctionValidate an already-interpolated config object.
enabledJobsfunctionThe jobs switched on, by name.
priceEndpointsfunctionWhere the keeper reads prices: the stream URLs, the request API and the symbols registry prices.endpoint names, each replaced by prices.streamUrls, prices.restUrl or prices.symbolsUrl when set.
resolvedNetworkfunctionThe network a config names, with its preset applied: chain id, factory, start block, subgraph and whether official.
subgraphUrlfunctionThe subgraph URL a config resolves to, or null for none.
RpcConfigconst + typeThe rpc section’s zod schema and type.
SubgraphConfigconst + typeThe subgraph section’s zod schema and type.
PricesConfigconst + typeThe prices section’s zod schema and type.
WalletConfigconst + typeOne entry of wallets: its zod schema and type.
JobConfigconst + typeThe options every job shares: zod schema and type.
LiquidationJobconst + typeThe jobs.liquidation section’s zod schema and type.
TriggersJobconst + typeThe jobs.triggers section’s zod schema and type.
UnloadJobconst + typeThe jobs.unload section’s zod schema and type.
AdlJobconst + typeThe jobs.adl section’s zod schema and type.
RefreshJobconst + typeThe jobs.refresh section’s zod schema and type.
CollectJobconst + typeThe jobs.collect section’s zod schema and type.
TerminalSettlementJobconst + typeThe jobs.terminalSettlement section’s zod schema and type.
SweepExpiredJobconst + typeThe jobs.sweepExpired section’s zod schema and type.
JobsConfigconst + typeThe jobs section’s zod schema and type.
ProfitConfigconst + typeThe profit section’s zod schema and type.
GasConfigconst + typeThe gas section’s zod schema and type.
BudgetConfigconst + typeThe budget section’s zod schema and type.
SafetyConfigconst + typeThe safety section’s zod schema and type.
ALERT_KINDSconstThe alert kinds alerts.notify can name: lowBalance, jobPaused, endpointDown, opportunity, dailySummary, action.
AlertKindtypeOne of ALERT_KINDS.
AlertsConfigconst + typeThe alerts section’s zod schema and type.
StateConfigconst + typeThe state section’s zod schema and type.
LogConfigconst + typeThe log section’s zod schema and type.
EngineConfigconst + typeThe engine section’s zod schema and type.
KeeperConfigconst + typeThe whole keeper config’s zod schema and type.
JOB_NAMESconstThe jobs in the order the keeper runs and reports them, by their config key.
JobNametypeOne of JOB_NAMES.
ResolvedNetworkinterfaceWhat resolvedNetwork returns.

Wallets and Signers

ExportKindWhat it is
KEYS_DIRconstWhere bazaar wallet new puts keystores (expand with expandHome).
KeystoreV3interfaceA v3 JSON keystore.
LocalSignerclassSigns with a key held in this process.
RemoteSignerclassAny signer that answers eth_signTransaction over JSON-RPC (Web3Signer, a KMS bridge).
RemoteSignerOptionsinterfaceOptions of RemoteSigner: timeout and fetch.
SignerinterfaceSomething that signs keeper transactions: an address and sign(tx).
TxRequestinterfaceAn EIP-1559 (type 2) transaction, as the executor builds it.
WalletErrorclassA wallet that cannot be loaded or used (a wrong password, a bad key or phrase, a remote signer’s failure).
checkMnemonicfunctionThe phrase, normalized, after the checks eth-account makes: a known word count, every word from one language’s list, and a matching checksum.
decryptKeystorefunctionThe private key in a v3 keystore.
encryptKeystorefunctionA v3 keystore for key, with the Python keeper’s parameters and field order.
loadSignerfunctionThe signer for one configured wallet.
newKeyfunctionA new random private key.
writeKeystorefunctionEncrypt key to a JSON keystore at path (owner-only permissions where the OS has them); returns the address.

Execution, Ledger and Spend Policy

ExportKindWhat it is
ActionclassA call a job wants made: target, data, value, summary, locks, wallet and how it is paid.
ActionInitinterfaceWhat an Action is built from.
ActionResultclassWhat happened to an action: status, tx hash, gas, cost, reward, claimed, and the decoded error.
ActionResultInitinterfaceWhat an ActionResult is built from.
EmittypeHow the executor reports events (ExecutorEvents).
ExecutorclassSimulate, decide, send and track: the path every keeper action takes, with one nonce lane per wallet.
ExecutorEventsinterfaceWhat the executor reports: “alert” [kind, message], “sent” [action, txHash], “action” (a sent call’s result).
LaneclassOne wallet: its signer and its nonce sequence.
MutexclassA small FIFO mutex: acquire() returns nothing when the lock is free, so the free path never waits.
ResultStatustypeAn action’s outcome: confirmed, reverted, unknown, skipped or simulated.
RunOptionsinterfaceOptions of Executor.run: dryRun, force and the job’s config.
lockKeyfunctionOne key in the executor’s in-flight set, such as lockKey("liq", market.address, account).
DAYconst86,400 seconds.
EntryclassOne ledger line: a transaction the keeper sent, with its cost, reward and kind.
EntryInitinterfaceWhat an Entry is built from.
EntryKindtypeWhat an entry is: profit | loss | unpaid | collect | forward | manual | forced.
EntryStatustypeconfirmed, reverted or unknown.
LedgerclassThe earnings ledger (ledger.jsonl): every transaction sent, and the daily budgets read from it.
SummaryRowinterfaceOne row of the ledger’s summary: calls, reward, cost, net, claimed and reverted.
DecideOptionsinterfaceOptions of SpendPolicy.decide: whether the call is paid, an unpaid duty’s cap, and force.
DecisioninterfaceWhat SpendPolicy.decide returns: whether to send, the kind, and the reason.
DecisionKindtypeprofit | loss | unpaid | forced | skip, or a job’s own (collect, forward).
QuoteclassWhat a simulated call would earn and cost, in USD, and what it costs in wei.
SpendPolicyclassWhen a simulated call is worth sending: the profit rule, loss budgets and daily spend caps.

Jobs

The job classes are also on the jobs namespace (import { jobs } from "@liberta-labs/bazaar-keeper").

ExportKindWhat it is
ActionExtrastypeEverything an Action takes besides what Job.action fills in.
JOBSconstConfig key (camelCase, as JobsConfig names them) -> job class.
JobclassThe base class of a keeper job: its scope, cooldowns, the price it acts on, and plan (or planGlobal).
JobClasstypeThe constructor every job class has (the config is the job’s own schema type).
PricedCallclassThe price a planner judges by and the update payload its call carries.
jobs.AdlJobclassThe adl job.
jobs.ALL_STATUSESconstEvery market status (for a job that runs in all of them).
jobs.ActionExtrastypeEverything an Action takes besides what Job.action fills in.
jobs.JobclassThe base class of a keeper job: its scope, cooldowns, the price it acts on, and plan (or planGlobal).
jobs.JobClasstypeThe constructor every job class has (the config is the job’s own schema type).
jobs.LIVEconstThe statuses most jobs run in.
jobs.LIVE_OR_ADLconstLive, or with an ADL window open (matching halts; liquidation, ADL and refresh still run).
jobs.PricedCallclassThe price a planner judges by and the update payload its call carries.
jobs.monotonicconstSeconds on a monotonic clock, for cooldowns and schedules.
jobs.CollectJobclassThe collect job.
jobs.LiquidationJobclassThe liquidation job.
jobs.belowMaintenancefunctionWhether p is below its maintenance requirement at price and fundingIndex.
jobs.RefreshJobclassThe refresh job.
jobs.SweepExpiredJobclassThe sweepExpired job.
jobs.TerminalSettlementJobclassThe terminalSettlement job.
jobs.TriggersJobclassThe triggers job.
jobs.UnloadJobclassThe unload job.
jobs.JOBSconstConfig key (camelCase, as JobsConfig names them) -> job class.

Manual Operations

ExportKindWhat it is
AdlOptionsinterfaceOptions of keeper.run.executeAdl: the winners to close on each side.
CollectOptionsinterfaceOptions of keeper.run.collect: the markets to claim on.
FactoryOperationsclassThe factory’s permissionless operations: listings and identifier upgrades.
LiquidateOptionsinterfaceOptions of keeper.run.liquidate: the accounts to liquidate.
ManualOptionsinterfaceHow a manual operation goes.
OpOptionsinterfaceHow a one-shot run of an automatic job goes.
Operationsclasskeeper.run: every job once, on one market, and the manual operations.
SettleOptionsinterfaceOptions of keeper.run.settleTerminal: the accounts to settle.
SweepOptionsinterfaceOptions of keeper.run.sweepExpired: the orders to sweep.
TriggerOptionsinterfaceOptions of keeper.run.executeTriggers: the orders to fire.
OpportunityclassA manual operation someone could run: what, where (a market’s label, for people), why, and the CLI command that runs it (naming the market by its address, and only ids checked to be ids).
findOpportunitiesfunctionEvery manual operation that a dry run shows would go through now, or that a “too early” revert shows will open later.

Index: Store, Log Tail and Bootstrap

ExportKindWhat it is
EffectsclassWhat applying logs changed, for the engine to act on.
SNAPSHOT_VERSIONconstThe version of the keeper’s snapshot format (the Python keeper’s is 1; each ignores the other’s and bootstraps afresh).
StoreclassThe keeper’s local index: markets, open positions and live orders, kept current from logs.
handledPairEventsfunctionThe names of the pair events the store reacts to (for tests that check them against the ABI).
bootstrapfunctionLoad open positions and live orders as of block into the store, for the markets it holds, and return how many of each it loaded.
LogTailclassFollows the logs of the factory, the terminator and every market into a Store, handling reorgs and refused ranges.
REGROW_AFTERconstLog requests in a row that succeed at a reduced range before the tail tries one twice as wide.
REORG_REWINDconstBlocks the tail re-reads when the stored head’s hash no longer matches the chain.
TailDeploymentinterfaceThe contracts the tail follows besides the markets (the SDK’s Deployment fits).
TailLoggerinterfaceWhere the tail reports what it does.
refusedfunctionWhether the node answered and turned the request down, as providers do when a log query spans too many blocks or would return too many logs.

Logging and Alerts

ExportKindWhat it is
AlerterclassSends alerts to Telegram, Discord or a webhook, with repeats suppressed.
AlerterOptionsinterfaceOptions of Alerter: timeout and fetch.
SendOptionsinterfaceOptions of Alerter.send: repeatAfter.
LogFormattypepretty or json.
LogLeveltypedebug, info, warning or error.
LoggerinterfaceA named logger: debug, info, warning, error, exception and isEnabledFor.
formatMessagefunctionFill a %-template; returns the text and the exception argument, if any.
getLoggerfunctionThe logger with this name, created on first use.
setupfunctionConfigure every logger: the lowest level shown, and the output format.
setupLoggingfunctionConfigure every logger: the lowest level shown, and the output format.

CLI and Dev Tools

ExportKindWhat it is
runDoctorfunctionRun every check; true when nothing failed (warnings allowed).
runWizardfunctionAsk for the network, RPC, subgraph, price endpoint, wallet, jobs and markets, checking each answer, then write the config at configPath and a .env beside it.
MockProclassA Pyth Pro compatible price server for local chains (bazaar mock-prices): updates built by the SDK’s encoder, signed with the local signing key, stamped with the chain’s time; prices set, paused and resumed per feed.
MockProOptionsinterfaceWhat new MockPro takes: starting prices and symbols, the chain (or clock) to follow, the signing key, the default confidence, a token to require.
MockProServerinterfaceA running server: its url, streamUrl, host, port and close().
MockClockinterfaceThe time a MockPro stamps updates with.
MockUpdateinterfaceA signed update the mock built, and the feeds it carries.
MockUpdateSpecinterfaceWhat an update is asked to hold: its stamp, channel and properties.
MockFeedStateinterfaceOne feed as an update stamped at some instant carries it.
FeedReftypeA feed as the mock takes it: its Pyth Pro number, decimal digits, or the bytes32 that holds it.
FeedEntriestypeFeed -> value, as a record, a Map or entries.
feedNumberfunctionThe Pyth Pro feed number a FeedRef names.
startMockProfunctionServe a MockPro in the background (port 0 picks a free one); resolves once it listens.
serveMockProfunctionbazaar mock-prices: serve in the foreground until Ctrl-C (or SIGTERM).