feat(indexer): bot-grade book snapshots, discovery, streams and keyed read budgets #1580
Labels
No labels
agent:fix_bugfix
agent:fix_conflicts
agent:fix_security
agent:gap_analysis
agent:implement
agent:implement
agent:implement
agent:open_issues
agent:ready
agent:research
agent:security_audit
agent:verify
architecture
backend
blocker:hybrid
blocker:launch
blocker:limit-orders
blocker:v2
block:log_only
block:security
bug
ci
contracts
correctness
deploy
dev
devops
docs
documentation
duplicate
e2e
enhancement
epic
feature
frontend
functional-completion
gas
good first issue
governance
help wanted
high-risk
hooks
hybrid
indexer
infra
infrastructure
integrators
invalid
launch-blocker
limit-orders
localnet
localterra
low priority
missing-implementation
needs-design
ops
performance
priority
high
priority
medium
product
qa
QA
question
ready
ready
research
scripts
security
security-hardening
smartcontracts
tech-debt
testing
ux
UX
v2
verification
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
code/cl8y-dex-terraclassic#1580
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
External trading bots (market makers, cross-venue arbitrage, Hummingbot-class connectors) need a read surface that is cheap for the indexer, honest about freshness, and stable enough to build a maintained connector against. Today the only bot-usable book endpoints proxy on-chain LCD walks: each page costs
1 + Nsmart queries, they are capped atRATE_LIMIT_LCD_HEAVY_RPS(10 rps per socket peer IP in production), and they cannot supply the ≥100-level depth or push streams that the Hummingbot spot-connector standard expects.The indexer already maintains an LCD-free mirror of pool reserves and the resting limit book for the route solver, but that mirror is not exposed to anyone. This issue bundles the DEX-side read plane for bots:
It is a prerequisite for the two connector issues it will be cross-linked with, and it changes no contract behavior, quote math, or existing endpoint contract.
Community request (anonymized)
A community request asked whether a Hummingbot connector is worth building for CL8Y DEX, reasoning that strategy/bot flow already reaches major centralized venues, that bots only need a discoverable, tradable and profitable market, and that this would widen reach without a marketing programme.
This issue covers only the DEX read surface those connectors need. Do not retain or reproduce handles, timestamps, quotations, or any user-identifying information from that request in this issue, code, docs, tests or fixtures.
Current codebase
Routes and rate layers
indexer/src/api/mod.rswires the LCD-heavy router:order-book-head,limit-book-shallow,limit-book,limit-book/insert-hints,route/solve,route/solve/best,route/solve/progress,compliance/blacklist-check,cg/orderbook,cmc/orderbook/*. It appliesrequire_quote_chain(chain-attestation gate) andapply_rate_limit_layer(.., config.rate_limit_lcd_heavy_rps).indexer/src/config.rs:RUN_MODE=prodforcesRATE_LIMIT_RPS=60andRATE_LIMIT_LCD_HEAVY_RPS=10when unset/zero (prod_forces_nonzero_rate_limits_when_zero). Dev dual-zero is refused on a non-loopback bind unlessALLOW_ZERO_RATE_LIMITS=1.indexer/src/security.rskeys the governor on the socket peer IP (PeerIpKeyExtractor); noX-Forwarded-For/CF-Connecting-IPtrust. Listener is IPv4-only by default (API_IPV6_ENABLED).Retry-After+x-ratelimit-*; quote paths addCache-Control: no-storeviaindexer/src/api/quote_cache_control.rs.LCD-proxy book (expensive, paginated)
GET /api/v1/pairs/{addr}/limit-book?side=&limit=&after_order_id=— default 50, max 100 rows, one page ≈1 + NLCD smart queries.GET /api/v1/pairs/{addr}/order-book-head,.../limit-book-shallow(default 10, max 20),.../limit-book/insert-hints(≤100 prices, one walk).docs/limit-orders.md§ Indexer limit book (LCD proxy) anddocs/integrators.md.LCD-free mirror (exists, unexposed)
indexer/src/indexer/book_snapshot.rsruns everyBOOK_SNAPSHOT_INTERVAL_MS(10 000 ms) and upserts:resting_limit_orders(order_id,side,price,remaining,owner,expires_at,block_height,snapshot_at,walk_index) — wholesale replace per pair,walk_indexpreserves on-chain FIFO afterUpdateLimitOrderPrice(L23 / #1227).pair_reserves/hybrid_pair_reserves(reserve_0,reserve_1,fee_bpswith-1= unobserved,block_height,snapshot_at) — independent generations since #1453.BOOK_SNAPSHOT_STALENESS_TOLERANCE_CYCLES = 2,BOOK_SNAPSHOT_MAX_STALENESS_MS = 20_000;AppState.book_snapshot_max_staleness_ms.indexer/src/api/db_orderbook_sim.rs(MirrorLoadMeta { db_hybrid_queries, lcd_fallback_queries, mirror_stale_hops, mirror_missing_hops, max_snapshot_age_ms }) and the solver only. No HTTP route exposes the mirror.Bot-shaped reads that already exist (DB-backed)
GET /api/v1/pairs,/{addr},/{addr}/stats,/{addr}/tradesGET /api/v1/pairs/{addr}/limit-placements|limit-cancellations|limit-fills,/{addr}/limit-orders/{order_id}/fillsGET /api/v1/traders/{addr}/limit-placements|limit-cancellations|limit-fills|trades|positionsGET /api/v1/tokens,/{addr},/{addr}/pairsGET /api/v1/route/solve— already zero-LCD (local_v1), returnshops,router_operations,estimated_amount_out_net,optimality_scope,snapshot_age_ms,snapshot_block_height,quote_kind.GET /api/v1/health,/ready,/ready-api,GET /api/v1/health/fee-discount.Missing pieces (the gap)
indexer/Cargo.tomlhas no WebSocket/SSE dependency.snapshot_age_ms).Why
limit-bookcalls/s, each costing1 + depthLCD queries, against a 10 rps per-IP cap. That is both an LCD-amplification risk and a guaranteed 429 for legitimate bots (and for retail behind the same NAT).Constraints and guardrails
lcd_*queries. Enforce with a test that asserts an LCD mock receives zero calls on these routes.snapshot_at,age_ms,block_height,staleandsource. Unknown ≠ empty: a missing/stale reserves row must be distinguishable from "no resting orders". Astale: truesnapshot is advisory only and must never be presented as tradeable depth.remainingis the on-chain post-maker-fee escrow;priceis raw token1-per-token0 (Decimalatomics). Document the basis and decimals next to the field. Do not humanise, invert, or compute USD in this endpoint.owneris already public on-chain; do not add trader tiers, balances, IPs, or any other actor data. No hashing scheme that pretends to anonymise a public chain address.limit-book*contracts, caps and rate buckets unchanged. Migrations must be additive and indexed; no new required env var (defaults only); Coolify single-container deploy must keep working.Cache-Control: no-store(they are chain state, not static).ETag/304is allowed only when derived from a server-computed generation (snapshot_at+block_height) — never from a client-supplied value.SKIP; executed failures remainFAIL.RUN_MODE=prodforced limits remain; no new public unauthenticated mutation surface;/metricsis still not exposed (observability istracingper #200).Relevant files
indexer/src/api/mod.rs,indexer/src/config.rs,indexer/src/security.rs,indexer/src/startup.rsindexer/src/indexer/book_snapshot.rs,indexer/src/db/queries/resting_orders.rs,indexer/src/db/queries/pair_reserves.rs,indexer/src/api/db_orderbook_sim.rsindexer/src/api/pairs.rs,indexer/src/api/tokens.rs,indexer/src/api/traders.rs,indexer/src/db/queries/limit_order_fills.rsindexer/src/api/quote_cache_control.rs,docs/runbooks/chain-attestation.mdindexer/migrations/docs/indexer-http.md,docs/indexer-invariants.md,docs/limit-orders.md,docs/integrators.md,docs/runbooks/book-snapshot-mirror.md, OpenAPI annotations inapi/*.rssmartcontracts/packages/dex-common/src/pair.rs,smartcontracts/packages/dex-common/src/limit_placement.rsindexer/tests/api_limit_book_deep.rs,indexer/tests/book_snapshot_loop.rs,indexer/tests/db_orderbook_mirror.rs,indexer/tests/api_route_solve.rsRecommended direction
Phase 1 — cached L2 snapshot
GET /api/v1/pairs/{addr}/book/snapshot?depth_bids=100&depth_asks=100depth_truncatedrather than silent truncation.stale: truewith the last good snapshot.ETagfrom(snapshot_at, block_height, depth); supportIf-None-Match→304.Phase 2 — venue manifest + discovery (one call)
GET /api/v1/markets(paginated, stable sort by pair id):chain_id(columbus-5),gas_price_uluna(28.325),router,factory,fee_discount_registry,treasury— from indexer config/env, never hardcoded in clients.pair,base/quotetoken address, symbol, decimals,fee_bps,effective_fee_note,price_band_min/max(human 1e-9…1e9),min_place_remaining_raw(10),max_batch_rungs(pair query, cached from indexer),max_adjust_steps_cap(256),max_maker_fills_cap(100),paused,blacklisted,code_id_frozen,hook_addresses,indexed_at,snapshot_at.nullwith a reason string, neverfalse.Phase 3 — streaming
GET /api/v1/stream/book?pairs=<csv>&depth=100(SSE first; a WebSocket wrapper is optional if upstream review requires it). Events:snapshot(initial),update(pair, generation, block height, changed levels),heartbeat.id:= monotonic generation forLast-Event-IDresume within a bounded replay window; gap beyond the window → newsnapshotand a client-visibleresyncflag.POST /api/v1/auth/challenge→ short-lived nonce;POST /api/v1/auth/verifywith a canonical, domain-separated signed message (chain-id + host + nonce + expiry) → short-lived read token.GET /api/v1/stream/trader/{addr}with that token: order placements, fills, cancellations, parks (reason), claims — only for the authenticated address. Anonymous access to this stream is refused (public chain history remains available through existing REST).Phase 4 — keyed budgets
X-API-Key(hashed at rest) mapped to{rps, burst, max_streams, depth_cap}; admin-managed outside the request path (env file or SQL, operator-run script; no HTTP admin route in this issue).Retry-After; keys never bypass per-IP anonymous caps. Document anonymous caps as the default contract.Phase 5 — contract, docs, verification
schema_version), document freshness/stalesemantics, publish it indocs/indexer-http.md, add OpenAPI (utoipa), add askills/AGENTS_BOT_MARKET_DATA.mdplaybook with invariants, adocs/qa/issue-<n>/README.mdchecklist, andmake verify-issue-<n>.Given / When / Then
Given the indexer mirror is fresh for pair P and the LCD is unreachable,
When a bot calls
GET /api/v1/pairs/P/book/snapshot?depth_bids=100andGET /api/v1/markets,Then both answers come from Postgres with zero LCD queries, carry
snapshot_at/age_ms/block_height/stale, and the depth ordering matches on-chain FIFO (walk_index, notorder_id).Given the mirror is older than the configured staleness budget,
When the bot requests the snapshot or a book stream,
Then the response is explicitly
stale: true(REST) or emitsresync(stream) and never presents the data as current, and the bot-side guard can refuse to trade.Given a market is paused, blacklisted, or its code id is frozen,
When the bot reads
/api/v1/markets,Then the flag is present and truthful, and an unreadable flag is
nullwith a reason rather than a falsefalse.Acceptance criteria
GET /api/v1/pairs/{addr}/book/snapshotserves bids/asks fromresting_limit_ordersinwalk_indexorder, includes reserves/fee/freshness, honours depth caps, and performs zero LCD queries (asserted by test).staleis set fromBOOK_SNAPSHOT_MAX_STALENESS_MS(boundary tested on both sides).ETag/304works and cannot be forced by client input;Cache-Control: no-storeis set on all new dynamic routes.GET /api/v1/marketsreturns chain/venue manifest plus per-market decimals, fee, price band, min remainder, rung/step/maker-fill caps, paused/blacklist/frozen flags, andsnapshot_at; pagination is stable and bounded.GET /api/v1/stream/bookdelivers initial depth ≥100 per pair, ordered updates with generation/height, heartbeat,Last-Event-IDresume, and an explicitresyncwhen resume is impossible.POST /api/v1/auth/challenge+ verify yields a short-lived read token; signature is domain-separated (chain-id + host + nonce + expiry), single-use, replay-rejected; a token only authorises its own address.GET /api/v1/stream/trader/{addr}delivers placements/fills/cancels/parks/claims for that address only, with no cross-address leakage, and refuses unauthenticated access.Retry-After; no key value appears in logs, traces, errors, or URLs.limit-book*,route/solve*,/pairs,/traders/*) are byte-compatible and keep their rate buckets; regression suites pass unchanged.docs/indexer-http.md+docs/integrators.mddescribe freshness, caps, and the mirror-vs-LCD distinction.make verify-issue-<n>exists and passes;docs/qa/issue-<n>/README.mdchecklist andskills/AGENTS_BOT_MARKET_DATA.mdare present with invariants MD1–MD10.Test plan — all paths
walk_indexorder, bids/asks separateddepth=0, negative, float, exponent, string, huge (1e9)depth_truncatedfor oversize; never allocate unboundedreserves: null+stalesemantics / `bidsfee_bps = -1(unobserved)fee_bps_observed: false, never0lcd_calls == 0stale:falsethenstale:trueETagchanges;If-None-Matchold value → 200 with new body, current value → 304/marketswith paused, blacklisted, frozen, listing-excluded, missing-metadata pairsnull+ reason; excluded pairs follow existing policy/marketspagination at boundaries (first, last, beyond end)walk_indexorderLast-Event-IDwithin window / beyond window / unknown idresync+ fresh snapshot /resyncRetry-After; keyed budget honoured; revoked → anonymous capslimit-book*,route/solve*,/pairs,/traders/*RUN_MODE=prod, missing optional envAdversarial test plan — attack, hack, abuse
depth=999999999, deep pagination, comma-bombpairs=, duplicate pairsdepth_truncated; no OOMX-Forwarded-For/CF-Connecting-IP, rotating IPv6, key header guessingIf-None-Match,Last-Event-ID, or clock-skew to pin stale data as freshresync; client clocks never trustedno-storeon dynamic/private routes;Varywhere relevant; private stream never cacheablestaleand trades on frozen depthdocs/supply-chain-security.md)Verification criteria
make verify-issue-<n>runs:cargo fmt --check,cargo clippy -- -D warnings, unit tests, Postgres integration tests (T5–T9, T14–T18), stream/auth tests (T10–T13), the zero-LCD assertion (T5/A1), OpenAPI/documentation link checks, and a schema contract diff.make test-indexer-integration(or the subset documented in the checklist) passes with a disposable DB perdocs/runbooks/indexer-database-isolation.md.docs/qa/issue-<n>/README.mdrecords each acceptance criterion as PASS / FAIL / SKIP with the exact command and result. Unavailable live checks are explicit SKIP and do not close acceptance; executed failures stay FAIL.curl -s https://indexer.dex.cl8y.com/api/v1/markets | jq …, snapshot curl for one pair, one SSE capture with--max-time, with UTC timestamps and the served git SHA (/healthgit_sha).lcd_calls == 0./readyand/ready-apistill truthful.Out of scope
https://bridge.cl8y.com).Deliverables
indexer/tests/api_book_snapshot.rs,api_markets.rs,api_stream_book.rs,api_stream_trader_auth.rs,api_read_keys.rs(or equivalent), plus contract/schema fixtures.docs/indexer-http.md+docs/integrators.md+docs/runbooks/bot-market-data.md; OpenAPI annotations.skills/AGENTS_BOT_MARKET_DATA.mdwith invariants MD1–MD10;docs/qa/issue-<n>/README.md;make verify-issue-<n>;scripts/verify-issue-<n>.sh.First-pass model recommendation
Recommendation: a high-capability coding model with Postgres + Rust/Axum experience. The risky parts are the freshness/
unknown≠emptycontract, streaming backpressure, and auth/replay handling; a wrong default there silently becomes a bot that trades on stale or fabricated depth.Dependent connector issues: (#1581) Hummingbot spot connector and (#1582) Hummingbot Gateway Terra Classic chain + CL8Y router/AMM connector.
Phase 1 (book snapshot) and Phase 2 (
/markets) unblock the spot connector's degraded-but-safe path. Phase 3 (book stream at depth >= 100 and the authenticated per-wallet order/fill stream) satisfies the two Hummingbot channels that no current endpoint can provide.