feat(indexer): virtual CG/GT pairs so native LUNC and USTC can be priced #1437
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#1437
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 five listing-only virtual pairs to the CoinGecko (
/cg/*) and GeckoTerminal (/gt/*) adapters so those crawlers can price native Terra Classic assets. The pairs are not factory pools, must not be stored as pairs, and must not appear on any other API.CoinGecko and GeckoTerminal build that price from the swap and event feeds, not from pair metadata alone. Each published virtual market must show
swaprows onGET /gt/eventsand buy/sell prints onGET /cg/historical_trades, in the same JSON shapes as a factory pair. Ticker volume, high, low, and last price are those swaps.Legs (base / target):
terra1437qslye72t7qmmahn4t5chz50r8a62g45phwkquwpyu2l62u6ksqssgdgulunaterra1nap4dxh9tv35v0ynd9m4k6zt6c0dq6weszc4j5m564kjls56hu7qcr56chuusdulunauusdulunaterra1z0xe7t5ymmltg4vju8tghkq0pewy4et548ta23nlu9zxtl950uyqkv8mv4(18 decimals)uusdIdentity is the contract or denom above, not the ticker string.
cLUNC/cluncin the request are the same CW20.Current codebase
Factory pairs are CW20/CW20. Native LUNC and USTC enter pools only after the wrap mapper turns
ulunainto cLUNC anduusdinto cUSTC. Create-pair does not listulunaoruusdas selectable legs. Indexed rows live inpairsand are served byGET /api/v1/pairs.CoinGecko exchange shape (
indexer/src/api/cg.rs, docs indocs/CG_CMC_COMPLIANCE.md):GET /cg/pairswalksget_all_pairs, skips gem / ALPHA / USTRIX / SpaceUSD viapair_is_listing_excluded, and returns a top-level array of{ ticker_id, base, target, pool_id }.ticker_idis{asset_0.symbol}_{asset_1.symbol}.pool_idispairs.contract_address.GET /cg/tickersuses the set-based aggregator snapshot (default limit 100, 60s cache).base_currency/target_currencyare the CW20 address or the bank denom.last_price/bid/ask/high/lowandliquidity_in_usdcome from indexed swap stats, reserve stamps, andpair_liquidity_usd. Volumes are consolidated swap totals.cl8y_extensionsis always present.GET /cg/orderbookandGET /cg/historical_tradesresolveticker_idthroughfind_pair_by_ticker(indexer/src/api/mod.rs), which maps symbol pairs ontopairs.contract_addressand skips duplicate tickers (L685-7). Historical trades then loadswap_eventsfor that pair id and split buy/sell withoffer_asset_id == asset_1(buy = offer is the target). Volumes andtrade_idare the stored swap row. The orderbook path can call LCD for the pair contract.limitmax is 500.GeckoTerminal Integration API (
indexer/src/api/gt.rs, #646 / #684 / #694):GET /gt/pair?id=loadspairsby contract address. Unknown or excluded ids are 404. Response is{ pair: { id, dexKey: "cl8y", asset0Id, asset1Id, createdAtBlockNumber, createdAtBlockTimestamp, feeBps } }. Asset ids are CW20 addresses or denoms. There is no pair-list route.GET /gt/eventsis how GT discovers pools and prices them. Rows are realswap_eventsandliquidity_eventsonly. A swap carriestxnId,txnIndex,eventIndex,maker,pairId,asset0In/asset1In/asset0Out/asset1Out,priceNative, and post-eventreserves. Amounts are decimalized.reservesare persisted post-event AMM reserves (#684). Combined factory rows are capped at 5000 (over-cap is HTTP 400, no truncation). Block span max is 2000.notify_deposit/unwrapon the pinned mapper), not asswap_events. They never appear on/gt/eventsor/cg/historical_trades.GET /gt/asset?id=loadsassetsby contract or denom.coinGeckoIdis set for the CL8Y CW20 (ceramicliberty-com) and otherwise fromassets.coingecko_id.Native asset symbols in the indexer are LUNC and USTC, not the denoms (#630). A real cLUNC/cUSTC pool is the economic source for an LUNC/USTC cross. Columbus-5 form pin:
terra15rl8g308yzzt5kxu4skgwlahrvm8adyv0s2cupsmvte0akgs2ttsszau38. USDT pricing elsewhere is an advisory $1 catalog pin (#1258) and must not be reused as a DEX print./cmc/*,GET /api/v1/pairs, DeFiLlama daily, route solve, candles, trader volume, andprotocol_pair_tvlall read the samepairs/swap_eventstables. Anything inserted there becomes a real market.Why this is needed
CoinGecko and GeckoTerminal build a token price by walking pool edges. Our traded markets are denominated in cLUNC and cUSTC. The crawlers have no edge from those CW20s to bank
ulunaanduusd, so they cannot publish a native LUNC or USTC price from CL8Y liquidity. They also asked foruluna/uusd,uluna/usdt, andcLUNC/uusdso the native coins connect to each other and to pinned USDT.Those five markets do not exist on-chain. The adapters have to present them in the same JSON shapes the crawlers already parse, including the swap objects inside
/gt/eventsand/cg/historical_trades. A pair row with no swaps is invisible to their pricer. The rest of the DEX keeps treating the markets as absent.Constraints and guardrails
GET /cg/pairs,GET /cg/tickers,GET /cg/orderbook,GET /cg/historical_trades,GET /gt/pair,GET /gt/asset(ids andcoinGeckoIdonly), andGET /gt/events. Do not add them to/cmc/*,/api/v1/pairs, pair detail, candles, trades, stats, route solve, DeFiLlama, protocol TVL, protocol fees, hub prices, or the dApp.pairs,swap_events,liquidity_events,pair_reserves,pair_liquidity_usd, or candles. Pair discovery must ignore the virtual ids. A listing-only projection table is allowed for wrap principal that is not already stored. Fee routes, trader volume, and DeFiLlama must not read it.virtual,synthetic, or a wrapper object./cg/pairsand/cg/tickersstay top-level arrays./gt/pairstays{ "pair": { ... } }withdexKeycl8y.pool_idand GTpair.idare fixed strings, one per market:cl8y-virtual:clunc-uluna,cl8y-virtual:custc-uusd,cl8y-virtual:uluna-uusd,cl8y-virtual:uluna-usdt,cl8y-virtual:clunc-uusd. They are not bech32 and must never equal apairs.contract_address. Every handler that loads a pair by address rejects thecl8y-virtual:prefix with the same 404 it uses for an unknown contract, before LCD or SQL.indexer/src/config.rs(DEFAULT_HUB_CLUNC_ADDRESS,DEFAULT_HUB_CUSTC_ADDRESS,DEFAULT_USDT_CW20_ADDRESS) plus denomsulunaanduusd. Env overrides that the indexer already uses for those pins apply. A CW20 whose symbol iscLUNC,LUNC, orUSDTat any other address is not a leg. LocalTerra addresses that are not inassetscause that one virtual market to be omitted, not a 500./cg/pairsbase,target, andticker_iduseassets.symbolon the pinned rows (natives areLUNCandUSTC, so the expected ids arecLUNC_LUNC,cUSTC_USTC,LUNC_USTC,LUNC_USDT,cLUNC_USTC)./cg/tickersbase_currencyandtarget_currencyare the contract or denom, same as factory rows. Do not putulunainbasewhen the indexed symbol isLUNC.last_priceis human target-per-base, the same orientation asclose_pricefor a factory pair with that asset order. Bid/ask uselisting_spread(reserve mid ± fee, BigDecimal). Nof64. No scientific notation (format_dec). USDT’s 18 decimals stay on the USDT side.GET /gt/eventsincludeseventType: "swap"for each projected fill. The object isGtEventBody::Swap:txnId,txnIndex,eventIndex,maker,pairId,asset0In/asset1In/asset0Out/asset1Out,priceNative,reserves.pairIdis the opaque virtual id. Amounts go through the samedecimalize+format_decpath as factory swaps.priceNativeis the same human target-per-base number as tickerlast_pricefor that print.reservesare the virtual pool balances after that swap. No extra fields. Do not emit a zero-amountjoinin place of a swap.GET /cg/historical_tradesreturnsbuyandsellarrays ofCgTradeEntryfor the virtual ticker. Buy/sell uses the factory rule (offeris the target leg → buy).typeandlimit(max 500) behave as they do now.trade_timestampstays Unix seconds. Build the entry with the same field assignment ascg_historical_trades, so raw-vs-human units cannot drift from factory rows.GET /cg/tickersbase_volume,target_volume,high,low, andlast_priceare the 24h projected swaps, aggregated the same way as factory consolidated volume (each projected swap once).cl8y_extensionsstays the same struct:consolidated: true, book leg"0", pool-only count and pool leg equal to the projected swaps.liquidity_in_usdis the in-memory USD of the virtual reserves using the factory stamp helper. Do not write that number intopair_liquidity_usd.txnIdis the real chain tx hash.makeris that tx’s sender. Block height and timestamp are that tx’s block.trade_idis stable for the source event and unique within the virtual ticker.notify_deposit/unwrapfrom any other contract is ignored, same fail-closed rule as protocol-fee ingest.uluna/uusdandcLUNC/uusduse the pinned cLUNC/cUSTC pool.uluna/usdtuses the pinned cLUNC/USDT pool. A reversed source asset order inverts once. An 18-dec USDT leg stays on the USDT side.txnId, differentpairId.eventIndexis unique per(block, txnId)across the combined response.event_count > 5000is HTTP 400). A window at or under 5000 factory rows stays HTTP 200, then the projected swaps for source events inside that window are appended. Those extra rows must not flip the window to 400 and must not drop a factory row. A window above 5000 factory rows stays 400 and includes no virtual rows.feeBpsis omitted unless the mapper’s configured wrap fee is already known without an LCD call on the request path. Reserves are the mapper’s custodied native balance on one side and the same human amount on the other (1:1 backing). Unset mapper, zero custody, or missing asset → omit the market. Do not publish price1with zero reserves.pair_liquidity_usd, excluding listing-excluded pairs. Price is that pool’s human price composed with the two peg rates. Read asset order frompairs; do not assume cLUNC isasset_0. Missing source or either peg → omit.pair_liquidity_usd. Compose with the cLUNC/uluna peg. No such pool → omit. Do not price this market from the #1258 advisory $1, the LUNC CEX oracle, or hub prices./gt/assetonly.uluna→terra-luna-classic.uusd→terraclassicusd. Pinned USDT →tether. Do not useterra-luna,terra-luna-2, orterrausd. Do not copy the native id onto cLUNC or cUSTC. Other assets stay as they are.pair_is_listing_excludedfor real pairs./cg/pairslist in the fixed table order, then apply the existing limit/offset. On/cg/tickers, append only markets that are published, after the volume-sorted real page, without changing the real rows’ order, and include them in the 60s aggregator cache payload. Ticker-map cache must resolve virtual ticker ids to the opaque id and must not let a virtual id replace a real pair or the reverse.ticker_idwith different legs, keep the real pair, omit the virtual market from CG ticker lookup, and log once. Do not shadow a factory market. Today none of the five symbol pairs should exist as factory pairs.Relevant files
indexer/src/api/cg.rs— pairs, tickers, orderbook, historical tradesindexer/src/api/gt.rs— pair, asset, events, row capindexer/src/api/mod.rs—find_pair_by_ticker, route tableindexer/src/api/aggregator_snapshot.rs— set-based ticker load and cache keyindexer/src/api/listing_spread.rs— bid/ask andliquidity_in_usdindexer/src/api/consolidated_stats.rs—cl8y_extensionsindexer/src/api/cmc.rs— must stay free of virtual rowsindexer/src/indexer/listing_exclude.rs— shared exclude listindexer/src/config.rs— hub and USDT pins,WRAP_MAPPER_ADDRESSindexer/src/db/queries/pairs.rs— factory pair load; do not persist virtual ids heredocs/CG_CMC_COMPLIANCE.md,docs/indexer-invariants.mddocs/listings/forms/geckoterminal.md— list the five opaque ids in the remark so GT can bind themindexer/tests/api_aggregator_batch.rs, GT adapter tests, andlisting_excludetestsRecommended direction
Add a small pure module, for example
indexer/src/api/listing_virtual_pairs.rs, that holds the five definitions and builds responses from pins plus already-loaded factory state. Call it only from the CG and GT handlers after the real query succeeds./cg/tickers,/cg/historical_trades, or/gt/events.swap_events. Translate each fill’s amounts, price, and post-swap reserves into the virtual leg order. The source row stays in the factory event stream.find_pair_by_tickerto return the opaque id for a published virtual ticker.cg_orderbookandcg_historical_tradesmust branch on thecl8y-virtual:prefix beforesimulate_orderbook_cachedor any LCD client. Orderbook: sameCgOrderbookResponseshape, timestamp in Unix milliseconds, one bid and one ask at the latest projected price, sizes from the post-swap reserves, depth still capped bycap_orderbook_depth. Historical trades: the projected swaps for that ticker, mapped by the existing buy/sell loop (HTTP 200). An unpublished ticker stays 404.gt_eventsmaps projected swaps through the existing swap arm (GtEventBody::Swap).gt_pairreturns theGtPairstruct for a known virtual id (created block/timestamp from the first projected swap, else the source pair, else the indexed tip).feeBpsomitted unless rule 10 supplies it.find_pair_by_tickeronly for real pairs. Split the lookup or filter the prefix inside the CMC handlers so/cmc/tickerand/cmc/orderbook404 these ticker ids.docs/CG_CMC_COMPLIANCE.mdand add an invariants row. State that/gt/eventsswaps and/cg/historical_tradesprints are a translated view of real wrap/unwrap and source-pool swaps, and thatswap_events, protocol TVL, and DeFiLlama do not include them.Acceptance criteria
/cg/pairsand/cg/tickerswith the same keys as a factory row andpool_idequal to its opaque id. Currencies are the pinned contract or denom.base_volumeandtarget_volumeequal the 24h projected swaps.last_priceis the newest projected swap.1in human units. A wrap of 5ulunaemits one cLUNC/ulunaswap with principal 5 on each side, not the fee. Cross swap prices match the source fill composed with the pegs, including a reversed source asset order and a 6/18 USDT leg."0"for that market, and it does not emit a swap for it./cg/orderbook?ticker_id=for a published virtual ticker returns 200 in the existing shape and does not call LCD./cg/historical_tradesreturns 200 with oneCgTradeEntryper projected swap, buy/sell split the factory way,limitcapped at 500. An unpublished ticker stays 404. Malformed ticker ids stay 400./gt/pair?id=cl8y-virtual:…returns the same shape as a factory pair,dexKeycl8y, and asset ids equal to the contracts or denoms./gt/assetservescoinGeckoIdterra-luna-classic,terraclassicusd, andtetherforuluna,uusd, and the pinned USDT only./gt/eventsemits oneeventType: "swap"per projected fill whose source tx is inside the window, with the factory field set, the real tx hash, the real sender, and the virtualpairId. The factory swap for that tx is still present and unchanged. A factory window of 5000 rows stays 200 and includes the extra virtual swaps. A factory window of 5001 rows stays 400 and includes none. No virtualjoinis required.GET /api/v1/pairs, pair detail, candles, trades,/cmc/summary,/cmc/ticker,/cmc/assets, DeFiLlama daily, and route solve do not list the opaque ids or the five ticker ids.protocol_pair_tvland trader volume are unchanged.Test plan
Postgres integration tests, no chain. Seed factory assets for the pins,
uluna,uusd, a cLUNC/cUSTC pair with known reserves and at least two swaps, a cLUNC/USDT pair with 6/18 decimals and one swap, indexed wrap and unwrap principal on the pinned mapper, a fee-only fake wrap from another contract, and one gem pair./cg/pairsincludes the five opaque ids in allowlist order after real non-excluded pairs. Gem pairs still absent.limit/offsetslice the combined list. Offset above 10000 is still 400. Empty page when offset is past the end.base_volume/target_volume/high/low/last_pricematch the projected swaps.cl8y_extensionsis present. Cache hit returns the same payload. The source pair’s own ticker volume is unchanged.ulunawith fee 0.01 produces one GT swap and one CG trade on cLUNC/uluna: both sides principal 5,priceNative1,txnIdthe chain hash,makerthe sender. The fee is not the amount. Unwrap flips the in/out legs. Zero principal → that peg emits no swap.uluna/uusdswap and onecLUNC/uusdswap in the same block, same hash, differentpairId. Price 2 with unit pegs stays 2. Reversed source asset order inverts once. The USDT swap uses the same human amount string the factory GT swap would. A second request does not duplicate the projection.buyorsellusing the factory offer-is-target rule.limit=1returns one.type=buydrops sells. LCD client mock records zero calls. Unknown ticker 404;A_B_C400.dexKeycl8yand the right asset ids.terra-lunaandterrausdare not emitted. cLUNC’scoinGeckoIdis notterra-luna-classic.swaprows. A window that does not contain the tx has neither. Factoryreserveson the real pair are unchanged. A 5001-row factory window still 400s and contains no virtual swaps. A 5000-row window stays 200 and includes the virtual swaps.eventIndexdoes not collide inside one tx./api/v1/pairs,/api/v1/pairs/{opaque}, candles, trades,/cmc/summary,/cmc/ticker,/cmc/orderbook/{ticker}do not return the markets (404 on detail). DeFiLlama fixture totals andpair_liquidity_usdsums ignore virtual reserves.LUNC/USTCon different contracts. Real ticker wins. Virtualuluna/uusdis absent from ticker lookup. A second CW20 namedUSDTis not the USDT leg.Attack, hack, and abuse tests
GET /api/v1/pairs/cl8y-virtual:clunc-uluna, route solve with that hop, candles, and trades return 404 and issue no LCD query. Pair discovery fed that string does not insert apairsrow. A body field or query that repeats the prefix (cl8y-virtual:cl8y-virtual:…, encoded slash, uppercase) does not bypass the prefix check.depthis the maximum and when the ticker is repeated.swap_eventsrow count, trader volume, pair rolling volume, protocol fees, and DeFiLlama daily do not increase.pair_liquidity_usddoes not gain a virtual row.txnIdis not an indexed wrap, unwrap, or sourceswap_eventshash does not appear. Query parameters cannot add a swap. The same source tx cannot emit two swaps on one virtual market.makeron the virtual swap is the source sender, and that fact does not create atrader_positionsrow or a/api/v1trade for the opaque pair id.uluna/usdtstill matches the factory pool. Hub UST1$1does not appear.cLUNCorLUNCand a pool againstuusddoes not change virtualbase_currencyorpool_id. Listing exclude still drops the gem pool.Infinity). Dust reserves stay insideformat_dec. A hostile 18-dec amount does not overflow the decimal string or flip the side./cmc/tickernever receives the virtual object from the shared cache.pool_ids or their relative order.Verification
make verify-issue-<this>runs the Postgres integration tests above plus a source check thatlisting_virtual_pairsis referenced fromcg.rsandgt.rsonly, and thatcmc.rs, DeFiLlama, andpairs.rsdo not reference the opaque prefix except the shared 404 guard if that guard lives in one place.make verify-issue-685,make verify-issue-646,make verify-issue-684,make verify-issue-694,make verify-issue-631, andmake verify-issue-655stay green.docs/indexer-invariants.mdand the CG/GT section ofdocs/CG_CMC_COMPLIANCE.mdname the five ids and state that/gt/eventsand/cg/historical_tradescarry one projected swap per real wrap, unwrap, or source-pool swap.PR #1445 merged to main with hosted CI already successful. No merge conflict.
Production rollout and the GeckoTerminal form receipt stay recorded in docs/qa/issue-1437/production-listing.md. Remaining external acceptance, attested historical replay, and the optional #655 browser check are tracked on #1446. Closing this issue because the implementation and rollout commits are on main.