Market-maker tools (v1)
HartiiLabs is building toward a market maker that quotes two-sided prices on its own tokens. v0
(shipped 2026-10-04) was the read-only foundation: a cross-venue price reference, a deterministic
quote-preview calculator, inventory-band math, and a FIFO P&L ledger. v1 (shipped 2026-10-05, tag
v1.7.0) adds the executor itself — a one-minute cron Worker (workers/mm-engine) that reads that
same math, decides at most one action per pair per run, and writes it to D1 — plus a risk guard,
a pause/kill switch, real fill ingestion, daily P&L snapshots, a creator depth-request flow, a pool
APR route, and live-reserve portfolio pricing.
What v1 is
- A price reference —
GET /api/token/:addr/referencedepth-weights a token's price across every venue it can read into onemid/low/highband with a confidence score. Unchanged from v0; see below. - A quote preview —
GET /api/mm/pairsstill computes a bid/ask preview against an always-empty inventory; it is a preview, not what the engine actually does with a funded vault. See Quote preview. - The executor Worker — a one-minute cron that builds live pair state (reference, reserves, vault balances when a vault is configured, on-chain pause state), decides an action, and records it — in dry-run only, today. See The executor.
- A risk guard and kill switch — hard-clamped pair-share, daily-loss, per-trade, and daily-action-count limits, plus a global and per-pair pause checked before every decision. See Risk guard and the kill switch.
- Alerts and a remote stop — the Worker pings the operator over ntfy and has a token-protected pause route (no chat bot, no Telegram). See Alerts and remote stop.
- Fill ingestion — confirmed/provisional HartiiSwap swap and LP activity, correlated through the router's self-forwarding call paths. See Fill ingestion.
- Daily P&L snapshots —
GET /api/mm/pnl/history?pair=serves immutable per-pair, per-UTC-day cumulative snapshots. See P&L history. - A written market-integrity policy — six rules in
src/data/mmRules.json. See Market-integrity rules. - A creator depth-request flow —
POST /api/mm/requests, EIP-191 signed, creator-only, one request per token. See Creator depth requests. - A pool APR route — honestly
null/—until seven days of verified swap history exist. See Pool APR. - Live-reserve portfolio pricing — every portfolio holding now carries a
priceSource. See Portfolio pricing. - The
/mmdashboard (v1) — still no navigation entry, still no wallet/transaction UI; owner controls are not on the page (the remote stop is a token-protected route, see Alerts and remote stop). Seven panels: Pairs, Positions, Actions, Fills, P&L, Alerts, Requested, plus Rules/Settings drawers. Every number links back to the API call that produced it; a missing engine endpoint shows as explicitly unavailable, never a fabricated zero.
What v1 is not
- No maker is quoting. There is no process, bot, or wallet placing real orders.
GET /api/mm/pairsstill carriespreview: trueandmaker: nullon every entry — constants, not fields that happen to be empty. - Nothing sends a transaction today. The executor exists and runs every minute, but both dry-run gates described above are closed on hartiilabs.com, so every decision it makes is recorded and discarded, never signed or broadcast.
- The remote stop is a pause, nothing more.
POST /api/mm-engine/admin/pause,resumeandclearonly flip the pause flags in D1; they cannot send a transaction, move funds or touch a key, and they answer 401 without the bearer token. The automatic risk-triggered pause (hitting a hard limit) works regardless — see Risk guard and the kill switch for the distinction. - A pair's
statusstays"planned"until an actual funded maker exists for it. The one registered pair today, QAXE/WQUAI, is"planned". - No vault is funded.
HARTII_LABS_MM_VAULTis unset on hartiilabs.com today; every position and every risk check that depends on a real balance reads back honestly zeroed/unknown instead of a fabricated number.
The pair registry
One pair is registered today, in src/data/mmPairs.json:
| Field | Value | Meaning |
|---|---|---|
pair | QAXE/WQUAI | Display name. |
token | 0x0035187a7660f595d93cd53a4d16c635d6cffc8f | The QAXE token address. |
depthTargetQuai | 25000 | Target two-sided depth, in QUAI — a quote preview's size per side is half of this (less on the heavier side when inventory is skewed). |
targetRatio | 0.5 | Target QUAI share of inventory value — 50/50. |
band | 0.15 | Allowed drift around the target before inventory bands flags a rebalance — ± 15 percentage points. |
maxTradeQuai | 160 | Per-pair cap on a single engine action, in QUAI. Equal to the engine's own global cap today (see Risk guard) — whichever is lower wins. |
limits.minSpreadBps | 40 | Floor on the quote preview's full bid-to-ask spread. |
limits.maxSpreadBps | 300 | Ceiling — a computed spread above this sets reasons: ["spread-too-wide"] and ok: false. |
limits.maxConfidenceBps | 400 | Ceiling on the reference's own confidenceBps — above this both the quote preview and the live engine refuse to act (confidence-too-wide). |
status | "planned" | No maker funded for this pair. |
GET /api/mm/pairs returns this exact row shape, enriched with a live reference, venues, and
quote — see the API reference for the full response and a real worked
example (including one where the preview correctly refuses to quote because confidence was too
wide).
How the reference mid is computed
functions/_lib/mm/referenceMath.js's computeReference takes a list of venues — each with a
priceWei (QUAI wei per whole token) and a depthQuaiWei — and produces one reference. This is
the same primitive both the /api/mm/pairs preview and the executor's live decision read from.
- Depth-weighted average.
midis the weighted mean of every venue with a known price, weighted bydepthQuaiWei. If every priced venue reports zero depth, it falls back to an equal weighting instead of dividing by zero. - Staleness widens the band, it doesn't move the mid. Each venue's price is allowed to drift
ageBlocks × 5 bps(configurable, capped at 5,000 bps) before contributing tolow/high—lowis the smallest lower bound across venues,highthe largest upper bound.confidenceBpsis the wider of(mid−low)/(high−mid)as a fraction ofmid. A venue with an explicitstalenessBpsuses that instead of computing one fromageBlocks. - Flags.
drift:<venue>when a venue's own price sits more than a configurable 100 bps frommid;thinwhen total depth across all priced venues is below a configurable 1,000 QUAI floor. The executor refuses to act on a reference flaggeddrift(reasonreference-drift), and on one whoseconfidenceBpsexceeds the pair'smaxConfidenceBps(reasonconfidence-too-wide) — see The executor.
Today there are two live venues per token (curve, hartiiswap) and two typed-but-always-null
placeholders (external, conversion) reserved for a future off-platform venue and a future
QUAI/Qi conversion leg — they carry zero weight until they have a real price to contribute.
Quote preview
functions/_lib/mm/quoter.js's quote() is a pure function: given a reference, an inventory
state, a volatility estimate, a depth target, and the pair's spread/confidence limits, it computes
a bid/ask preview — and nothing else. It never touches the network. GET /api/mm/pairs calls this
against an always-empty (quai: 0, token: 0) inventory — it is a preview of what a quote would
look like with a flat book, not what the executor actually does with a real position.
- Spread is
2 × max(minSpreadBps, poolFeeBps + ½·sigmaBps + ½·confidenceBps + ½·|skewBps|)— the pool fee, half the volatility estimate, half the reference's own confidence, and half the inventory skew all widen the spread, floored at the pair'sminSpreadBps. If the result exceedsmaxSpreadBps, or the reference'sconfidenceBpsexceedsmaxConfidenceBps, the preview adds a reason and setsok: false— it still returns the numbers (so you can see why it would refuse), it just tells you honestly that it would not actually quote this. - Skew comes from how far the inventory sits from its 50/50 ± band target (see next section), scaled to at most ± 100 bps, and shifts both sides of the quote in the same direction — a QUAI-heavy book quotes a higher bid and ask (encouraging buys of the token), a token-heavy book quotes lower (encouraging sells).
- Size is half of
depthTargetQuaiper side by default, reduced on the heavier side as skew grows (down to zero reduction at skew 0, more reduction as|skewBps|approaches its cap).
Inventory bands
functions/_lib/mm/inventory.js's inventoryState() marks a { quai, tokenQty } position to a
reference price and checks it against a target ratio and band — 50/50 ± 15% for the registered
pair. Outside the band it returns a rebalance: { side, amountQuai } — side: "buy" when QUAI is
over-weight, "sell" when the token is. GET /api/mm/positions marks this against a real vault
balance when one is configured (reads back empty/in-band when it isn't); the executor's own
buildPairState calls the same function on the same real balances and feeds its rebalance hint
straight into decideActions — see The executor. An empty wallet with no vault is
never reported as "balanced": ratio: null, inBand: false.
FIFO P&L
functions/_lib/mm/pnl.js's pnlFromFills() walks a list of fills in block order, opening a token
lot at its QUAI cost on every buy and consuming the oldest open lots first on every sell (strict
FIFO) to compute realisedQuai. Fees are tracked separately in feesQuai — netted out of
inventory, but never folded into the realised/unrealised figures, so the gross trading result and
the fee drag are always two distinct numbers. GET /api/mm/pnl runs this in-request over every
confirmed, non-provisional row in mm_fills; GET /api/mm/pnl/history?pair= serves the daily
snapshot table built from the same math — see P&L history. The ledger is empty
today: no vault is funded, so nothing has filled yet.
The executor
workers/mm-engine is a Cloudflare Worker, deployed, on a */1 * * * * (one-minute) cron
(workers/mm-engine/wrangler.toml), sharing the site's HARTII_LABS_DB D1 binding. Each run
(src/lib/cycle.js's runCycle):
- Acquires a single-flight lock (see below), builds each registered pair's live state
(
buildPairState: reference, HartiiSwap reserves, vault balances and LP share when a vault is configured, the vault's ownpaused()getter), and evaluates the risk guard against it. - Calls the pure
decideActions(functions/_lib/mm/engine.js) — the same decision boundary/api/mm/pairs's preview math is built from, but now fed real reserves/inventory instead of an empty book. It returns at most one action per pair per run:rebalance-buy,rebalance-sell,add-liquidity, or askipwith a reason (unfunded,pre-graduation,confidence-too-wide,reference-drift,risk-paused,vault-paused,venue-not-hartiiswap,no-action-needed, …). It never quotes against a pre-graduation curve and never considers a venue other than the discovered HartiiSwap WQUAI pair. - Checks for a pending-action guard: if this pair already has an action in
mm_actionswithstatus = 'pending'recorded in the last 10 minutes, this run's action is overridden to a skip (pending-action-under-10-minutes) regardless of what step 2 decided — this, plus "at most one action per pair per run," is the engine's idempotency guarantee. - Records the (possibly overridden) action to
mm_actionswithmode: 'dry'ormode: 'live'depending on the dry-run/vault gate, andstatus: 'planned'(dry) or'pending'(live, until the send resolves). - Only when both gates are open AND the action isn't a skip does it build a signer
(
AGENT_PRIVATE_KEYsecret) and send through the original v1 AgentVaultexecuteStepspath (the bot key signed onlyvault.execute; since 1.12.0 the engine instead signs directly from its signer with software caps - see the note at the top); gas is estimated on the read provider with an explicit buffered limit; the receipt is polled before the action is markedsuccess/failed/pending.
Single-flight cron lock. runCycle acquires a KV-based lock (HARTII_LABS_MM_LOCK, reused
directly from workers/agent-trader/src/lib/lock.js — best-effort, short TTL, not a true CAS)
before doing anything else, with a TTL just under one cron period (50 seconds). An overlapping fire
(the previous cycle still running when the next one starts) logs a warning and returns
{ ran: false, reason: 'locked' } without touching D1. No KV bound never blocks.
Profit-gated arbitrage (QAXE, Labs 1.11.0)
A pair can run the arb-round-trip strategy instead of the HartiiSwap-only liquidity lane. QAXE
does: almost all of its volume trades on its own graduated V1 curve pool, while the HartiiSwap
QAXE/WQUAI pair is a second, shallower venue. When the two prices diverge, the engine buys QAXE on the
cheaper venue and sells exactly the tokens it received on the dearer one — two transactions
(originally two vault.execute calls; direct from the signer since 1.12.0) in one cycle — so the profit is realised in QUAI and the vault never carries a
directional QAXE position.
- Size is the closed-form optimum of the two composed
x·y=kvenues (both venues' fees included: the curve's livefeeBps, HartiiSwap's 0.3%), clamped by the pair'smaxTradeQuai, the vault'smaxPerTxandremainingToday(), and 25% of the shallower pool's QUAI reserve. - The gate.
net = quoted proceeds − QUAI in − gas for every leg(live gas price × 1.2; per leg the higher of a measured floor and livequai_estimateGas× 1.15). It trades only whennet ≥ max(3 × gas, 5 QUAI). Otherwise it records askipwith reasonbelow-profit-gateand the numbers (direction, size, gross edge, gas, net, required). - What that means today. A round trip costs roughly 30 QUAI of gas at ~50k gwei, so the engine only trades on a large dislocation (or when gas falls). It is designed to sit idle rather than pay gas for an edge that is not there.
- Before signing it re-reads and re-quotes before the first leg, before any approval and before
the sell, and cross-checks its maths against the contracts' own
quoteBuy/quoteSell/getAmountsOut. If the edge disappears after the first leg it stops, keeps the tokens (valued at cost basis) and latchesarb-stranded-inventoryuntil/resume. - Limits: at most 10 actions a day, the 2% daily-loss latch (every mined transaction's gas counts, reverted legs included), one pending action per pair, slippage floors at the exact quote minus 0.5%, and it never trades while its vault holds LP in that pair.
- Signer (since 1.12.0): the QAXE lane trades directly from signer
0x002d7E47CA1FbfbfD1340BD6d1113Dac4D7fa7E9with software caps (800 QUAI per transaction, 1,500 QUAI per day) checked before every signature. It is a hot key that holds funds directly; nothing on chain caps it - the engine software does. The 1.11.1 AgentVault0x00392c13…2001was emptied and revoked. The engine runs in dry-run until a deliberate switch, so every decision is recorded publicly at/api/mm/actionsbefore any trade. - Reach (original vault design, pre-1.12.0): each cycle re-verified that the vault may call the curve (
tokenFactory().curveOf(token)must equal the curve) and the HartiiSwap router; otherwise it skips withvault-cannot-reach-curve/vault-cannot-reach-router.
Risk guard and the kill switch
functions/_lib/mm/risk.js's evaluate() is pure and checked before every decision, in this
order: global pause → per-pair pause → the vault's own on-chain paused() → unfunded → pair-share
limit → daily-loss limit → daily-action-count limit. Any failing check returns
{ pairPaused: true, reason }, which the engine folds into that pair's decision as a skip.
Hard-clamped limits (risk.js's exported constants — a caller-supplied override can only tighten
these, never loosen them):
| Constant | Value | Checked against |
|---|---|---|
MAX_PAIR_SHARE_BPS | 3,000 (30%) | This pair's exposure (wallet inventory + LP share) as a fraction of total MM inventory across every pair. |
MAX_DAILY_LOSS_BPS | 200 (2%) | Today's realised P&L (net of fees) as a loss against the pair's UTC-day starting inventory value. |
MAX_ACTIONS_PER_DAY | 1,000 | Count of this pair's planned/success actions since UTC midnight. |
MAX_ENGINE_TRADE_QUAI_WEI (functions/_lib/mm/engine.js) | 160 QUAI | The single largest amount any one action can move — the lower of this and the pair's own maxTradeQuai (also 160 for QAXE/WQUAI today, so they're currently identical). |
Pause / kill switch, global and per pair. State lives in D1 (mm_state's global_paused and
pair_paused keys, read/written by functions/_lib/mm/store.js). Two ways a pair ends up paused:
- Automatic (live today, independent of the remote stop). Hitting
pair-share-limit,daily-loss-limit,daily-action-limit, or the vault's ownvault-pausedstate latches that reason intopair_paused[pair]on the nextrunCycle— it stays latched (re-checked and re-applied every run) until explicitly cleared. - Manual, via the remote stop.
POST /api/mm-engine/admin/pause(optionally with{"pair":"QAXE/WQUAI"}) writes the sameglobal_paused/pair_pausedstate; a pair paused this way carries the reasonadmin-pause.resumelifts it andclearremoves every pause and latch. See Alerts and remote stop.
A paused pair's next decideActions call always short-circuits to a skip (risk-paused /
vault-paused) before it ever reaches the trade-sizing logic — the guard is checked first, every
run, not just at startup.
Alerts and remote stop
There is no chat bot and no Telegram path in the Worker (removed in Labs 1.23.0). The operator is told over ntfy and stops the engine with a token-protected route.
Alerts (ntfy). The Worker pings the operator when a pair newly latches, when an execution ends failed, partial or pending, when a signing lease is held, and when the live self-test fails. A once-a-day digest goes out at 08:00 UTC and is only marked as sent after ntfy acknowledges it. Every fifth minute the cron also checks that the indexer is still moving and pings if it has not for 30 minutes.
Remote stop. POST /api/mm-engine/admin/pause, /admin/resume and /admin/clear, each with
Authorization: Bearer <token> and an optional JSON body {"pair":"QAXE/WQUAI"}. The token is compared in
constant time, and a missing or wrong token gets 401. The route only changes the pause flags in D1 (global, or
per pair); it cannot send a transaction, move funds or read a key. clear removes every pause and latch, so it
is for after a human has reviewed why the engine stopped.
Fill ingestion
A fill reaches mm_fills one of two ways, both keyed uniquely by (tx_hash, log_index):
- The Worker's own live send (not reachable today — see the dry-run gate above). When a live
action's transaction lands,
cycle.js'sexecuteOnedecodes that one receipt's logs withfunctions/_lib/mm/swapDecode.js'sdecodeHartiiSwapReceiptand writes the result withprovisional: 1. - The site's indexer, independently of the Worker — it re-derives each configured pair's
HartiiSwap WQUAI pool, scans vault-related Swap/Mint/Burn activity plus LP Transfer correlation,
and writes confirmed rows (
provisional: 0). A Worker-written provisional row is reconciled (confirmed, or removed if the indexer's receipt check shows it was dropped by a reorg) by this same pass.
Why correlation, not just sender/to. HartiiSwapRouter self-forwards on several paths —
swapExactTokensForETH/swapTokensForExactETH (any vault sell to native QUAI) and
removeLiquidityETH call the pair's _swap/burn with to = address(this) so the router can
unwrap WQUAI before paying the vault, and a Mint log has no to topic at all. On every one of
those, the pair's own Swap/Mint/Burn log names the router, never the vault, as sender/to — not
an edge case, the normal shape for those calls. decodeHartiiSwapLog only accepts one of these
when the same transaction also carries an ERC-20 Transfer that actually moved the swapped/
pooled asset into or out of the vault (vaultTouchedByTransfer) — correlation evidence, not an
assumption about log shape.
mm_fills' uniqueness is (tx_hash, log_index) — migrated 2026-10-05 from a legacy tx_hash-only
constraint that a live insert would otherwise have failed against; the migration self-heals the
live table on ensureSchema's first run with no row loss. GET /api/mm/pnl only ever sums
confirmed (provisional = 0) rows.
With no vault funded today, there is no vault activity for either path to pick up — mm_fills is
genuinely empty.
P&L history
GET /api/mm/pnl/history?pair=<pair> reads mm_pnl_daily, written by the site's indexer run
(functions/api/indexer-run.js's snapshot pass, immutable per pair/UTC day) — up to 365 rows,
newest first:
{ "pair": "QAXE/WQUAI", "items": [
{ "date": "2026-10-05", "pair": "QAXE/WQUAI", "realisedQuai": "0", "unrealisedQuai": "0",
"feesQuai": "0", "inventoryQuaiValue": "0" }
], "limit": 365, "at": "2026-10-05T12:00:00.000Z", "version": 1 }Market-integrity rules
src/data/mmRules.json is the published policy — six rules, shown verbatim on the /mm dashboard
and mirrored here:
| Rule | Title | What it says |
|---|---|---|
self-match | No self-matching | The maker must never trade against itself or create artificial volume. |
graduation | Graduated pools only | Never quote against a pre-graduation bonding curve. |
real-depth | Real on-chain positions | Every live quote must be backed by a real on-chain position. Preview numbers are not posted liquidity. |
transparency | Public maker attribution | Market-maker fills must be tagged in the public feed. |
caps | Spending caps | The engine software enforces the configured spending caps before it signs (direct-EOA, no AgentVault). The page cannot change them. |
kill-switch | One-block kill switch | The kill switch must land in one block. This page reports engine state; it cannot guarantee inclusion or submit the switch. Owner actions happen through a token-protected remote stop, with alerts over ntfy. |
Creator depth requests
A token's creator can ask HartiiLabs to consider making a market in their pool:
POST /api/mm/requests with { token, pair, note, ts, wallet, signature }.
token/pairmust be0x+ 40-hex, nonzero;pairis the pool contract address, not a display name;note≤ 500 characters.- Signed message:
`hartiilabs:mm-request:v1:` + JSON.stringify([9, token.toLowerCase(), pair.toLowerCase(), note, ts])—9is Quai's chain id, baked into the signed payload so a signature can't be replayed on another chain. tsmust be no more than 60 seconds in the future and no more than 10 minutes in the past of the server clock (closes the replay window).- Creator-only: the recovered signer must equal
wallet, andwalletmust equal the token's on-chain-indexedcreator— not merely a valid signature from any wallet. - One request per token: the insert is
INSERT OR IGNOREontoken— a repeat request for the same token is idempotent and can never reset an operator'saccepted/declineddecision.statusstarts"requested"; changing it is an operator action with no public route. - Rate limit: 10 requests/minute per IP.
- Errors:
400(validation, or an expired/future timestamp),401(bad or mismatched signature),403(wallet isn't the indexed creator),404(token not indexed),429(rate limited). GET /api/mm/requests?token=0x…reads one token's status;GET /api/mm/requests(no param) lists newest-first, 100 rows per page, withhasMore/nextOffset.
This is a signature, never a transaction — no gas, no approval, no calldata.
Pool APR
GET /api/pool/:pair/apr verifies the given address is a real HartiiSwap WQUAI pool (checks its
live factory() against the known HartiiSwap factory, and that the factory's own getPair agrees)
and reads its live two-sided QUAI TVL. The formula (functions/_lib/poolApr.js):
feeAprBps = (7-day volume × 25/10000) / TVL × 365/7all in BigInt, bps as D1 TEXT. This checkout has no persisted HartiiSwap Swap-event history or
coverage cursor, so the route is honest about it rather than guessing from the token's
bonding-curve volume (a different, unrelated number): it returns feeAprBps: null,
coverageSeconds: 0, complete: false, and a reason explaining fewer than seven verified days
of swap data exist yet. The dashboard renders this as "—", not a zero or a stale estimate. A
graduated V4 curve's separate LP-reserve reward stream (lpReserve, when present) is explicitly
labelled appliesTo: 'curve-lp-only' — it is not an APR on this HartiiSwap pool and external
HartiiSwap LPs don't qualify for it.
Portfolio pricing
functions/_lib/portfolioPrices.js's readPortfolioPrice now marks graduated/Quainance holdings
from live on-chain reserves instead of only the last indexed trade, and every holding on
GET /api/portfolio/:wallet carries a priceSource:
priceSource | When | Notes |
|---|---|---|
live-reserve-reference | Graduated native HartiiLabs token | Reads GET /api/token/:addr/reference's midWei; priceAt carries the reference's own timestamp. |
quainance-pool-reserves | Quainance-launched token | Reads the Quainance router's discovered WQUAI pair reserves directly; pricePool names the pool. |
indexed-last-trade | Pre-graduation native token | Unchanged from before — the token's last indexed trade price. |
unavailable | Any RPC/read failure | Never substitutes a stale trade price for a failed live read. |
Pricing is bounded to at most 6 holdings in flight at once (mapWithLimit, PRICE_FANOUT_LIMIT),
with the Quainance router's factory()/WETH() statics memoised per isolate for 1 hour and a
discovered WQUAI pair memoised per token for 24 hours — a 20-holding wallet on a cold cache no
longer fires ~120–160 concurrent quai_calls.
Related
- API reference › Market-maker tools — exact request/response shapes, caching, and error cases for every route mentioned above.
- Pricing a token — the underlying curve/pool spot-price math the reference endpoint reads from.
- How the indexer works — the money-math rules (
TEXTwei columns,BigInt-only arithmetic) this feature follows, and where fill confirmation happens. - Versions & changelog — the 1.4.0 (v0) and 1.7.0 (v1) entries this feature shipped under.