# Route Decision Tree

This document describes the live route-selection tree used by the Token Aggregation Service.

## What It Does

- Resolves pools from the live indexed database.
- Normalizes token labels using the token table and canonical token list.
- Falls back to raw addresses when token metadata is missing, so "missing quote token" pools still render.
- Returns pool depth and freshness on every request.
- Expands the route tree with bridge and destination-swap legs when a destination chain is provided.

## API

### Live tree

```bash
GET /api/v1/routes/tree?chainId=138&tokenIn=0x...&tokenOut=0x...&amountIn=1000000&destinationChainId=1
```

### Depth summary

```bash
GET /api/v1/routes/depth?chainId=138&tokenIn=0x...&tokenOut=0x...&amountIn=1000000&destinationChainId=1
```

## Decision Order

1. Resolve the source token and destination token.
2. Load all live pools for the source token on the source chain.
3. Prefer direct pools for the requested pair, ordered by TVL.
4. If a destination chain is provided, add:
   - bridge leg
   - destination swap leg, when destination liquidity exists
5. Mark pools with stale or missing depth so routing can avoid them.

## Decision Tree

```mermaid
flowchart TD
  A["Start"] --> B["Resolve source token"]
  B --> C["Load live source pools"]
  C --> D{"Direct pool exists?"}
  D -->|Yes| E["Rank by TVL and freshness"]
  D -->|No| F["Bridge or fallback route"]
  E --> G{"Destination chain provided?"}
  F --> G
  G -->|No| H["Return direct-pool decision"]
  G -->|Yes| I["Add bridge leg"]
  I --> J{"Destination liquidity exists?"}
  J -->|Yes| K["Add destination swap leg"]
  J -->|No| L["Bridge-only decision"]
  K --> M["Return atomic-swap-bridge tree"]
  L --> N["Return bridge-only tree"]
```

## Missing Quote Token Pools

The service now resolves token labels in this order:

1. Token row from the database.
2. Canonical token mapping for the chain.
3. Raw address fallback.

That means pools with incomplete token metadata still appear in the API and UI, instead of collapsing to `?` or being dropped entirely.

## Notes

- Route depth is derived from current pool TVL and freshness.
- The endpoint is intentionally short-cache so it follows the current pool index.
- For the full funding flow, the tree reflects:
  - direct pool on Chain 138
  - atomic swap + bridge from Chain 138
  - destination-side completion on the target chain
