feat(integrations): Hummingbot Gateway Terra Classic chain, CL8Y router/AMM connector and bridge-backed cross-chain arbitrage #1582
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#1582
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
Add Terra Classic chain support to Hummingbot Gateway plus a CL8Y DEX connector (router + AMM), so Hummingbot's DEX strategies —
amm_arbitragebetween a centralized venue and CL8Y, liquidity-provision routines, and cross-chain inventory arbitrage — can trade this venue through Gateway's standardized REST contract instead of a bespoke Python signer.Cross-chain arbitrage is in scope and it uses CL8Y Bridge (
https://bridge.cl8y.com, sourcecode/cl8y-bridge-monorepo), not a new bridge built here. The bridge is a lock/attest/delay/execute rail (operatorApproveWithdraw, default 300 s withdrawal delay with canceler oversight, then permissionlessExecuteWithdraw), so cross-chain arbitrage is inventory-based: pre-position value on both chains, price bridge fee + delay/volatility + cancel risk, and use the bridge for rebalancing only. It is never an atomic leg insidetradeorquote.Gateway today ships exactly two chains (
ethereum,solana) and DEX connectors for those chains only. There is no code path from Hummingbot to a Cosmos/CosmWasm venue, and no bot-facing bridge path. This issue bundles the whole enablement: chain implementation, DEX connector, bridge-aware inventory arbitrage, safety limits, tests against LocalTerra plus the bridge monorepo's local development stack, and an upstream contribution path.Related, but separate: the spot/CLOB connector (#1581) covers resting limit orders and hybrid takers inside the Hummingbot client. This issue covers the Gateway-mediated swap/LP and cross-chain paths. Neither depends on the other to be useful, but both consume the DEX read plane (#1580: cached book snapshot,
/marketsdiscovery).Community request (anonymized)
A community request asked whether Hummingbot could be brought to CL8Y DEX as a distribution channel for bot/strategy flow without marketing spend, and whether bridging between chains could eventually be part of that flow.
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 logs.
Current codebase
Gateway (upstream)
src/chains/{ethereum,solana}only;src/connectors/{uniswap,pancakeswap,raydium,orca,meteora,jupiter,dflow,titan,okx,0x}.quote,trade,estimateGas), AMM (poolPrice,addLiquidity,removeLiquidity), CLMM (positions).pnpm+ Node 18+; per-connector config schemas; interactive Swagger in dev.CL8Y DEX (this repository)
columbus-5, cosmwasm 1.x on a 0.47-era chain; bech32 prefixcosmos; gas floor 28.325 uluna/gas.ExecuteSwapOperationswith per-hophybridparams; pairHybridSimulation/HybridReverseSimulation;provide_liquidity/withdraw_liquidity; LP CW20s (18 decimals); factory pair discovery;SwapOperation::TerraSwap.GET/POST /api/v1/route/solve→hops,router_operations,estimated_amount_out_net,optimality_scope,snapshot_age_ms,quote_kind(docs/route-solver.md,docs/integrators.md).skills/AGENTS_TERRACLASSIC_GAS.md,skills/AGENTS_HYBRID_LIMIT_GAS.md).docs/reference/fee-discount-tiers.md).CL8Y Bridge (external system, consumed here — source of truth)
https://bridge.cl8y.com; sourcecode/cl8y-bridge-monorepo(Solidity contracts, CosmWasm bridge, Solana program, operator and canceler services, frontend,multichain-rsshared crate).56/0x00000038, opBNB204/0x000000cc, MegaETH4326/0x000010e6, Terra Classiccolumbus-5/0x00000001, Solanamainnet-beta/0x00000005.0xb2a22c74da8e3642e0effc107d3ac362ce885369on BSC and opBNB (identical CREATE3 addresses; ChainRegistry0x2e5d36…, TokenRegistry0x3d8820…, LockUnlock0xd7b3bf…, MintBurn0x0a1a4b…, plus the router); Terra Classic bridgeterra18m02l2f43c2dagqnz3kfccpgz9pzzz5hk9l5mh5wvr6dcvv47zfqdfs7la; Solana bridge program4XX8ndYXupw4Sb4SsRgAPTmBJJjfZbg8rWjj87iKEhVtwith BridgeConfig PDAHarAAW2pPcgBwMhcwRsUxRqiDeihCJVjZCmdCWpJbmsD.deposit/depositNative, Terra nativeLock, Terra CW20Send { Lock }) → operator observes and callsApproveWithdraw→ withdrawal delay (default300s, admin-settable 60–86 400 s) → anyone callsExecuteWithdraw/withdraw; authorized cancelers mayCancelWithdrawApprovalduring the delay, and adminReenableWithdrawApprovalresets the timer. Reorged deposits are cancelled and re-enabled the same way.Config.fee_bps/fee_config.standard_fee_bpsand EVMgetFeeConfig().standardFeeBps;min_bridge_amount/max_bridge_amount; per-tokenRateLimit/PeriodUsage. ERC20 path pays the fee inmsg.valueat destination; native path deducts it from the bridged amount.keccak256(srcChain, destChain, srcAccount, destAccount, destToken, netAmount, nonce); queriesComputeWithdrawHash,DepositHash,DepositByNonce,PendingWithdraw(all states, single hash),ActiveWithdrawals(non-terminal index,next_start_after),WithdrawApproval,WithdrawDelay,RateLimit,PeriodUsage,Token,Chain; TerraSimulateBridge { token, amount, dest_chain_id }previews the fee./health,/status,/pending,/metrics;/pendingis auth-gated byOPERATOR_API_TOKEN).Gaps
Why
amm_arbitrageneeds a Gateway connector. Without one, CL8Y can only be reached from the client-side spot connector, which does not implement Gateway's AMM/CLMM contract and does not expose LP operations.poolPrice,addLiquidity,removeLiquidity) let strategy authors rebalance liquidity without writing CosmWasm messages. That directly improves book/pool depth.Constraints and guardrails
cl8yroutes must work on loopback only by default and never expose key material.chainIdmust becolumbus-5; verify against the node on startup and per request when the node reports a different chain; refuse to sign otherwise. Config must not accept an arbitrarychainIdoverride in production mode.to.trademust execute the exact route returned byquote, with a positivemin_return/belief_pricederived fromestimated_amount_out_netand the caller's slippage bound. Reject stale quotes (snapshot_age_ms), degraded quote kinds, and missing execution metadata. Never acceptmin_return = 0.HybridSimulation/router simulation (bounded) and refuse if simulated output differs from the quote beyond a documented tolerance.gas/feesper route; never accept caller-supplied gas that exceeds policy; reject when gas price deviates from the configured floor by more than a bound.token_infodecimals must match the catalog.code 32refresh, and request idempotency keys fortradeso a retried HTTP call cannot double-spend.withdraw_delay(default 300 s) plus operator attestation latency plus destination finality.quote/trademust never include a bridge leg; cross-chain arbitrage must be an inventory/rebalance strategy with explicit exposure limits.Status/Configpaused check, token enabled check,Token/Chainregistry lookup,min_bridge_amount/max_bridge_amount, andRateLimit/PeriodUsage. Never bridge to an unregistered destination token or an unverified address.ComputeWithdrawHashagainst the local computation before submitting; reconcile fromPendingWithdraw(all states) andActiveWithdrawals.ApproveWithdrawas pending, not settled: watch forCancelWithdrawApproval/ReenableWithdrawApproval(which resets the timer), never execute before the delay, and never count a bridged amount as balance untilExecuteWithdrawcommits and the destination balance is confirmed.code/cl8y-bridge-monorepowith its own invariants and reviews.Relevant files
gateway/src/chains/terraclassic/—terraclassic.ts,terraclassic.config.ts,terraclassic.constants.ts,terraclassic.routes.ts, wallet/sequence helpersgateway/src/connectors/cl8y/—cl8y.ts,cl8y.config.ts,cl8y.constants.ts,cl8y.utils.ts,router-routes/,amm-routes/integrations/cl8y_bridge_client/— config/address pinning, fee + limit reads, hash computation, deposit/approve/execute state machine, status reconciliation, operator-API adapterpackages/crosschain-arb/— cost model, inventory ledger, exposure caps, orchestration, testsgateway/src/chains/chain.routes.ts,gateway/src/schemas/gateway/src/templates/(config schema pattern),gateway/docs/docs/route-solver.md,docs/integrators.md,docs/limit-orders.md,smartcontracts/packages/dex-common/src/pair.rs,smartcontracts/contracts/router/code/cl8y-bridge-monorepo:docs/architecture.md,docs/crosschain-flows.md,docs/security-model.md,docs/operator.md,docs/contracts-terraclassic.md,docs/contracts-evm.md,docs/TERRACLASSIC_BRIDGE_INVARIANTS.md,packages/contracts-terraclassic/bridge/src/query.rs,packages/contracts-evm/,packages/operator/src/api.rs,packages/multichain-rs/skills/AGENTS_TERRACLASSIC_GAS.md,docs/reference/fee-discount-tiers.mdscripts/setup-cloud-agent-localterra.sh,docs/localterra-sdk53.md; bridge repodocs/local-development.md(anvil + LocalTerra local bridge)docs/security-model.md,docs/supply-chain-security.mdRecommended direction
Phase 1 — chain implementation
src/chains/terraclassicusing@cosmjs/stargate+@cosmjs/cosmwasm-stargate(or the current upstream-supported equivalent), with: node info/chain-id assertion, bank balances, CW20 balances via smart query, account number/sequence cache + single-flight, fee estimation from message shape, broadcast + tx result parsing (including wasm events for fills/refunds), and request timeouts.chainId(pinned),nodeUrl/lcdUrlallowlist,gasPrice(default28.325uluna, bounded override),gasAdjustmentcap,expectedBech32Prefix(cosmos), factory/router/fee-discount addresses, token allowlist, per-trade notional cap,maxOpenOrders/maxRoutesbounds.status,balances,tokens,allowances,estimateGas,poll, following the existing chain-route shape so the Python client needs no special case.Phase 2 — CL8Y connector
quotefromGET/POST /api/v1/route/solve(amount in, pool-only and hybrid modes, max hops), returning output, price impact context, route legs, expiry and a route fingerprint;tradeexecutes the returnedrouter_operations(single-hop pairSwapwhen the route is one hybrid hop, otherwise routerExecuteSwapOperations) with caller slippage →min_return;estimateGasfrom the documented envelopes.poolPricefrom pairHybridSimulation(pool-only params) or mirrored reserves;addLiquidity/removeLiquidityvia pair messages with CW20 allowance handling and LP token accounting (18-decimal LP,MINIMUM_LIQUIDITYrules documented inskills/AGENTS_REBALANCE_MINT_UST1_LP.mdand the pair contract).quote, sotradecannot silently substitute a different route.Phase 3 — CL8Y Bridge client (read + bounded write)
Config/FeeConfig/WithdrawDelay/Token/Chain/RateLimit/PeriodUsage; EVMgetFeeConfig/getCancelWindow/TokenRegistry), never hardcoded.bridge_fee = ceil(amount * fee_bps / 10_000)per the deployed contract, plus both-chain gas, plus a configurable delay/volatility buffer (expected price move overdelay + attestation latency), plus destination venue slippage/depth, plus a cancel/operator-risk margin. Refuse when edge ≤ cost.Lock, Terra CW20Send { Lock }, EVMdeposit/depositNative, destinationExecuteWithdraw(Terra) /withdraw(EVM). Reject an unregistered destination token, a chain that is disabled/paused, an amount outside min/max, and a rate-limit-exceeding amount before signing.quoted → source_deposit_sent → deposit_confirmed → approval_observed → delay_elapsed → withdraw_executed → settled, with terminalcancelled,reapproved(delay reset),stuck,failed. Reconcile fromPendingWithdraw,ActiveWithdrawals,DepositHash, EVM events and destination balances; never infer settlement from an approval alone./status+/pendingreads (whenOPERATOR_API_TOKENis configured) to detect attestation lag; on lag or cancel events, halt new bridging and alert. Never treat the operator API as authority over chain state.bridge kill switch.Phase 4 — cross-chain inventory arbitrage
crosschain_inventory_arbcomponent (not shoehorned intoamm_arbitrage): read CL8Y price (route solver), destination venue price (Gateway connector or CEX), bridge cost/limits, and inventory ledger. Decide between "trade on-chain", "rebalance via bridge", or "do nothing".Phase 5 — tests, docs, contribution
Given / When / Then
Given a Gateway instance with the
terraclassicchain and thecl8yconnector configured, a funded wallet and a running indexer,When a strategy calls
quotefor LUNC → USTC and thentradewith 1% slippage,Then
tradesigns exactly the quoted route with a positivemin_return, uses the documented gas envelope, returns a tx hash, and reports the confirmed output from committed wasm events.Given a quote whose reserve snapshot is older than the freshness bound or whose route includes an unknown market flag,
When
tradeis called,Then Gateway refuses with a structured error and does not sign — even if the caller supplies their own
min_return.Given the node reports a chain id other than
columbus-5(testnet, fork, or a malicious proxy),When any signing route is called,
Then the request fails closed before keys are used, and the failure is visible in the status route.
Given a CL8Y premium on Terra and a discount on a BSC venue for the bridged asset, both inventories funded, and the bridge not paused,
When the cross-chain arb component evaluates the opportunity,
Then it nets the bridge fee, both-chain gas, delay/volatility buffer, destination slippage and cancel risk; if the edge is positive and caps allow, it bridges only the rebalance amount, tracks
deposit → approval → delay → execute → settled, and refuses to count the amount as spendable until settlement.Given the bridge approval is cancelled during the delay window, or the operator stops attesting, or the token/chain is paused or rate-limited,
When the component would otherwise complete a transfer,
Then it halts new bridging, marks the transfer
cancelled/stuck, keeps the amount in in-flight exposure (never spendable), and surfaces an operator-visible alert.Acceptance criteria
terraclassicchain andcl8yconnector from config alone (documented schema, defaults, validation errors);statusreports chain id, height, node health and wallet readiness.estimateGas, andpollwith the standard response shape.cl8y.router.quotereturns route legs, expected output, price impact/degradation metadata, route fingerprint, freshness, and expiry; it supports pool-only, hybrid and multi-hop.cl8y.router.tradeexecutes only the fingerprinted quote with positivemin_return; stale/degraded/unknown-market quotes are refused; simulated-vs-quoted deviation beyond tolerance is refused.estimateGasmatches the documented per-message envelopes within a stated tolerance for swap routes (1-hop pool, 1-hop hybrid, ≥2-hop router), and refuses when the envelope cannot be established.cl8y.amm.poolPrice,addLiquidity,removeLiquiditywork end-to-end with correct decimals, LP accounting, allowance handling, andMINIMUM_LIQUIDITYbehaviour.tradecalls.chainId/node pinning, pause/blacklist/F6-freeze preflight, gas-price bounds, notional caps, and request size/rate limits are enforced and tested.Status/Configpause, token/chain enabled, min/max amount, fee bps,withdraw_delay, andRateLimit/PeriodUsageare read and enforced; the client refuses an unregistered destination token or an unverified address.ComputeWithdrawHash; state machine covers deposit → approval → delay → execute → settled, pluscancelled,reapproved,stuck,failed; nothing is spendable before settlement.quote/tradenever include a bridge leg; cross-chain arb runs only through the separate inventory component; config cannot enable bridge legs insidetrade.amm_arbitrageCEX↔CL8Y completes a LocalTerra end-to-end cycle in test mode (CEX leg simulated or paper), including a no-trade case below the profit threshold; the cross-chain component completes a local bridge cycle against the bridge monorepo's local stack, or records an explicit SKIP with the reason and a chain-truth fixture receipt.pnpm lint/pnpm testare clean under the upstream toolchain.make verify-issue-<n>(repo-local harness) anddocs/qa/issue-<n>/README.mdexist;skills/AGENTS_HUMMINGBOT_GATEWAY.md(HG1–HG12) andskills/AGENTS_CL8Y_BRIDGE_CLIENT.md(BC1–BC10) present.Test plan — all paths
columbus-5/ other chain / unreachableestimateGasfor 1-hop pool, 1-hop hybrid, ≥2 hops, unknown routequoteroute fingerprint stability and route substitution attempt intrademin_return=0, negative, absurdly high, non-integerquote_kind; unknown market flagcode 32, concurrenttrade, retried idempotency keyamm_arbitrageCEX (paper) ↔ CL8Y: profitable, break-even, unprofitableConfig/FeeConfig/WithdrawDelay, EVMgetFeeConfig; boundary amounts at min, min−1, max, max+1ComputeWithdrawHashfixtures (Terra→EVM, EVM→Terra, native + CW20 + ERC20), wrong token/side/nonceApproveWithdraw→ delay →ExecuteWithdraw; CW20 and native pathsreapprovedWithdrawDelayNotElapsedthen successNonceAlreadyUsed/replay refused; no double spendpendingauth failurestuck; alert; no retry stormAdversarial test plan — attack, hack, abuse
tradewith attacker-supplied contract address or message typecolumbus-5, node verification per request, fail closedtoken_infotoken_infocheck + refuse unknown semanticsquoteto exhaust the indexer budget or Gateway CPUConfig/Status, no config override at runtimeTokenlookup, decimals + contract pinning, allowlist; refuse unregistered mintscancelled, in-flight exposure retained, alert, no blind retry; re-enable path requires fresh delay and operator reviewstuck; never assume eventual settlement; documented recovery pathExecuteWithdraw/withdrawfirstRateLimit/PeriodUsagebefore signing; back off; alert; never queue unbounded transfersVerification criteria
make verify-issue-<n>: unit/route tests, chain fixture tests, bridge client unit tests,pnpm lint, coverage gate, docs link check, and LocalTerra + local-bridge integration suites (explicit SKIP without chain; never a silent pass).docs/qa/issue-<n>/README.mdrecords each AC as PASS/FAIL/SKIP with commands, tx hashes, heights and UTC timestamps. Executed failures remain FAIL; unavailable live checks are explicit SKIP and do not close acceptance.gas_used < gas_wanted; refusal receipts for stale quote, bad chain id, unlisted token,min_return=0.ComputeWithdrawHashmatch, approval tx, delay elapsed, execute tx, destination balance delta, fee-collector delta, plus one cancelled/re-enabled transfer showing the delay reset, and one refusal for paused/unregistered/rate-limited.amm_arbitragedry-run receipt: one profitable cycle and one skipped cycle with the cost breakdown.Out of scope
code/cl8y-bridge-monorepowith their own issues, invariants and reviews. This issue only consumes the deployed bridge and reports defects there.trade/quoteroute may include bridging.Deliverables
gateway/src/chains/terraclassic/*andgateway/src/connectors/cl8y/*with route handlers, config schemas, constants and utils.integrations/cl8y_bridge_client/(bridge config pinning, cost model, hash parity, deposit/approve/execute state machine, reconciliation, operator-API adapter) andpackages/crosschain-arb/(inventory ledger, exposure caps, orchestration).quote-only dry-run mode.gateway/docs/terraclassic.md,gateway/docs/cl8y.md,docs/runbooks/hummingbot-gateway.md,docs/runbooks/cl8y-bridge-client.mdin this repo,skills/AGENTS_HUMMINGBOT_GATEWAY.md(HG1–HG12),skills/AGENTS_CL8Y_BRIDGE_CLIENT.md(BC1–BC10),docs/qa/issue-<n>/README.md,make verify-issue-<n>.First-pass model recommendation
Recommendation: a high-capability coding model with TypeScript + CosmJS + Solidity/ABI experience and access to both LocalTerra and the bridge monorepo's local development stack. The high-risk areas are signed-route fidelity, chain-id/bridge-address pinning, transfer-hash parity, and the non-atomic inventory accounting; a mistake in any of those moves funds or double-counts exposure.
feat(integrations): Hummingbot Gateway Terra Classic chain and CL8Y router/AMM connectorto feat(integrations): Hummingbot Gateway Terra Classic chain, CL8Y router/AMM connector and bridge-backed cross-chain arbitrage