'use client' import { useEffect, useMemo, useState } from 'react' import Link from 'next/link' import { Card } from '@/libs/frontend-ui-primitives' import { configApi, type TokenListResponse } from '@/services/api/config' import { aggregateLiquidityPools, featuredLiquiditySymbols, getLivePlannerProviders, getRouteBackedPoolAddresses, getTopLiquidityRoutes, selectFeaturedLiquidityTokens, type AggregatedLiquidityPool, } from '@/services/api/liquidity' import { plannerApi, type InternalExecutionPlanResponse, type PlannerCapabilitiesResponse } from '@/services/api/planner' import { routesApi, type MissionControlLiquidityPool, type RouteMatrixResponse } from '@/services/api/routes' import { missionControlApi, type MissionControlBridgeStatusResponse } from '@/services/api/missionControl' import { statsApi, type ExplorerStats } from '@/services/api/stats' import { summarizeChainActivity } from '@/utils/activityContext' import ActivityContextPanel from '@/components/common/ActivityContextPanel' import FreshnessTrustNote from '@/components/common/FreshnessTrustNote' import { resolveEffectiveFreshness } from '@/utils/explorerFreshness' import { formatCurrency, formatNumber, relativeAge, truncateMiddle, } from './OperationsPageShell' const tokenAggregationV1Base = '/token-aggregation/api/v1' const tokenAggregationV2Base = '/token-aggregation/api/v2' interface TokenPoolRecord { symbol: string pools: MissionControlLiquidityPool[] } interface EndpointCard { name: string method: string href: string notes: string } interface LiquidityOperationsPageProps { initialTokenList?: TokenListResponse | null initialRouteMatrix?: RouteMatrixResponse | null initialPlannerCapabilities?: PlannerCapabilitiesResponse | null initialInternalPlan?: InternalExecutionPlanResponse | null initialTokenPoolRecords?: TokenPoolRecord[] initialStats?: ExplorerStats | null initialBridgeStatus?: MissionControlBridgeStatusResponse | null } function routePairLabel(routeId: string, routeLabel: string, tokenIn?: string, tokenOut?: string): string { return [tokenIn, tokenOut].filter(Boolean).join(' / ') || routeLabel || routeId } export default function LiquidityOperationsPage({ initialTokenList = null, initialRouteMatrix = null, initialPlannerCapabilities = null, initialInternalPlan = null, initialTokenPoolRecords = [], initialStats = null, initialBridgeStatus = null, }: LiquidityOperationsPageProps) { const [tokenList, setTokenList] = useState(initialTokenList) const [routeMatrix, setRouteMatrix] = useState(initialRouteMatrix) const [plannerCapabilities, setPlannerCapabilities] = useState(initialPlannerCapabilities) const [internalPlan, setInternalPlan] = useState(initialInternalPlan) const [tokenPoolRecords, setTokenPoolRecords] = useState(initialTokenPoolRecords) const [stats, setStats] = useState(initialStats) const [bridgeStatus, setBridgeStatus] = useState(initialBridgeStatus) const [loadingError, setLoadingError] = useState(null) const [copiedEndpoint, setCopiedEndpoint] = useState(null) useEffect(() => { let cancelled = false if ( initialTokenList && initialRouteMatrix && initialPlannerCapabilities && initialInternalPlan && initialTokenPoolRecords.length > 0 && initialStats && initialBridgeStatus ) { return () => { cancelled = true } } const load = async () => { const [tokenListResult, routeMatrixResult, plannerCapabilitiesResult, planResult, statsResult, bridgeResult] = await Promise.allSettled([ configApi.getTokenList(), routesApi.getRouteMatrix(), plannerApi.getCapabilities(), plannerApi.getInternalExecutionPlan(), statsApi.get(), missionControlApi.getBridgeStatus(), ]) if (cancelled) return if (tokenListResult.status === 'fulfilled') setTokenList(tokenListResult.value) if (routeMatrixResult.status === 'fulfilled') setRouteMatrix(routeMatrixResult.value) if (plannerCapabilitiesResult.status === 'fulfilled') setPlannerCapabilities(plannerCapabilitiesResult.value) if (planResult.status === 'fulfilled') setInternalPlan(planResult.value) if (statsResult.status === 'fulfilled') setStats(statsResult.value) if (bridgeResult.status === 'fulfilled') setBridgeStatus(bridgeResult.value) if (tokenListResult.status === 'fulfilled') { const featuredTokens = selectFeaturedLiquidityTokens(tokenListResult.value.tokens || []) const poolResults = await Promise.allSettled( featuredTokens.map(async (token) => ({ symbol: token.symbol, pools: (await routesApi.getTokenPools(token.address)).pools || [], })) ) if (!cancelled) { setTokenPoolRecords( poolResults .filter((result): result is PromiseFulfilledResult => result.status === 'fulfilled') .map((result) => result.value) ) } } const results = [tokenListResult, routeMatrixResult, plannerCapabilitiesResult, planResult, statsResult, bridgeResult] as const const failedCount = results.filter((result) => result.status === 'rejected').length if (failedCount === results.length) { setLoadingError('Live liquidity data is temporarily unavailable from the public explorer APIs.') } } load().catch((error) => { if (!cancelled) { setLoadingError( error instanceof Error ? error.message : 'Live liquidity data is temporarily unavailable from the public explorer APIs.' ) } }) return () => { cancelled = true } }, [ initialBridgeStatus, initialInternalPlan, initialPlannerCapabilities, initialRouteMatrix, initialStats, initialTokenList, initialTokenPoolRecords, ]) const featuredTokens = useMemo( () => selectFeaturedLiquidityTokens(tokenList?.tokens || []), [tokenList?.tokens] ) const aggregatedPools = useMemo( () => aggregateLiquidityPools(tokenPoolRecords), [tokenPoolRecords] ) const livePlannerProviders = useMemo( () => getLivePlannerProviders(plannerCapabilities), [plannerCapabilities] ) const routeBackedPoolAddresses = useMemo( () => getRouteBackedPoolAddresses(routeMatrix), [routeMatrix] ) const highlightedRoutes = useMemo( () => getTopLiquidityRoutes(routeMatrix, 6), [routeMatrix] ) const dexCount = useMemo( () => new Set(aggregatedPools.map((pool) => pool.dex).filter(Boolean)).size, [aggregatedPools] ) const activityContext = useMemo( () => summarizeChainActivity({ blocks: [], transactions: [], latestBlockNumber: stats?.latest_block, latestBlockTimestamp: null, freshness: resolveEffectiveFreshness(stats, bridgeStatus), diagnostics: stats?.diagnostics ?? bridgeStatus?.data?.diagnostics ?? null, }), [bridgeStatus, stats], ) const insightLines = useMemo( () => [ `${formatNumber(routeMatrix?.counts?.liveSwapRoutes)} live swap routes and ${formatNumber(routeMatrix?.counts?.liveBridgeRoutes)} bridge routes are currently published in the public route matrix.`, `${formatNumber(aggregatedPools.length)} unique pools were discovered across ${formatNumber(featuredTokens.length)} featured Chain 138 liquidity tokens.`, `${formatNumber(livePlannerProviders.length)} planner providers are live, and the current internal fallback decision is ${internalPlan?.plannerResponse?.decision || 'unknown'}.`, `${formatNumber(routeBackedPoolAddresses.length)} unique pool addresses are referenced directly by the current live route legs.`, ], [routeMatrix, aggregatedPools.length, featuredTokens.length, livePlannerProviders.length, internalPlan?.plannerResponse?.decision, routeBackedPoolAddresses.length] ) const endpointCards: EndpointCard[] = [ { name: 'Canonical route matrix', method: 'GET', href: `${tokenAggregationV1Base}/routes/matrix?includeNonLive=true`, notes: 'All live and non-live route inventory with counts and pool-backed legs.', }, { name: 'Planner capabilities', method: 'GET', href: `${tokenAggregationV2Base}/providers/capabilities?chainId=138`, notes: 'Live provider inventory, published pair coverage, and execution modes.', }, { name: 'Internal execution plan', method: 'POST', href: `${tokenAggregationV2Base}/routes/internal-execution-plan`, notes: 'Returns the direct-pool fallback posture that the operator surfaces already verify.', }, { name: 'Mission-control token pools', method: 'GET', href: `/explorer-api/v1/mission-control/liquidity/token/${featuredTokens[0]?.address || '0x93E66202A11B1772E55407B32B44e5Cd8eda7f22'}/pools`, notes: 'Cached public pool inventory for a specific Chain 138 token.', }, ] const copyEndpoint = async (endpoint: EndpointCard) => { try { await navigator.clipboard.writeText(endpoint.href) setCopiedEndpoint(endpoint.name) window.setTimeout(() => { setCopiedEndpoint((current) => (current === endpoint.name ? null : current)) }, 1500) } catch { setCopiedEndpoint(null) } } return (
Chain 138 Liquidity Access

Public liquidity, route discovery, and execution access points

This page now reads the live explorer APIs instead of hardcoded pool snapshots. It pulls the public route matrix, planner capabilities, and mission-control token pool inventory together so integrators can inspect what Chain 138 is actually serving right now.

{loadingError ? (

{loadingError}

) : null}
Live Pools
{formatNumber(aggregatedPools.length)}
Dedupe of mission-control pool inventory across featured Chain 138 tokens.
Route Coverage
{formatNumber(routeMatrix?.counts?.filteredLiveRoutes)}
{formatNumber(routeMatrix?.counts?.liveSwapRoutes)} swaps and {formatNumber(routeMatrix?.counts?.liveBridgeRoutes)} bridges.
Planner providers
{formatNumber(livePlannerProviders.length)}
{formatNumber(dexCount)} DEX families in the current discovered pools.
Fallback posture
{internalPlan?.plannerResponse?.decision || 'unknown'}
Execution contract {truncateMiddle(internalPlan?.execution?.contractAddress)}
{aggregatedPools.slice(0, 8).map((pool) => (
{(pool.token0?.symbol || '?') + ' / ' + (pool.token1?.symbol || '?')}
Pool: {pool.address}
{pool.dex || 'Unknown DEX'} · TVL {formatCurrency(pool.tvl)}
Seen from {pool.sourceSymbols.join(', ')}
))} {aggregatedPools.length === 0 ? (

Mission-control pool inventory is currently empty, but the live route matrix still references{' '} {formatNumber(routeBackedPoolAddresses.length)} pool-backed legs across{' '} {formatNumber(routeMatrix?.counts?.filteredLiveRoutes)} published live routes.

Use the highlighted route-backed paths below and the public route matrix endpoint while pool inventory catches up.

) : null}
{insightLines.map((item) => (

{item}

))}

Featured symbols in this view: {featuredLiquiditySymbols.join(', ')}.

{highlightedRoutes.map((route) => (
{routePairLabel(route.routeId, route.label || '', route.tokenInSymbol, route.tokenOutSymbol)}
{formatNumber((route.legs || []).length)} legs · {formatNumber((route.legs || []).filter((leg) => leg.poolAddress).length)} pool-backed
{route.aggregatorFamilies?.join(', ') || 'No provider families listed'}
{(route.legs || []) .map((leg) => leg.poolAddress) .filter(Boolean) .map((address) => truncateMiddle(address)) .join(' · ') || 'No pool addresses published'}
))}
{featuredTokens.map((token) => { const matchingRecord = tokenPoolRecords.find((record) => record.symbol === token.symbol) return (
{token.symbol}
{token.name || 'Unnamed token'} · {formatNumber(matchingRecord?.pools.length || 0)} mission-control pools
{truncateMiddle(token.address, 10, 8)}
) })}
{endpointCards.map((endpoint) => (
{endpoint.name}
{endpoint.method}
{endpoint.href}
{endpoint.notes}
{endpoint.name === 'Mission-control token pools' ? ( Open pools page ) : null}
))}
{[ `GET ${tokenAggregationV1Base}/routes/matrix?includeNonLive=true`, `GET ${tokenAggregationV2Base}/providers/capabilities?chainId=138`, `POST ${tokenAggregationV2Base}/routes/internal-execution-plan`, `GET /explorer-api/v1/mission-control/liquidity/token/${featuredTokens[0]?.address || '0x93E66202A11B1772E55407B32B44e5Cd8eda7f22'}/pools`, ].map((example) => (
{example}
))}

Use the wallet page for network onboarding, the pools page for a tighter live inventory view, and this page for the broader route and execution surfaces.

The live route matrix was updated {relativeAge(routeMatrix?.updated)}, and the current route-backed pool set references {formatNumber(routeBackedPoolAddresses.length)} unique pool addresses.

Open pools page Open wallet tools Explorer docs
) }