# Token Aggregation Service — REST API Reference

Base path: `/api/v1`. Used for discovery of tokens, liquidity pools, prices, volume, and OHLCV by dApps and MetaMask Snap integrations. Supports Chain 138 (DeFi Oracle Meta Mainnet) and Chain 651940 (ALL Mainnet).

## Chains

### GET /api/v1/chains

Returns supported chains.

**Response:** `{ chains: [{ chainId, name, explorerUrl }] }`

---

## Networks and config (Snap)

### GET /api/v1/networks

Full EIP-3085 chain params for `wallet_addEthereumChain` (Chain 138, Ethereum Mainnet 1, ALL Mainnet 651940). Includes RPC URLs, block explorer URLs, native currency, and oracles per chain. Used by the MetaMask Snap to serve dynamic network and oracle data. Source priority is:

1. **NETWORKS_JSON_URL** when configured
2. **NETWORKS_JSON_PATH** / **CONFIG_NETWORKS_JSON_PATH** runtime local JSON
3. built-in network config

Responses include `source: "remote-url" | "runtime-file" | "built-in"` and send `Cache-Control: public, max-age=0, must-revalidate`.

**Response:** `{ source, version: string, networks: NetworkEntry[], lastModified?: string }`  
Each `NetworkEntry` has: `chainId` (hex), `chainIdDecimal`, `chainName`, `rpcUrls`, `nativeCurrency`, `blockExplorerUrls`, `iconUrls` (chain-specific logos; optional), `oracles: [{ name, address, decimals? }]`. Chain 138 and ALL Mainnet include explorer favicons; Ethereum includes standard ETH logo.

### GET /api/v1/config

Oracles (and config) per chain. Used by the Snap for USD price feeds (e.g. ETH/USD).

**Query:** `chainId` (optional) — if provided, returns config for that chain only.

`/api/v1/config` follows the same source priority as `/api/v1/networks`, so both endpoints read from the same freshest source rather than drifting.

**Response (no query):** `{ source, version: string, chains: [{ chainId, oracles: [{ name, address }] }] }`  
**Response (chainId=138):** `{ source, version, chainId: 138, oracles: [{ name, address }] }`

---

## Token list (report)

**GET /api/v1/report/token-list** returns a Uniswap-style token list with **logoURI** per token and a list-level **logoURI**. Each token has: `chainId`, `address`, `symbol`, `name`, `decimals`, `type`, `logoURI`. Chain 138 also exposes staged GRU x402 deployments such as `cUSDT_V2` and `cUSDC_V2` explicitly, with optional metadata fields like `familySymbol`, `deploymentVersion`, and `preferredForX402`. Use for MetaMask token list URL or Snap `get_token_list`. Optional query `?chainId=138` filters by chain. If **TOKEN_LIST_JSON_URL** is set (e.g. GitHub raw URL), the service fetches that JSON and returns it (with optional chainId filter); otherwise uses the built-in canonical token list.

**GET /api/v1/report/cw-registry** returns the public-chain `cW*` registry grouped by chain. When `DEPLOYMENT_STATUS_JSON_PATH` / `CW_REGISTRY_JSON_PATH` points to `cross-chain-pmm-lps/config/deployment-status.json`, the endpoint reads that file at request time so explorer surfaces do not need a rebuild after registry edits. If the file is unavailable, it falls back to the built-in canonical `cW*` subset.

---

## Quote

### GET /api/v1/quote

Returns an estimated swap output amount (constant-product from first available pool for the token pair). When a staged Chain 138 deployment such as `cUSDT_V2` or `cUSDC_V2` is requested before pool cutover, the response includes `canonicalLiquidity` showing whether the quote was resolved through the current active liquidity deployment.

**Query:**

| Param    | Type   | Required | Description                                      |
|----------|--------|----------|--------------------------------------------------|
| chainId  | number | yes      | 138 or 651940                                   |
| tokenIn  | string | yes      | Token address (in)                              |
| tokenOut | string | yes      | Token address (out)                             |
| amountIn | string | yes      | Raw amount in token's smallest unit (integer)   |

**Response:** `{ amountOut: string | null, error?: string, poolAddress?: string | null, dexType?: string }`  
If no pool is found, `amountOut` is `null` and `error` describes. Used by the MetaMask Snap for swap quotes.

---

## Bridge routes

### GET /api/v1/bridge/routes

Returns CCIP bridge routes for WETH9 and WETH10 (Chain 138 and Ethereum Mainnet). Used by the MetaMask Snap and dApps for bridge discovery. Source priority is:

1. **BRIDGE_LIST_JSON_URL** when configured
2. **BRIDGE_LIST_JSON_PATH** / **BRIDGE_ROUTES_JSON_PATH** runtime local JSON
3. built-in routes

If the remote URL is configured but fails, the route falls back to the runtime file or built-in payload rather than returning stale hard failure data. Responses include `source` and send `Cache-Control: public, max-age=0, must-revalidate`.

**Response:** `{ source, routes, chain138Bridges, tokenMappingApi?, lastModified? }`  
- `routes`: `{ weth9: Record<string, string>, weth10: Record<string, string> }` — destination chain name → bridge address.  
- `chain138Bridges`: `{ weth9: string, weth10: string }` — Chain 138 bridge addresses.  
- `tokenMappingApi`: When the service runs from the monorepo, `{ basePath, pairs, resolve, note }` — use the same host and these paths for **cross-chain token address resolution** (138↔651940, 651940↔other chains). Bridge UIs should call `GET /api/v1/token-mapping?fromChain=&toChain=` or `GET /api/v1/token-mapping/resolve?fromChain=&toChain=&address=` when resolving token addresses on destination chains.
- `gruTransport.summary`: when GRU Transport overlay is available, includes counts such as `transportPairs`, `eligibleTransportPairs`, and `runtimeReadyTransportPairs`.

### GET /api/v1/bridge/status

Returns GRU Monetary Transport Layer pair status, including structural `eligible`, operational `runtimeReady`, and per-pair blockers.

**Response:** `{ ok, bridges, gruTransport, message }`  
- `gruTransport.summary`: overlay counts  
- `gruTransport.pairs[]`: `{ key, canonicalSymbol, mirroredSymbol, destinationChainId, eligible, runtimeReady, eligibilityBlockers[], runtimeMissingRequirements[] }`

### GET /api/v1/bridge/metrics

Returns GRU Transport summary counts suitable for dashboards.

**Response:** `{ ok, lanes, gruTransport: { system, summary }, message }`

### GET /api/v1/bridge/preflight

Returns a preflight view of GRU Transport readiness. Use this before deploy, restart, or route enablement.

**Response:** `{ ok, generatedAt, gruTransport: { system, summary, blockedPairs[], readyPairs[] } }`  
- `blockedPairs[]`: pairs that are not structurally eligible or not runtime-ready, with `eligibilityBlockers[]` and `runtimeMissingRequirements[]`
- `readyPairs[]`: minimal list of pairs fully ready to carry live traffic

---

## Token mapping (multichain)

When run from the monorepo (with `config/token-mapping-multichain.json` available):

| Endpoint | Description |
|----------|-------------|
| `GET /api/v1/token-mapping?fromChain=138&toChain=651940` | Token mapping for a chain pair (tokens, addressMapFromTo, addressMapToFrom). |
| `GET /api/v1/token-mapping/pairs` | All defined chain pairs. |
| `GET /api/v1/token-mapping/transport/active` | Full GRU Transport overlay view, including counts and active transport pair metadata. |
| `GET /api/v1/token-mapping/resolve?fromChain=&toChain=&address=` | Resolve token address on target chain. |

`GET /api/v1/token-mapping/resolve` also returns `activeTransportEligible`, `gruTransportRuntimeReady`, and `gruTransportPairKey` when the address maps into an active GRU pair.

Use these for bridge UIs and cross-chain address resolution. See token-aggregation README § Token mapping.

---

## Tokens

### GET /api/v1/tokens

List tokens for a chain with optional market data.

**Query:**

| Param | Type | Required | Description |
|-------|------|----------|-------------|
| chainId | number | yes | 138 or 651940 |
| limit | number | no | Default 50 |
| offset | number | no | Default 0 |
| includeDodoPool | boolean | no | Include DODO pool flag per token |

**Response:** `{ tokens: Token[], pagination: { limit, offset, count } }`  
Each token may include `market` (price, volume, TVL) and `hasDodoPool` / `pmmPool` when requested.

### GET /api/v1/tokens/:address

Token detail by chain and address. Includes market data, pools, and external enrichment (CoinGecko, CMC, DexScreener).

**Query:** `chainId` (required) — 138 or 651940.

**Response:** `{ token: { ...token, onChain, market, external: { coingecko, cmc, dexscreener }, pools[], hasDodoPool, pmmPool } }`

### GET /api/v1/tokens/:address/pools

Liquidity pools for a token.

**Query:** `chainId` (required).

**Response:** `{ pools: [{ address, dex, token0, token1, reserves, tvl, volume24h, feeTier }] }`

### GET /api/v1/tokens/:address/ohlcv

OHLCV (candlestick) data for charts.

**Query:**

| Param | Type | Required | Description |
|-------|------|----------|-------------|
| chainId | number | yes | 138 or 651940 |
| interval | string | no | One of: 5m, 15m, 1h, 4h, 24h. Default 1h |
| from | ISO date | no | Start time (default: 7 days ago) |
| to | ISO date | no | End time (default: now) |
| poolAddress | string | no | Specific pool for price source |

**Response:** `{ chainId, tokenAddress, interval, data: OHLCV[] }`

### GET /api/v1/tokens/:address/price-at

Point-in-time USD valuation for a token at or immediately before a requested timestamp. Intended for explorer transaction detail pages where the transfer-time value should stay anchored to the transaction, while wallet/address/token overview pages can continue showing current market value.

**Query:**

| Param | Type | Required | Description |
|-------|------|----------|-------------|
| chainId | number | yes | 138 or 651940 |
| timestamp | ISO date | yes | Transfer time to price against |

**Response:** `{ chainId, tokenAddress, requestedTimestamp, effectiveTimestamp?, priceUsd?, source }`

- `source` is one of `swap_event`, `ohlcv_5m`, `ohlcv_15m`, `ohlcv_1h`, `ohlcv_4h`, `ohlcv_24h`, `current_market_fallback`, `canonical_fallback`, or `unavailable`
- `effectiveTimestamp` is the candle/snapshot time actually used for valuation

### GET /api/v1/tokens/:address/pricing-context

Snap-ready combined pricing response for one token. Returns the current market valuation and, when `timestamp` is supplied, a transfer-time historical valuation in the same payload.

**Query:**

| Param | Type | Required | Description |
|-------|------|----------|-------------|
| chainId | number | yes | 138 or 651940 |
| timestamp | ISO date | no | Transfer time to price against |

**Response:** `{ chainId, tokenAddress, current, historical? }`

- `current` includes `{ chainId, tokenAddress, priceUsd?, asOf?, sourceLayer, stale, marketLastUpdated? }`
- `historical` includes `{ chainId, tokenAddress, requestedTimestamp, effectiveTimestamp?, priceUsd?, source, locked }`
- `locked` is `true` only when the historical price came from `swap_event` or an `ohlcv_*` source; fallback values are returned with `locked: false`

### GET /api/v1/tokens/:address/signals

Trending/signals (e.g. CoinGecko trending rank) for a token.

**Query:** `chainId` (required).

**Response:** `{ chainId, tokenAddress, signals: { trendingRank } }`

---

## Pools

### GET /api/v1/pools/:poolAddress

Single pool by chain and pool address.

**Query:** `chainId` (required).

**Response:** `{ pool: { address, dex, token0, token1, reserves, tvl, volume24h, feeTier } }`

---

## Search

### GET /api/v1/search

Search tokens by symbol or name.

**Query:** `chainId` (required), `q` (required) — search string.

**Response:** `{ query, chainId, results: Token[] }`

---

## Pricing and market data

- **Per-token price/volume:** Use `GET /api/v1/tokens/:address`; the `market` and `external` fields provide prices and volume (from indexer and CoinGecko/CMC/DexScreener).
- **Liquidity (TVL):** Use `GET /api/v1/tokens/:address/pools` or `GET /api/v1/pools/:poolAddress`; each pool includes `tvl` and `volume24h`.
- **OHLCV:** Use `GET /api/v1/tokens/:address/ohlcv` for time-series price data.

---

## Health

### GET /health

Returns service and database health. Response: `{ status: 'healthy'|'unhealthy', timestamp, services: { database } }`.

---

## Caching and rate limiting

- Endpoints use short-lived cache (e.g. 1–5 minutes). Send `?refresh=1` to bypass the in-process cache when an explorer or operator view needs the latest read immediately.
- `/api/v1` is rate-limited; see server configuration for limits.

---

## Use for discovery (no CMC/CoinGecko submission)

This API is the primary source for **token discovery**, **liquidity pool discovery**, and **pricing/market data** for Chain 138 and ALL Mainnet. dApps and a custom MetaMask Snap can consume it for:

- Token list and metadata
- Liquidity pools and TVL
- Prices and volume
- OHLCV for charts

Combine with the **explorer-hosted token list** (`https://explorer.d-bis.org/api/config/token-list`) for MetaMask token list URL discovery. For dynamic Snap integration, use **GET /api/v1/networks** and **GET /api/v1/config** (see "Networks and config (Snap)" above); the Snap can return the token list URL as `{apiBaseUrl}/api/v1/report/token-list` for MetaMask Settings.
