feat(integrations): Hummingbot spot connector for CL8Y limit book and hybrid swaps #1581

Open
opened 2026-10-29 00:31:36 +00:00 by PlasticDigits · 0 comments
Owner

Summary

Build and maintain an open-source Hummingbot spot connector for CL8Y DEX so strategy bots can market-make on the on-chain limit book and take liquidity through the hybrid route solver without writing chain code. A Hummingbot connector is the lowest-friction, no-marketing distribution channel available to this venue: bots already hunt for discoverable, profitable markets and do not care that the settlement asset is LUNC.

This issues bundles the whole connector deliverable: connector package (market data, balances, orders, fills, fees), the Terra Classic signing/execution layer the connector needs, self-trade and spend guardrails, a LocalTerra-based conformance harness, and the upstream contribution path.

It consumes the DEX read plane from the sibling market-data issue (#1580: cached book snapshot, /markets discovery, book + per-wallet streams). The connector must still work, degraded but safe, if those streams are unavailable. Gateway-mediated swaps/LP are tracked separately in #1582.

Community request (anonymized)

A community request asked whether a Hummingbot connector is worth building for CL8Y DEX, reasoning that bot/strategy flow already reaches major centralized venues, that bots only need a discoverable, tradable and profitable market, and that the connector (open source) would widen reach without marketing spend.

Do not retain or reproduce handles, timestamps, quotations, or any user-identifying information from that request in this issue, code, docs, tests, fixtures, commit messages, or connector logs.

Current codebase

What exists

  • On-chain venue: Terra Classic (columbus-5) CosmWasm DEX. Pair contract supports pool swaps, hybrid pool+book swaps, greedy book-first swaps, resting FIFO limit orders (place batch/ladder, cancel batch, reprice, expiry/claim, permissionless clean), router multi-hop execution, community-tax CW20s, and CL8Y fee-discount tiers. Message shapes and invariants: docs/limit-orders.md, docs/integrators.md, smartcontracts/packages/dex-common/src/pair.rs.
  • Read API: indexer REST at indexer.dex.cl8y.com (prod) / 127.0.0.1:3001 (dev). Book via LCD-proxy endpoints; route solving is zero-LCD (local_v1) and returns hops + router_operations + estimated_amount_out_net + snapshot_age_ms. See docs/indexer-http.md.
  • Fills/order history: GET /api/v1/pairs/{addr}/limit-fills, .../limit-orders/{order_id}/fills, .../limit-placements|limit-cancellations, and trader-scoped equivalents.
  • In-repo bots (not a connector): scripts/bots/swarm.py / swarm_tax.py build CW20 Send + pair hook messages and shell out to docker exec … terrad tx … on LocalTerra. packages/localnet-trading-swarm is a TypeScript LocalTerra-only swarm. Neither holds keys safely for mainnet nor implements order lifecycle reconciliation.
  • Python signing library available: terra-classic-sdk (PyPI, 3.0.2, >=3.10,<4) supports Terra Classic LCD/key management/signing including the 0.47 chain upgrade.
  • Hummingbot upstream: ~28 CEX spot connectors under hummingbot/connector/exchange/*; no Terra/Terra Classic connector today. Gateway (the DEX path) supports only ethereum and solana chains, so a Gateway route is not available without a new chain implementation (separate sibling issue).
  • Hummingbot connector standard (hummingbot.org/connectors/): required public REST (active markets, last price, order book snapshot, ping, trading rules), required private REST (balance, order status, open orders, create/cancel), required public book channel with minimum depth 100, required private user order/trade channel, documented rate limits, and an auth class. A connector must live in hummingbot/connector/exchange/<name>/ with a matching test folder, docs PR to hummingbot-site, and an HGP for upstream inclusion.
  • Chain economics: columbus-5 gas floor 28.325 uluna/gas (docs/runbooks/mainnet-soft-launch.md); place/cancel/reprice/hybrid gas envelopes are derived from signed message shape (skills/AGENTS_HYBRID_LIMIT_GAS.md, skills/AGENTS_TERRACLASSIC_GAS.md).

Gaps

  • No connector, no maintained Python client, no documented placement/reconciliation state machine for external bots, no self-trade protection guidance, no fee-aware sizing helper, no LocalTerra conformance suite for third-party bot authors, no upstream documentation/HGP artefacts.

Why

  • Distribution without marketing. Hummingbot users run pure_market_making, avellaneda_market_making, cross_exchange_market_making and arbitrage strategies against any connector that passes their standard. A maintained connector makes CL8Y a selectable venue.
  • Market quality. Market makers tighten the book; arbitrage bots close pool/book and cross-venue gaps; both need reliable order lifecycle semantics rather than ad-hoc scripts.
  • Correctness and safety. A naive bot can double-place after a timeout, cross its own resting orders, misprice by decimals, or size gas from a stale quote. The connector is where those defects must be impossible, not where they are documented as caveats.
  • Fee revenue is already modelled. Maker placement and taker fills pay the treasury; a connector that models the maker/taker split and CL8Y tier discounts keeps bot P&L honest and makes the venue attractive to professional makers.

Constraints and guardrails

  1. Keys never leave the host and never reach logs. Mnemonic/private key comes from Hummingbot's encrypted config or an explicit local file with 0600 permissions; refuse to start otherwise. Redact key material, signed bytes, and full tx payloads. No telemetry, no remote signing, no key in env printed by --help/status.
  2. Chain identity is verified before signing. On startup, assert LCD/RPC reports columbus-5 (and the expected bech32 prefix cosmos); refuse to trade on mismatch. Never sign a tx whose chain_id came from an unverified source.
  3. order_id binding is explicit. CL8Y assigns order_id on-chain; it appears only in wasm events (limit_order_placed, order_id) of the placement tx. The connector must bind client_order_id → order_id by parsing the committed tx response. On ambiguous broadcast (timeout/unknown), look up the placement by tx hash (indexer limit-placements / LCD tx events) before re-signing. Blind retry after an ambiguous send is a fund-loss defect.
  4. Sequence safety. Cache account number/sequence per wallet, single-flight all signing, refresh on code 32 (sequence mismatch) with bounded retries, and halt with a clear error when another process appears to share the key.
  5. Quote/execute agreement. Market (taker) orders must execute exactly the route that was quoted: re-validate the quote's freshness (snapshot_age_ms under a configured bound), refuse degraded quote kinds, and set min_return from estimated_amount_out_net minus configured slippage. Gas comes from the documented message-shape envelopes; no flat 15M default, no query-string gas.
  6. No book trade on stale or unknown depth. If the book snapshot is stale/missing or the market flags are unknown, the maker strategy must pause rather than place.
  7. Self-trade prevention. Configurable policy (reject, cancel_oldest, offset) applied before placement, including against the connector's own open orders and any same-wallet orders found on-chain. Wash trading for tier discounts is explicitly not supported.
  8. Bounded spending. Per-order, per-pair, per-hour and per-day notional caps; optional kill switch; dry_run/paper mode that never signs. Caps are enforced locally even if a strategy misbehaves.
  9. Legal/venue rules. Respect pair pause (pause blocks Receive, cancel and claim), factory blacklist (wallet/token/pair), and F6 code-id freeze. Surface typed errors; do not retry a deterministic revert.
  10. Rate limits and budget. Use the DEX read plane; do not poll LCD in loops; honour 429 Retry-After; no more than one book refresh per pair per configured interval; no per-order full-book walks.
  11. Token semantics. Only trade tokens with known decimals and supported tax semantics; community-tax CW20s need the documented TaxPreview/extra-debit handling (skills/AGENTS_FRONTEND_EXTRA_DEBIT_SELL.md, skills/AGENTS_LOCAL_QUOTE_COVERAGE.md). Unknown semantics fail closed.
  12. Supply chain. Pin dependencies, no unpinned git installs, no build-time network fetches in the connector runtime, respect docs/supply-chain-security.md.
  13. Anonymity. No user handles, chat text, operator identities, or wallet-to-person mappings in code, docs, fixtures, screenshots or logs.

Relevant files

Area Files
New connector package integrations/hummingbot/hummingbot/connector/exchange/cl8y_dex/ — cl8y_dex_constants.py, cl8y_dex_auth.py, cl8y_dex_web_utils.py, cl8y_dex_utils.py, cl8y_dex_order_book.py, cl8y_dex_api_order_book_data_source.py, cl8y_dex_api_user_stream_data_source.py, cl8y_dex_exchange.py, dummy.pyx, __init__.py
Connector tests integrations/hummingbot/test/hummingbot/exchange/cl8y_dex/ — one test module per component, plus test_cl8y_dex_order_lifecycle.py and test_cl8y_dex_signing.py
Chain execution layer integrations/cl8y_client/ (build/sign/broadcast, OrderStatus reader, tx-log parser, sequence manager)
Harness / ops integrations/hummingbot/README.md, integrations/hummingbot/conf/*.yml.example, scripts/qa/hummingbot-localterra.sh, scripts/qa/hummingbot-smoke.sh, Makefile
Contract/message reference docs/limit-orders.md, docs/route-solver.md, docs/integrators.md, smartcontracts/packages/dex-common/src/pair.rs, smartcontracts/packages/dex-common/src/limit_placement.rs
Existing message builders (reference only) scripts/bots/swarm.py, scripts/bots/swarm_tax.py, frontend-dapp/src/services/terraclassic/pair.ts, frontend-dapp/src/services/terraclassic/hybridSwapGas.ts
Gas rules skills/AGENTS_HYBRID_LIMIT_GAS.md, skills/AGENTS_TERRACLASSIC_GAS.md, docs/limit-orders.md § Batch / ladder gas savings
Fees docs/reference/fee-discount-tiers.md (I13 limit discount), docs/integrators.md § Limit book fees
Local chain scripts/setup-cloud-agent-localterra.sh, scripts/e2e-provision-dev-wallet.sh, docs/localterra-sdk53.md
Policy docs docs/security-model.md, docs/supply-chain-security.md, AGENTS.md

Recommended direction

Phase 0 — package, harness, guardrails

  • New integrations/hummingbot/ tree containing the connector plus a cl8y_client execution layer. Upstream-ready folder layout from day one (constants/auth/web_utils/utils/order_book/data sources/exchange).
  • terra-classic-sdk for account, CW20/bank balances and signing; indexer REST for markets/book/trades/fills; direct LCD only for broadcast, account state, OrderStatus, and pre-sign simulation.
  • LocalTerra harness: reuse the existing chain bootstrap, a dedicated dev wallet funded like the swarm, and a repeatable make hummingbot-localterra target. Connector tests must run in CI without network.

Phase 1 — read-only parity

  • GET /markets (from the sibling issue) → trading pairs, decimals, trading rules (price band, min remainder, rung/step caps, fees, pause/blacklist/frozen).
  • Book from book/snapshot + book stream with sequence/height handling; resync on gap. Depth ≥100 per pair.
  • Last price from pairs/{addr}/stats or best bid/ask; reconcile with trades.
  • Balances: bank uluna and CW20 contracts; report available and total, fee-aware.
  • Until the streams exist, the data source falls back to bounded REST polling with explicit stale-guard and a logged degraded mode (must never silently trade on stale data).

Phase 2 — maker path

  • place_limit_order via CW20 Send → PlaceLimitOrderBatch (single-rung batch for one order) with max_adjust_steps and hint_after_order_id from limit-book/insert-hints; optional expires_at.
  • cancel (single/batch), cancel_all on shutdown/startup per config, reprice via UpdateLimitOrderPrice (relink joins the tail of the equal-price run, no new maker fee — L23).
  • Claim parked orders (ClaimExpiredLimitOrder(s)) with the reason discriminator (expired/dust_filled/force_cleaned/blacklisted/unfillable); pause blocks cancel/claim → surface and wait.
  • Fill tracking: per-order fills from limit-orders/{order_id}/fills and trader stream; idempotent trade IDs; no duplicate fills after restart. Reconcile with typed OrderStatus (Active / ParkedRefund / Unknown) — Unknown is not proof of fill.
  • Fees: maker half charged at placement from escrow; taker half on each fill; model as deducted_from_returns/added_to_cost correctly so Hummingbot P&L is right. Apply the pair's placement discount (limit_discount_bps, tier 1–9) and the taker discount; never invent a discount for an unwired pair (I14).

Phase 3 — taker path

  • Market buy/sell from GET/POST /api/v1/route/solve with amount_in: execute the returned router_operations via the router, or CW20 Send → pair Swap for a single hop that carries hybrid.
  • Pre-sign agreement: re-check snapshot_age_ms, quote_kind, optimality_scope; set min_return/belief_price from estimated_amount_out_net minus slippage; size gas from the documented envelopes (hybrid formula, pool-only 840k, unknown 15M fallback is a refusal, not a default); never reuse a stale quote across a book change.
  • Handle book/bookless hybrid degradation (indexer_hybrid_lcd_degraded, book_start_hint validity) and community-tax extra-debit quotes (gross offer vs net output; route_local_v1).

Phase 4 — safety, observability, packaging

  • Self-trade prevention, spend caps, kill switch, dry-run, startup reconciliation (cancel/reclaim orphan orders; refuse to adopt orders that are not provably ours), single-instance lock.
  • Structured logs (no secrets), counters for orders placed/cancelled/rejected, ambiguous broadcasts, sequence refreshes, stale skips, quote refusals; a status command for humans.
  • Config schema (conf/) with a cl8y_dex section: network endpoints, wallet selector, pair allowlist, slippage bounds, caps, strategies' defaults, poll intervals, self_trade_prevention, dry_run.
  • Docs: install, config, key custody, safety limits, known deviations, troubleshooting, plus a "what the connector will not do" list.

Phase 5 — upstream contribution

  • Connector folder + test folder conforming to the spot checklist; a docs PR to hummingbot-site; an HGP draft; a maintenance commitment (CI, release cadence, security contact) stated in the PR.
  • Independent fallback: a documented "vendor connector" install path (pinned commit/tag, no fork required) so users are not blocked on governance. Both paths must share the same code.

Given / When / Then

Given a funded wallet, a running indexer and a fresh book on a supported pair,

When the operator starts Hummingbot with a pure_market_making strategy on cl8y_dex,

Then the connector discovers the pair rules, places a resting order through the on-chain book, binds the returned order_id to its client order id, reports the maker placement fee in the fee ledger, refreshes the book from snapshots/streams without LCD spam, and cancels its orders on shutdown.

Given a placement broadcast whose response is lost (timeout or node error),

When the connector retries,

Then it first locates the tx by hash and the order_id in the placement records, and only re-signs when no committed placement exists — never producing duplicate resting orders.

Given the indexer book snapshot is stale or a market flag is unknown,

When a strategy asks the connector for a price or to place an order,

Then the connector refuses to place, reports the degraded reason, and does not fall back to a chain poll inside the request path.

Given a market (taker) quote older than the configured freshness bound,

When the strategy submits a buy/sell,

Then the connector re-quotes and signs only a fresh route with a positive min_return, or fails without signing.

Acceptance criteria

  1. Connector package layout, classes and file names match the Hummingbot spot-connector checklist, including _auth.py, order book + user stream data sources, and dummy.pyx; imports/instantiation work from a stock Hummingbot install.
  2. Market discovery and trading rules come from the DEX read plane: pair addresses, base/quote tokens with decimals, price band, min remaining, rung/step caps, fees, pause/blacklist/frozen; unknown values fail closed.
  3. Book depth ≥100 per pair with generation/height tracking; resync on gap; stale book ⇒ no placement and a typed reason. REST polling fallback is explicit and never bypasses the stale guard.
  4. Bank + CW20 balances reconcile with chain; available excludes escrowed/allowance-bound funds; decimal handling correct for 6/18-decimal assets.
  5. Maker orders: place (with hints and steps), batch cancel, reprice (no new maker fee, tail-of-equal-price semantics), cancel-all on shutdown, claim parked refunds with reason.
  6. client_order_id → order_id binding is derived from committed tx events; ambiguous broadcast resolves by tx hash before any retry; duplicate placements are impossible in tests.
  7. Fill/order lifecycle: idempotent fills, restart-safe tracking, typed OrderStatus reconciliation (Active/ParkedRefund/Unknown — Unknown never counted as filled), parks and claims reflected in status.
  8. Taker orders: route-solve execution with min_return, freshness and degraded-quote refusal, message-shape gas envelopes, and explicit failure when gas/quote cannot be established.
  9. Fees: maker placement half, taker fill half, CL8Y tier discounts (including limit_discount_bps for placement) reported through Hummingbot fee accounting without double counting.
  10. Self-trade prevention (configurable), spend caps per order/pair/hour/day, kill switch, and dry_run that provably never signs.
  11. Sequence/account handling: single-flight signing, refresh on sequence mismatch, bounded retries, halt on suspected key sharing; never signs with an unverified chain_id.
  12. Safety handling for pause, blacklist, F6 freeze, price band, dust (LimitOrderAmountTooSmall), insert-step exhaustion, batch-all-or-nothing revert, and expiry-park races.
  13. LocalTerra E2E passes with real transactions for both a maker strategy (PMM) and a taker strategy (cross_exchange_market_making against paper_trade or a supported CEX connector in dry-run), including cancel-all, restart/recovery, and fill reconciliation.
  14. Connector unit tests cover all components with ≥80% line coverage and no network; the suite runs in CI on Python ≥3.10 (or the pinned Hummingbot Python version).
  15. Docs + HGP draft + vendor-install path exist; every deviation from the upstream checklist is documented with rationale.
  16. make verify-issue-<n> exists and passes; docs/qa/issue-<n>/README.md checklist and skills/AGENTS_HUMMINGBOT_CONNECTOR.md (invariants HB1–HB12) are present.
  17. No secrets, handles, chat excerpts or user identifiers in the repository or logs.

Test plan — all paths

# Path Case Expected
T1 Unit /markets parsing, decimals 6/18, missing metadata, unknown flags Correct pairs; unknown ⇒ refuse to trade
T2 Unit Book snapshot ordering (walk_index), depth truncation, stale flag Ordering matches on-chain FIFO; stale ⇒ guard trips
T3 Unit Stream sequence gap, duplicate event, resync, reconnect Resync, no duplicate levels, no lost updates
T4 Unit REST fallback polling with 429/503/timeout Backoff honours Retry-After; stale after bound
T5 Unit Place order message construction (single, batch, ladder, expiry, hints, steps) Golden JSON matches contract schema
T6 Unit Cancel single/batch, cancel-all, ownership mismatch Correct messages; non-owned ids refuse locally
T7 Unit Reprice message + tail-of-equal-price expectation Message shape; no fee; no id change
T8 Unit Fee math: pair fee, tier 1–9, limit_discount_bps, taker discount, unregistered, tier 255 Matches contract floor(eff/2) and docs
T9 Unit Gas envelopes: place, ladder, reprice, hybrid, pool-only, unknown quote Exact documented formulas; unknown ⇒ refuse
T10 Unit Account sequence: success, code 32, concurrent signing, second process Single-flight; refresh; halt on suspected sharing
T11 Unit Ambiguous broadcast: timeout after commit, timeout before commit, node 500, duplicate hash Resolve-by-hash; no duplicate order; correct error
T12 Unit Tx log parsing: columnar attrs, missing attrs (legacy pair), multiple rungs order_id per rung; missing ⇒ ambiguous, no false binding
T13 Unit OrderStatus: Active, ParkedRefund (each reason), Unknown Correct lifecycle; Unknown never filled
T14 Unit Fills: partial, multiple per order, same fill twice, restart mid-fill Idempotent trade ids; no double count
T15 Integration LocalTerra place → fill → cancel/reprice/claim flows Chain state matches connector state; gas_used < gas_wanted
T16 Integration LocalTerra market order via route solver, 1-hop hybrid and ≥2-hop Signed ops equal quoted ops; min_return respected
T17 Integration Pause pair mid-run: place, cancel, claim, clean Typed refusals; no stuck retries; recovery after unpause
T18 Integration Blacklist wallet/token/pair, F6 freeze Pre-trade refusal or typed on-chain error; no retry storm
T19 Integration Dust/price band/rung cap/step exhaustion/batch skip refund Local validation or correct partial-refund accounting
T20 Integration Expiry park between quote and sign; park then claim No failed blind cancel; claim refunds and closes lifecycle
T21 Integration Insufficient gas balance, insufficient CW20 balance, allowance edge Clear pre-sign error; never a half-signed tx
T22 Integration Restart with open orders; second instance start Startup reconciliation; second instance refused
T23 Strategy PMM 15 min on LocalTerra No self-trades, no duplicate orders, caps respected, P&L fee-consistent
T24 Strategy XEMM vs paper_trade (dry-run CEX) 15 min Quotes/trades consistent; no signing on dry-run CEX leg
T25 Strategy avellaneda_market_making (V2) smoke Order lifecycle and inventory tracking correct
T26 Fault Indexer down, LCD down, RPC lag, chain-id mismatch, clock skew Degrade/refuse; never sign unsafe
T27 Ops Config validation: bad pair, wrong network, bad slippage, missing key, world-readable key file Refuse to start with actionable error; no secret echo

Adversarial test plan — attack, hack, abuse

# Vector Attack Required behaviour
A1 Malicious data source Compromised/spoofed indexer returns inflated book or quote to induce an adverse trade Cross-check executable amount with on-chain HybridSimulation/router sim before signing; bound deviation vs pool reference; refuse on mismatch; pinned HTTPS endpoint + optional cert pin
A2 Front-running / sandwich Observer sees pending maker/taker tx and trades ahead min_return from fresh quote; bounded size; timing jitter; avoid predictable ladder cadence; document mempool exposure honestly
A3 Fake fill / reorg API claims a fill that did not commit, or a fill is reorged out Trust chain OrderStatus + committed tx events; reorg handling on indexed history; never close a position on an uncommitted fill
A4 Duplicate placement Ambiguous send followed by a retry creates two orders Resolve-by-hash before retry (T11); assert single placement per client order id in integration tests
A5 Sequence griefing Another process/key user races the sequence to stall the bot code 32 handling with bounded retries, then halt with a distinct error; single-instance lock
A6 Key exfiltration Read env, config, logs, crash dumps, shell history, process args 0600 config, redaction tests, no key in argv, no key in exceptions, optional external signer interface; documented threat model
A7 Spend drain Strategy bug or malicious config drains the wallet Per-order/pair/hour/day caps, allowlisted pairs/tokens, kill switch, optional max open orders; caps cannot be raised by strategy code
A8 Self-trade / wash Connector crosses its own orders, or a user attempts wash volume for CL8Y tier discounts Self-trade prevention policy enforced pre-placement; wash trading unsupported and documented; report attempted manipulation
A9 Malicious CW20 Token with hidden transfer fee, blacklist, extra debit, or rebasing semantics Allowlist + token_info/TaxPreview checks; unknown semantics fail closed; never size from nominal remaining
A10 Dust/order-spam griefing Attacker floods the book to exhaust maker steps or park dust Bounded steps and rung caps; skip/park handling; connector never loops retries on deterministic reverts
A11 Quote staleness exploitation Adversary waits for a stale route and takes the other side Freshness bound + book change detection; re-quote on any generation change
A12 Pause/blacklist bypass Bot retries during an emergency pause or blacklist Typed refusal, no retry, visible status; never bypass governance controls
A13 Replay/cross-chain Tx or signed bytes replayed on another chain/network chain_id verification, sequence, and nonce semantics; signed payload never reused
A14 Dependency compromise Malicious PyPI dependency or connector update Pinned versions + hashes, reviewed lockfile, no runtime downloads, reproducible local install
A15 Fee-discount abuse Self-registering CL8Y balances to fake tier, or reporting discounts that do not exist Read tier from contract/indexer truth; never compute a discount locally; unwired pairs pay full fee (I14)

Verification criteria

  • make verify-issue-<n>: formatting/lint (ruff/black or repo standard), connector unit tests with coverage gate, cl8y_client unit tests, no-network assertion, and a LocalTerra suite gated like VERIFY_ISSUE_1329_CHAIN=1 (explicitly SKIP when no chain, never silently PASS).
  • docs/qa/issue-<n>/README.md records each AC as PASS/FAIL/SKIP with the exact command, tx hashes, heights and UTC timestamps. Executed failures remain FAIL; unavailable live checks are explicit SKIP and do not close acceptance.
  • LocalTerra receipts: placement/cancel/reprice/claim/market-order tx hashes with code=0, gas_used < gas_wanted, and OrderStatus read-backs for each lifecycle state.
  • Restart/ambiguous-broadcast receipts: induced timeout mid-broadcast, then proof that exactly one order exists on-chain.
  • Strategy soak: 15-minute PMM and XEMM (paper CEX) runs with no duplicate orders, no self-trades, caps enforced, fee totals reconciled against the pair's limit_order_fill events.
  • Production readiness (read-only): connector connected to prod indexer + a zero-balance wallet in dry_run can discover markets, read depth ≥100, and refuse to sign; no writes, no funds moved.
  • Upstream artefacts: connector checklist mapping table, docs PR link, HGP draft, maintenance policy; vendor-install instructions verified from a clean environment.
  • Source-level checks alone do not establish deployed acceptance.

Out of scope

  • Gateway DEX connector / amm-arbitrage (separate sibling issue).
  • Cross-chain settlement/bridging. The spot connector stays Terra Classic only; bridge-backed cross-chain arbitrage and inventory rebalancing are owned by #1582, which uses CL8Y Bridge (https://bridge.cl8y.com).
  • Perpetual/futures connectors (the venue has no perps).
  • Maker rebates, incentive programmes, or wash-trading volume schemes.
  • Strategy-side profit logic (Hummingbot owns strategies; the connector only supplies a correct venue).
  • Upstream governance outcome (the HGP vote is outside engineering control; the vendor path must work regardless).

Deliverables

  • integrations/hummingbot/ connector package + integrations/cl8y_client/ execution layer + tests + conf/ examples.
  • scripts/qa/hummingbot-localterra.sh, scripts/qa/hummingbot-smoke.sh, make hummingbot-localterra, make verify-issue-<n>.
  • docs/runbooks/hummingbot-connector.md (install, custody, limits, troubleshooting, deviations), docs/integrators.md bot section, skills/AGENTS_HUMMINGBOT_CONNECTOR.md (HB1–HB12), docs/qa/issue-<n>/README.md.
  • Cross-links: consume #1580 (read plane) and reference #1582 (Gateway path); comment on #1580/#1582 when the connector lands.

First-pass model recommendation

Recommendation: a high-capability coding model with Python + Cosmos/Terra Classic experience and access to a LocalTerra sandbox. The high-risk parts are order-id binding after ambiguous broadcasts, sequence handling, and fee/gas accounting; those are fund-loss classes of bug, not style issues.

# Summary Build and maintain an open-source **Hummingbot spot connector for CL8Y DEX** so strategy bots can market-make on the on-chain limit book and take liquidity through the hybrid route solver without writing chain code. A Hummingbot connector is the lowest-friction, no-marketing distribution channel available to this venue: bots already hunt for discoverable, profitable markets and do not care that the settlement asset is LUNC. This issues bundles the whole connector deliverable: connector package (market data, balances, orders, fills, fees), the Terra Classic signing/execution layer the connector needs, self-trade and spend guardrails, a LocalTerra-based conformance harness, and the upstream contribution path. It consumes the DEX read plane from the sibling market-data issue ([#1580](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1580): cached book snapshot, `/markets` discovery, book + per-wallet streams). The connector must still work, degraded but safe, if those streams are unavailable. Gateway-mediated swaps/LP are tracked separately in [#1582](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1582). # Community request (anonymized) A community request asked whether a Hummingbot connector is worth building for CL8Y DEX, reasoning that bot/strategy flow already reaches major centralized venues, that bots only need a discoverable, tradable and profitable market, and that the connector (open source) would widen reach without marketing spend. Do not retain or reproduce handles, timestamps, quotations, or any user-identifying information from that request in this issue, code, docs, tests, fixtures, commit messages, or connector logs. # Current codebase ### What exists - **On-chain venue**: Terra Classic (`columbus-5`) CosmWasm DEX. Pair contract supports pool swaps, hybrid pool+book swaps, greedy book-first swaps, resting FIFO limit orders (place batch/ladder, cancel batch, reprice, expiry/claim, permissionless clean), router multi-hop execution, community-tax CW20s, and CL8Y fee-discount tiers. Message shapes and invariants: `docs/limit-orders.md`, `docs/integrators.md`, `smartcontracts/packages/dex-common/src/pair.rs`. - **Read API**: indexer REST at `indexer.dex.cl8y.com` (prod) / `127.0.0.1:3001` (dev). Book via LCD-proxy endpoints; route solving is zero-LCD (`local_v1`) and returns `hops` + `router_operations` + `estimated_amount_out_net` + `snapshot_age_ms`. See `docs/indexer-http.md`. - **Fills/order history**: `GET /api/v1/pairs/{addr}/limit-fills`, `.../limit-orders/{order_id}/fills`, `.../limit-placements|limit-cancellations`, and trader-scoped equivalents. - **In-repo bots (not a connector)**: `scripts/bots/swarm.py` / `swarm_tax.py` build CW20 `Send` + pair hook messages and shell out to `docker exec … terrad tx …` on LocalTerra. `packages/localnet-trading-swarm` is a TypeScript LocalTerra-only swarm. Neither holds keys safely for mainnet nor implements order lifecycle reconciliation. - **Python signing library available**: `terra-classic-sdk` (PyPI, 3.0.2, `>=3.10,<4`) supports Terra Classic LCD/key management/signing including the 0.47 chain upgrade. - **Hummingbot upstream**: ~28 CEX spot connectors under `hummingbot/connector/exchange/*`; no Terra/Terra Classic connector today. Gateway (the DEX path) supports only `ethereum` and `solana` chains, so a Gateway route is not available without a new chain implementation (separate sibling issue). - **Hummingbot connector standard** (`hummingbot.org/connectors/`): required public REST (active markets, last price, order book snapshot, ping, trading rules), required private REST (balance, order status, open orders, create/cancel), required public book channel with **minimum depth 100**, required **private user order/trade channel**, documented rate limits, and an auth class. A connector must live in `hummingbot/connector/exchange/<name>/` with a matching test folder, docs PR to `hummingbot-site`, and an HGP for upstream inclusion. - **Chain economics**: columbus-5 gas floor **28.325 uluna/gas** (`docs/runbooks/mainnet-soft-launch.md`); place/cancel/reprice/hybrid gas envelopes are derived from signed message shape (`skills/AGENTS_HYBRID_LIMIT_GAS.md`, `skills/AGENTS_TERRACLASSIC_GAS.md`). ### Gaps - No connector, no maintained Python client, no documented placement/reconciliation state machine for external bots, no self-trade protection guidance, no fee-aware sizing helper, no LocalTerra conformance suite for third-party bot authors, no upstream documentation/HGP artefacts. # Why - **Distribution without marketing.** Hummingbot users run `pure_market_making`, `avellaneda_market_making`, `cross_exchange_market_making` and arbitrage strategies against any connector that passes their standard. A maintained connector makes CL8Y a selectable venue. - **Market quality.** Market makers tighten the book; arbitrage bots close pool/book and cross-venue gaps; both need reliable order lifecycle semantics rather than ad-hoc scripts. - **Correctness and safety.** A naive bot can double-place after a timeout, cross its own resting orders, misprice by decimals, or size gas from a stale quote. The connector is where those defects must be impossible, not where they are documented as caveats. - **Fee revenue is already modelled.** Maker placement and taker fills pay the treasury; a connector that models the maker/taker split and CL8Y tier discounts keeps bot P&L honest and makes the venue attractive to professional makers. # Constraints and guardrails 1. **Keys never leave the host and never reach logs.** Mnemonic/private key comes from Hummingbot's encrypted config or an explicit local file with `0600` permissions; refuse to start otherwise. Redact key material, signed bytes, and full tx payloads. No telemetry, no remote signing, no key in env printed by `--help`/status. 2. **Chain identity is verified before signing.** On startup, assert LCD/RPC reports `columbus-5` (and the expected bech32 prefix `cosmos`); refuse to trade on mismatch. Never sign a tx whose `chain_id` came from an unverified source. 3. **`order_id` binding is explicit.** CL8Y assigns `order_id` on-chain; it appears only in wasm events (`limit_order_placed`, `order_id`) of the placement tx. The connector must bind `client_order_id → order_id` by parsing the committed tx response. On ambiguous broadcast (timeout/unknown), **look up the placement by tx hash** (indexer `limit-placements` / LCD tx events) before re-signing. Blind retry after an ambiguous send is a fund-loss defect. 4. **Sequence safety.** Cache account number/sequence per wallet, single-flight all signing, refresh on `code 32` (sequence mismatch) with bounded retries, and halt with a clear error when another process appears to share the key. 5. **Quote/execute agreement.** Market (taker) orders must execute exactly the route that was quoted: re-validate the quote's freshness (`snapshot_age_ms` under a configured bound), refuse degraded quote kinds, and set `min_return` from `estimated_amount_out_net` minus configured slippage. Gas comes from the documented message-shape envelopes; no flat 15M default, no query-string gas. 6. **No book trade on stale or unknown depth.** If the book snapshot is stale/missing or the market flags are unknown, the maker strategy must pause rather than place. 7. **Self-trade prevention.** Configurable policy (`reject`, `cancel_oldest`, `offset`) applied before placement, including against the connector's own open orders and any same-wallet orders found on-chain. Wash trading for tier discounts is explicitly not supported. 8. **Bounded spending.** Per-order, per-pair, per-hour and per-day notional caps; optional kill switch; `dry_run`/paper mode that never signs. Caps are enforced locally even if a strategy misbehaves. 9. **Legal/venue rules.** Respect pair pause (pause blocks `Receive`, cancel and claim), factory blacklist (wallet/token/pair), and F6 code-id freeze. Surface typed errors; do not retry a deterministic revert. 10. **Rate limits and budget.** Use the DEX read plane; do not poll LCD in loops; honour `429` `Retry-After`; no more than one book refresh per pair per configured interval; no per-order full-book walks. 11. **Token semantics.** Only trade tokens with known `decimals` and supported tax semantics; community-tax CW20s need the documented `TaxPreview`/extra-debit handling (`skills/AGENTS_FRONTEND_EXTRA_DEBIT_SELL.md`, `skills/AGENTS_LOCAL_QUOTE_COVERAGE.md`). Unknown semantics fail closed. 12. **Supply chain.** Pin dependencies, no unpinned git installs, no build-time network fetches in the connector runtime, respect `docs/supply-chain-security.md`. 13. **Anonymity.** No user handles, chat text, operator identities, or wallet-to-person mappings in code, docs, fixtures, screenshots or logs. # Relevant files | Area | Files | | --- | --- | | New connector package | `integrations/hummingbot/hummingbot/connector/exchange/cl8y_dex/` — `cl8y_dex_constants.py`, `cl8y_dex_auth.py`, `cl8y_dex_web_utils.py`, `cl8y_dex_utils.py`, `cl8y_dex_order_book.py`, `cl8y_dex_api_order_book_data_source.py`, `cl8y_dex_api_user_stream_data_source.py`, `cl8y_dex_exchange.py`, `dummy.pyx`, `__init__.py` | | Connector tests | `integrations/hummingbot/test/hummingbot/exchange/cl8y_dex/` — one test module per component, plus `test_cl8y_dex_order_lifecycle.py` and `test_cl8y_dex_signing.py` | | Chain execution layer | `integrations/cl8y_client/` (build/sign/broadcast, `OrderStatus` reader, tx-log parser, sequence manager) | | Harness / ops | `integrations/hummingbot/README.md`, `integrations/hummingbot/conf/*.yml.example`, `scripts/qa/hummingbot-localterra.sh`, `scripts/qa/hummingbot-smoke.sh`, `Makefile` | | Contract/message reference | `docs/limit-orders.md`, `docs/route-solver.md`, `docs/integrators.md`, `smartcontracts/packages/dex-common/src/pair.rs`, `smartcontracts/packages/dex-common/src/limit_placement.rs` | | Existing message builders (reference only) | `scripts/bots/swarm.py`, `scripts/bots/swarm_tax.py`, `frontend-dapp/src/services/terraclassic/pair.ts`, `frontend-dapp/src/services/terraclassic/hybridSwapGas.ts` | | Gas rules | `skills/AGENTS_HYBRID_LIMIT_GAS.md`, `skills/AGENTS_TERRACLASSIC_GAS.md`, `docs/limit-orders.md` § Batch / ladder gas savings | | Fees | `docs/reference/fee-discount-tiers.md` (I13 limit discount), `docs/integrators.md` § Limit book fees | | Local chain | `scripts/setup-cloud-agent-localterra.sh`, `scripts/e2e-provision-dev-wallet.sh`, `docs/localterra-sdk53.md` | | Policy docs | `docs/security-model.md`, `docs/supply-chain-security.md`, `AGENTS.md` | # Recommended direction ### Phase 0 — package, harness, guardrails - New `integrations/hummingbot/` tree containing the connector plus a `cl8y_client` execution layer. Upstream-ready folder layout from day one (constants/auth/web_utils/utils/order_book/data sources/exchange). - `terra-classic-sdk` for account, CW20/bank balances and signing; indexer REST for markets/book/trades/fills; direct LCD only for broadcast, account state, `OrderStatus`, and pre-sign simulation. - LocalTerra harness: reuse the existing chain bootstrap, a dedicated dev wallet funded like the swarm, and a repeatable `make hummingbot-localterra` target. Connector tests must run in CI without network. ### Phase 1 — read-only parity - `GET /markets` (from the sibling issue) → trading pairs, decimals, trading rules (price band, min remainder, rung/step caps, fees, pause/blacklist/frozen). - Book from `book/snapshot` + book stream with sequence/height handling; resync on gap. Depth ≥100 per pair. - Last price from `pairs/{addr}/stats` or best bid/ask; reconcile with `trades`. - Balances: bank `uluna` and CW20 contracts; report `available` and `total`, fee-aware. - Until the streams exist, the data source falls back to bounded REST polling with explicit stale-guard and a logged degraded mode (must never silently trade on stale data). ### Phase 2 — maker path - `place_limit_order` via CW20 `Send` → `PlaceLimitOrderBatch` (single-rung batch for one order) with `max_adjust_steps` and `hint_after_order_id` from `limit-book/insert-hints`; optional `expires_at`. - `cancel` (single/batch), `cancel_all` on shutdown/startup per config, `reprice` via `UpdateLimitOrderPrice` (relink joins the tail of the equal-price run, no new maker fee — L23). - Claim parked orders (`ClaimExpiredLimitOrder(s)`) with the `reason` discriminator (`expired`/`dust_filled`/`force_cleaned`/`blacklisted`/`unfillable`); pause blocks cancel/claim → surface and wait. - Fill tracking: per-order fills from `limit-orders/{order_id}/fills` and trader stream; idempotent trade IDs; no duplicate fills after restart. Reconcile with typed `OrderStatus` (`Active` / `ParkedRefund` / `Unknown`) — `Unknown` is not proof of fill. - Fees: maker half charged at placement from escrow; taker half on each fill; model as `deducted_from_returns`/`added_to_cost` correctly so Hummingbot P&L is right. Apply the pair's placement discount (`limit_discount_bps`, tier 1–9) and the taker discount; never invent a discount for an unwired pair (I14). ### Phase 3 — taker path - Market buy/sell from `GET/POST /api/v1/route/solve` with `amount_in`: execute the returned `router_operations` via the router, or CW20 `Send` → pair `Swap` for a single hop that carries `hybrid`. - Pre-sign agreement: re-check `snapshot_age_ms`, `quote_kind`, `optimality_scope`; set `min_return`/`belief_price` from `estimated_amount_out_net` minus slippage; size gas from the documented envelopes (hybrid formula, pool-only 840k, unknown 15M fallback is a refusal, not a default); never reuse a stale quote across a book change. - Handle book/bookless hybrid degradation (`indexer_hybrid_lcd_degraded`, `book_start_hint` validity) and community-tax extra-debit quotes (gross offer vs net output; `route_local_v1`). ### Phase 4 — safety, observability, packaging - Self-trade prevention, spend caps, kill switch, dry-run, startup reconciliation (cancel/reclaim orphan orders; refuse to adopt orders that are not provably ours), single-instance lock. - Structured logs (no secrets), counters for orders placed/cancelled/rejected, ambiguous broadcasts, sequence refreshes, stale skips, quote refusals; a `status` command for humans. - Config schema (`conf/`) with a `cl8y_dex` section: network endpoints, wallet selector, pair allowlist, slippage bounds, caps, strategies' defaults, poll intervals, `self_trade_prevention`, `dry_run`. - Docs: install, config, key custody, safety limits, known deviations, troubleshooting, plus a "what the connector will not do" list. ### Phase 5 — upstream contribution - Connector folder + test folder conforming to the spot checklist; a docs PR to `hummingbot-site`; an HGP draft; a maintenance commitment (CI, release cadence, security contact) stated in the PR. - Independent fallback: a documented "vendor connector" install path (pinned commit/tag, no fork required) so users are not blocked on governance. Both paths must share the same code. # Given / When / Then **Given** a funded wallet, a running indexer and a fresh book on a supported pair, **When** the operator starts Hummingbot with a `pure_market_making` strategy on `cl8y_dex`, **Then** the connector discovers the pair rules, places a resting order through the on-chain book, binds the returned `order_id` to its client order id, reports the maker placement fee in the fee ledger, refreshes the book from snapshots/streams without LCD spam, and cancels its orders on shutdown. **Given** a placement broadcast whose response is lost (timeout or node error), **When** the connector retries, **Then** it first locates the tx by hash and the `order_id` in the placement records, and only re-signs when no committed placement exists — never producing duplicate resting orders. **Given** the indexer book snapshot is stale or a market flag is unknown, **When** a strategy asks the connector for a price or to place an order, **Then** the connector refuses to place, reports the degraded reason, and does not fall back to a chain poll inside the request path. **Given** a market (taker) quote older than the configured freshness bound, **When** the strategy submits a buy/sell, **Then** the connector re-quotes and signs only a fresh route with a positive `min_return`, or fails without signing. # Acceptance criteria 1. Connector package layout, classes and file names match the Hummingbot spot-connector checklist, including `_auth.py`, order book + user stream data sources, and `dummy.pyx`; imports/instantiation work from a stock Hummingbot install. 2. Market discovery and trading rules come from the DEX read plane: pair addresses, base/quote tokens with decimals, price band, min remaining, rung/step caps, fees, pause/blacklist/frozen; unknown values fail closed. 3. Book depth ≥100 per pair with generation/height tracking; resync on gap; stale book ⇒ no placement and a typed reason. REST polling fallback is explicit and never bypasses the stale guard. 4. Bank + CW20 balances reconcile with chain; `available` excludes escrowed/allowance-bound funds; decimal handling correct for 6/18-decimal assets. 5. Maker orders: place (with hints and steps), batch cancel, reprice (no new maker fee, tail-of-equal-price semantics), cancel-all on shutdown, claim parked refunds with `reason`. 6. `client_order_id → order_id` binding is derived from committed tx events; ambiguous broadcast resolves by tx hash before any retry; duplicate placements are impossible in tests. 7. Fill/order lifecycle: idempotent fills, restart-safe tracking, typed `OrderStatus` reconciliation (`Active`/`ParkedRefund`/`Unknown` — `Unknown` never counted as filled), parks and claims reflected in status. 8. Taker orders: route-solve execution with `min_return`, freshness and degraded-quote refusal, message-shape gas envelopes, and explicit failure when gas/quote cannot be established. 9. Fees: maker placement half, taker fill half, CL8Y tier discounts (including `limit_discount_bps` for placement) reported through Hummingbot fee accounting without double counting. 10. Self-trade prevention (configurable), spend caps per order/pair/hour/day, kill switch, and `dry_run` that provably never signs. 11. Sequence/account handling: single-flight signing, refresh on sequence mismatch, bounded retries, halt on suspected key sharing; never signs with an unverified `chain_id`. 12. Safety handling for pause, blacklist, F6 freeze, price band, dust (`LimitOrderAmountTooSmall`), insert-step exhaustion, batch-all-or-nothing revert, and expiry-park races. 13. LocalTerra E2E passes with real transactions for both a maker strategy (PMM) and a taker strategy (`cross_exchange_market_making` against `paper_trade` or a supported CEX connector in dry-run), including cancel-all, restart/recovery, and fill reconciliation. 14. Connector unit tests cover all components with ≥80% line coverage and no network; the suite runs in CI on Python ≥3.10 (or the pinned Hummingbot Python version). 15. Docs + HGP draft + vendor-install path exist; every deviation from the upstream checklist is documented with rationale. 16. `make verify-issue-<n>` exists and passes; `docs/qa/issue-<n>/README.md` checklist and `skills/AGENTS_HUMMINGBOT_CONNECTOR.md` (invariants **HB1–HB12**) are present. 17. No secrets, handles, chat excerpts or user identifiers in the repository or logs. # Test plan — all paths | # | Path | Case | Expected | | --- | --- | --- | --- | | T1 | Unit | `/markets` parsing, decimals 6/18, missing metadata, unknown flags | Correct pairs; unknown ⇒ refuse to trade | | T2 | Unit | Book snapshot ordering (`walk_index`), depth truncation, stale flag | Ordering matches on-chain FIFO; stale ⇒ guard trips | | T3 | Unit | Stream sequence gap, duplicate event, `resync`, reconnect | Resync, no duplicate levels, no lost updates | | T4 | Unit | REST fallback polling with 429/503/timeout | Backoff honours `Retry-After`; stale after bound | | T5 | Unit | Place order message construction (single, batch, ladder, expiry, hints, steps) | Golden JSON matches contract schema | | T6 | Unit | Cancel single/batch, cancel-all, ownership mismatch | Correct messages; non-owned ids refuse locally | | T7 | Unit | Reprice message + tail-of-equal-price expectation | Message shape; no fee; no id change | | T8 | Unit | Fee math: pair fee, tier 1–9, `limit_discount_bps`, taker discount, unregistered, tier 255 | Matches contract `floor(eff/2)` and docs | | T9 | Unit | Gas envelopes: place, ladder, reprice, hybrid, pool-only, unknown quote | Exact documented formulas; unknown ⇒ refuse | | T10 | Unit | Account sequence: success, `code 32`, concurrent signing, second process | Single-flight; refresh; halt on suspected sharing | | T11 | Unit | Ambiguous broadcast: timeout after commit, timeout before commit, node 500, duplicate hash | Resolve-by-hash; no duplicate order; correct error | | T12 | Unit | Tx log parsing: columnar attrs, missing attrs (legacy pair), multiple rungs | `order_id` per rung; missing ⇒ ambiguous, no false binding | | T13 | Unit | `OrderStatus`: Active, ParkedRefund (each `reason`), Unknown | Correct lifecycle; `Unknown` never filled | | T14 | Unit | Fills: partial, multiple per order, same fill twice, restart mid-fill | Idempotent trade ids; no double count | | T15 | Integration | LocalTerra place → fill → cancel/reprice/claim flows | Chain state matches connector state; gas_used < gas_wanted | | T16 | Integration | LocalTerra market order via route solver, 1-hop hybrid and ≥2-hop | Signed ops equal quoted ops; `min_return` respected | | T17 | Integration | Pause pair mid-run: place, cancel, claim, clean | Typed refusals; no stuck retries; recovery after unpause | | T18 | Integration | Blacklist wallet/token/pair, F6 freeze | Pre-trade refusal or typed on-chain error; no retry storm | | T19 | Integration | Dust/price band/rung cap/step exhaustion/batch skip refund | Local validation or correct partial-refund accounting | | T20 | Integration | Expiry park between quote and sign; park then claim | No failed blind cancel; claim refunds and closes lifecycle | | T21 | Integration | Insufficient gas balance, insufficient CW20 balance, allowance edge | Clear pre-sign error; never a half-signed tx | | T22 | Integration | Restart with open orders; second instance start | Startup reconciliation; second instance refused | | T23 | Strategy | PMM 15 min on LocalTerra | No self-trades, no duplicate orders, caps respected, P&L fee-consistent | | T24 | Strategy | XEMM vs `paper_trade` (dry-run CEX) 15 min | Quotes/trades consistent; no signing on dry-run CEX leg | | T25 | Strategy | `avellaneda_market_making` (V2) smoke | Order lifecycle and inventory tracking correct | | T26 | Fault | Indexer down, LCD down, RPC lag, chain-id mismatch, clock skew | Degrade/refuse; never sign unsafe | | T27 | Ops | Config validation: bad pair, wrong network, bad slippage, missing key, world-readable key file | Refuse to start with actionable error; no secret echo | # Adversarial test plan — attack, hack, abuse | # | Vector | Attack | Required behaviour | | --- | --- | --- | --- | | A1 | Malicious data source | Compromised/spoofed indexer returns inflated book or quote to induce an adverse trade | Cross-check executable amount with on-chain `HybridSimulation`/router sim before signing; bound deviation vs pool reference; refuse on mismatch; pinned HTTPS endpoint + optional cert pin | | A2 | Front-running / sandwich | Observer sees pending maker/taker tx and trades ahead | `min_return` from fresh quote; bounded size; timing jitter; avoid predictable ladder cadence; document mempool exposure honestly | | A3 | Fake fill / reorg | API claims a fill that did not commit, or a fill is reorged out | Trust chain `OrderStatus` + committed tx events; reorg handling on indexed history; never close a position on an uncommitted fill | | A4 | Duplicate placement | Ambiguous send followed by a retry creates two orders | Resolve-by-hash before retry (T11); assert single placement per client order id in integration tests | | A5 | Sequence griefing | Another process/key user races the sequence to stall the bot | `code 32` handling with bounded retries, then halt with a distinct error; single-instance lock | | A6 | Key exfiltration | Read env, config, logs, crash dumps, shell history, process args | 0600 config, redaction tests, no key in argv, no key in exceptions, optional external signer interface; documented threat model | | A7 | Spend drain | Strategy bug or malicious config drains the wallet | Per-order/pair/hour/day caps, allowlisted pairs/tokens, kill switch, optional max open orders; caps cannot be raised by strategy code | | A8 | Self-trade / wash | Connector crosses its own orders, or a user attempts wash volume for CL8Y tier discounts | Self-trade prevention policy enforced pre-placement; wash trading unsupported and documented; report attempted manipulation | | A9 | Malicious CW20 | Token with hidden transfer fee, blacklist, extra debit, or rebasing semantics | Allowlist + `token_info`/`TaxPreview` checks; unknown semantics fail closed; never size from nominal `remaining` | | A10 | Dust/order-spam griefing | Attacker floods the book to exhaust maker steps or park dust | Bounded steps and rung caps; skip/park handling; connector never loops retries on deterministic reverts | | A11 | Quote staleness exploitation | Adversary waits for a stale route and takes the other side | Freshness bound + book change detection; re-quote on any generation change | | A12 | Pause/blacklist bypass | Bot retries during an emergency pause or blacklist | Typed refusal, no retry, visible status; never bypass governance controls | | A13 | Replay/cross-chain | Tx or signed bytes replayed on another chain/network | `chain_id` verification, sequence, and nonce semantics; signed payload never reused | | A14 | Dependency compromise | Malicious PyPI dependency or connector update | Pinned versions + hashes, reviewed lockfile, no runtime downloads, reproducible local install | | A15 | Fee-discount abuse | Self-registering CL8Y balances to fake tier, or reporting discounts that do not exist | Read tier from contract/indexer truth; never compute a discount locally; unwired pairs pay full fee (I14) | # Verification criteria - `make verify-issue-<n>`: formatting/lint (ruff/black or repo standard), connector unit tests with coverage gate, `cl8y_client` unit tests, no-network assertion, and a LocalTerra suite gated like `VERIFY_ISSUE_1329_CHAIN=1` (explicitly SKIP when no chain, never silently PASS). - `docs/qa/issue-<n>/README.md` records each AC as PASS/FAIL/SKIP with the exact command, tx hashes, heights and UTC timestamps. **Executed failures remain FAIL**; unavailable live checks are explicit SKIP and do not close acceptance. - LocalTerra receipts: placement/cancel/reprice/claim/market-order tx hashes with `code=0`, `gas_used < gas_wanted`, and `OrderStatus` read-backs for each lifecycle state. - Restart/ambiguous-broadcast receipts: induced timeout mid-broadcast, then proof that exactly one order exists on-chain. - Strategy soak: 15-minute PMM and XEMM (paper CEX) runs with no duplicate orders, no self-trades, caps enforced, fee totals reconciled against the pair's `limit_order_fill` events. - Production readiness (read-only): connector connected to prod indexer + a zero-balance wallet in `dry_run` can discover markets, read depth ≥100, and refuse to sign; no writes, no funds moved. - Upstream artefacts: connector checklist mapping table, docs PR link, HGP draft, maintenance policy; vendor-install instructions verified from a clean environment. - Source-level checks alone do not establish deployed acceptance. # Out of scope - Gateway DEX connector / `amm-arbitrage` (separate sibling issue). - Cross-chain settlement/bridging. The spot connector stays Terra Classic only; bridge-backed cross-chain arbitrage and inventory rebalancing are owned by [#1582](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1582), which uses CL8Y Bridge (`https://bridge.cl8y.com`). - Perpetual/futures connectors (the venue has no perps). - Maker rebates, incentive programmes, or wash-trading volume schemes. - Strategy-side profit logic (Hummingbot owns strategies; the connector only supplies a correct venue). - Upstream governance outcome (the HGP vote is outside engineering control; the vendor path must work regardless). # Deliverables - `integrations/hummingbot/` connector package + `integrations/cl8y_client/` execution layer + tests + `conf/` examples. - `scripts/qa/hummingbot-localterra.sh`, `scripts/qa/hummingbot-smoke.sh`, `make hummingbot-localterra`, `make verify-issue-<n>`. - `docs/runbooks/hummingbot-connector.md` (install, custody, limits, troubleshooting, deviations), `docs/integrators.md` bot section, `skills/AGENTS_HUMMINGBOT_CONNECTOR.md` (**HB1–HB12**), `docs/qa/issue-<n>/README.md`. - Cross-links: consume [#1580](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1580) (read plane) and reference [#1582](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1582) (Gateway path); comment on #1580/#1582 when the connector lands. # First-pass model recommendation Recommendation: a high-capability coding model with Python + Cosmos/Terra Classic experience and access to a LocalTerra sandbox. The high-risk parts are order-id binding after ambiguous broadcasts, sequence handling, and fee/gas accounting; those are fund-loss classes of bug, not style issues.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
code/cl8y-dex-terraclassic#1581
No description provided.