Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions app/api/robinhood-tokens/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { unstable_cache } from 'next/cache';
import { fetchRobinhoodStockTokens } from '@/data-sources/robinhood-api/assets';

// Cache validated results. An upstream outage must not replace the last successful catalog.
const getCachedTokens = unstable_cache(fetchRobinhoodStockTokens, ['robinhood-stock-tokens:v1'], { revalidate: 1800 });

export async function GET() {
try {
return Response.json(await getCachedTokens(), { headers: { 'Cache-Control': 'public, max-age=300' } });
} catch {
return Response.json({ error: 'Robinhood Stock Token catalog unavailable.' }, { status: 502 });
}
}
7 changes: 4 additions & 3 deletions docs/TECHNICAL_OVERVIEW.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ RootLayout
└── ModalRenderer
```

`DataPrefetcher` warms token and market-whitelist metadata for product routes. The standalone analysis route skips this global prefetch because it manages its own data dependencies.
`DataPrefetcher` warms token and market-whitelist metadata for product routes. The optional Robinhood Stock Token catalog loads after the local and Pendle token query settles. The market registry keeps the indexed Robinhood rows so newly recognized markets can appear without fetching the registry again. The standalone analysis route manages its own data dependencies.

---

Expand Down Expand Up @@ -285,7 +285,7 @@ Hooks omitted from this matrix are local-state hooks or pure view/composition he
|---------------|----------------|-------------|----------------------------------|
| `useCurrentBlocks` / `useBlockTimestamps` / `usePositionSnapshots` / `useFreshMarketsState` / `useHistoricalSupplierPositions` | Block, snapshot, and live-state helpers used by positions/charts | Pure RPC reads via viem/wagmi | No Envio gap |
| `useUserBalancesQuery` | ERC20 wallet balances across chains | Pure RPC multicall via wagmi | No Envio gap |
| `useTokensQuery` | Token metadata lookup for app UI | Local token registry + Pendle assets API | Not part of Monarch migration |
| `useTokensQuery` | Token metadata lookup for app UI | Local token registry + Pendle assets API + deferred Robinhood Stock Token catalog via `/api/robinhood-tokens` | Not part of Monarch migration |
| `useOracleMetadata` / `useAllOracleMetadata` | Oracle classification and feed metadata | Scanner gist JSON | Not part of Monarch migration |
| `useMarketMetricsQuery` | Enhanced market metrics, flows, growing signal, scores, and current backend market flags | External data API via `/v1/markets/metrics` | Already Monarch-backed; compact discovery flags use `/v1/markets/flags` |
| `useUserRewardsQuery` | User claimable rewards and Merkl proofs | Merkl API through the server-side `/api/merkl` API-key proxy | Outside Monarch/Envio scope today |
Expand Down Expand Up @@ -366,7 +366,8 @@ All hooks in `/src/hooks/queries/` follow React Query patterns:
|------|-----|------------|---------|-------|
| `useMarketsQuery` | `['markets']` | 5 min | 5 min | Yes |
| `useMarketMetricsQuery` | `['market-metrics', ...]` | 5 min | 5 min | No |
| `useTokensQuery` | `['tokens']` | 5 min | 5 min | Yes |
| `useTokensQuery` | `['tokens']` | 30 min | 30 min | Yes |
| `useRobinhoodTokensQuery` | `['robinhood-stock-tokens']` | 30 min | 30 min | No |
| `useUserBalancesQuery` | `['user-balances', addr, networks]` | 30s | - | Yes |
| `useUserVaultsV2Query` | `['user-vaults-v2', addr]` | 60s | - | Yes |
| `useVaultV2Data` | `['vault-v2-data', addr, chainId]` | 30s | - | No |
Expand Down
129 changes: 125 additions & 4 deletions scripts/test-token-metadata-cache.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,16 @@ process.env.NEXT_PUBLIC_MONARCH_API_NEW = 'https://monarch.example';

const assert = require('node:assert/strict');
const { afterEach, beforeEach, mock, test } = require('node:test');
const { fetchMonarchMarket, fetchMonarchMarkets } = require('../src/data-sources/monarch-api/markets');
const { clearPersistedApiResponses } = require('../src/utils/persistedApiResponseCache');
const { fetchMonarchMarket, fetchMonarchMarkets, mapNewlyRecognizedMarkets } = require('../src/data-sources/monarch-api/markets');
const { fetchRobinhoodStockTokens } = require('../src/data-sources/robinhood-api/assets');
const { findToken } = require('../src/utils/tokens');
const {
clearPersistedApiResponses,
readPersistedApiResponse,
writePersistedApiResponse,
} = require('../src/utils/persistedApiResponseCache');
const { resolveTokenInfos, TokenMetadataUnavailableError } = require('../src/utils/tokenMetadata');
const { UNRECOGNIZED_COLLATERAL, UNRECOGNIZED_LOAN } = require('../src/utils/warnings');

const disk = new Map();
let storageUnavailable = false;
Expand All @@ -40,7 +47,7 @@ const database = {
clear: () => request(disk.clear()),
}),
};
queueMicrotask(() => queueMicrotask(() => transaction.oncomplete?.()));
setImmediate(() => transaction.oncomplete?.());
return transaction;
},
};
Expand Down Expand Up @@ -185,7 +192,7 @@ test('a cold malformed response rejects at the market fetcher while a valid spar
assert.equal(disk.size, 0);

tokenResponse = () => Response.json({ tokens: {} });
assert.deepEqual(await fetchMonarchMarkets(), { markets: [], tokenMetadataUnavailable: false });
assert.deepEqual(await fetchMonarchMarkets(), { markets: [], robinhoodRows: [], tokenMetadataUnavailable: false });
assert.equal(await fetchMonarchMarket(row.marketId, mainnet.chainId), null);
});

Expand Down Expand Up @@ -231,3 +238,117 @@ test('the opt-out skips storage and the live lookup works without IndexedDB', as
assert.deepEqual((await resolveTokenInfos([mainnet])).tokenInfos.get(tokenKey(mainnet)), metadata(mainnet));
assert.equal(disk.size, 0);
});

const stockChainId = 4663;
const stock = {
tokenSymbol: 'NVDA',
tokenDecimals: 18,
logoUrl: 'https://cdn.robinhood.com/ncw_assets/logos/nvda.png',
status: 'ASSET_STATUS_ACTIVE',
deployments: [{ chainId: stockChainId, contractAddress: `0x${address.slice(2).toUpperCase()}` }],
};

test('Robinhood assets use the public feed and select active canonical deployments by chain and address', async () => {
const otherAddress = '0x1111111111111111111111111111111111111111';
mock.method(globalThis, 'fetch', (url, init) => {
assert.equal(url, 'https://api.robinhood.com/rhj/assets');
assert.equal(init.credentials, 'omit');
assert.equal(init.headers, undefined);
return Response.json({
assets: [
{ ...stock, deployments: [{ chainId: 1, contractAddress: otherAddress }, ...stock.deployments] },
{ ...stock, tokenSymbol: 'duplicate' },
{ ...stock, status: 'ASSET_STATUS_INACTIVE', deployments: [{ chainId: stockChainId, contractAddress: otherAddress }] },
],
});
});
assert.deepEqual(await fetchRobinhoodStockTokens(), [{ address, symbol: 'NVDA', decimals: 18, logoUrl: stock.logoUrl }]);
});

test('Robinhood rejects empty and malformed catalogs before they can replace cached tokens', async () => {
const fetch = mock.method(globalThis, 'fetch');
for (const response of [
new Response(null, { status: 429 }),
new Response('bad json'),
Response.json({ assets: [] }),
Response.json({ assets: [{ ...stock, deployments: [{ chainId: 1, contractAddress: address }] }] }),
Response.json({ assets: null }),
Response.json({ assets: [{}] }),
Response.json({ assets: [stock, { ...stock, tokenDecimals: undefined }] }),
]) {
fetch.mock.mockImplementation(() => response);
await assert.rejects(fetchRobinhoodStockTokens);
}
fetch.mock.mockImplementation(() => Promise.reject(new DOMException('Timed out', 'TimeoutError')));
await assert.rejects(fetchRobinhoodStockTokens, { name: 'TimeoutError' });
});

test('late stock metadata adds only its recognized markets using existing registry rows', async () => {
const standardMarket = marketRow({ chainId: 1, address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' });
const stockMarket = {
...marketRow({ chainId: stockChainId, address }),
loanToken: '0x5fc5360d0400a0fd4f2af552add042d716f1d168',
// Identical identifiers on separate chains are distinct markets.
marketId: standardMarket.marketId,
};
const sameAddressOtherChain = marketRow(base);
const duplicateStockMarket = { ...stockMarket, marketId: stockMarket.marketId.slice(2).toUpperCase() };
const fetch = mockMarketRegistry([standardMarket, stockMarket, duplicateStockMarket, sameAddressOtherChain], () =>
assert.fail('Unexpected metadata request'),
);
const { markets, robinhoodRows } = await fetchMonarchMarkets(undefined, {}, { resolveUnknownTokens: false });
assert.equal(markets.length, 1);
assert.deepEqual(robinhoodRows, [stockMarket, duplicateStockMarket]);
assert.equal(mapNewlyRecognizedMarkets(robinhoodRows, markets, findToken), markets);
const recognized = mapNewlyRecognizedMarkets(robinhoodRows, markets, (tokenAddress, chainId) =>
chainId === stockChainId && tokenAddress === address ? { symbol: 'NVDA', decimals: 18 } : findToken(tokenAddress, chainId),
);
assert.equal(recognized.length, 2);
assert.equal(recognized[0], markets[0]);
assert.equal(recognized[1].collateralAsset.symbol, 'NVDA');
assert.equal(recognized[1].warnings.length, 0);
assert.equal(mapNewlyRecognizedMarkets(robinhoodRows, recognized, findToken), recognized);
assert.equal(fetch.mock.callCount(), 1);
});

test('late stock metadata updates an existing market and keeps its state and other warnings', async () => {
const row = {
...marketRow({ chainId: stockChainId, address }),
loanToken: '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
};
const fetch = mockMarketRegistry([row], () =>
tokensResponse([
{ address, chainId: stockChainId },
{ address: row.loanToken, chainId: stockChainId },
]),
);
const {
markets: [market],
robinhoodRows,
} = await fetchMonarchMarkets();
assert.deepEqual(market.warnings, [UNRECOGNIZED_LOAN, UNRECOGNIZED_COLLATERAL]);
const oracleWarning = { type: 'hardcoded_oracle', level: 'warning', __typename: 'MarketWarning_HardcodedOracle' };
const existing = { ...market, warnings: [...market.warnings, oracleWarning] };
const [recognized] = mapNewlyRecognizedMarkets(robinhoodRows, [existing], (tokenAddress, chainId) =>
chainId === stockChainId && tokenAddress === address ? { symbol: 'NVDA', decimals: 18 } : undefined,
);

assert.deepEqual(recognized.collateralAsset, { id: address, address, name: 'NVDA', symbol: 'NVDA', decimals: 18 });
assert.equal(recognized.loanAsset, existing.loanAsset);
assert.equal(recognized.state, existing.state);
assert.deepEqual(recognized.warnings, [UNRECOGNIZED_LOAN, oracleWarning]);
assert.equal(existing.warnings.length, 3);
assert.equal(fetch.mock.callCount(), 2);
});

test('market snapshots read the legacy array in one transaction and write the new format under its own key', async () => {
const previous = { data: [marketRow(mainnet)], updatedAt: 1 };
await writePersistedApiResponse('markets:v2', previous);
assert.deepEqual(await readPersistedApiResponse('markets:v3', 'markets:v2'), previous);
assert.equal(readonlyTransactions, 1);

const next = { data: { markets: previous.data, robinhoodRows: [] }, updatedAt: 2 };
await writePersistedApiResponse('markets:v3', next);
assert.deepEqual(await readPersistedApiResponse('markets:v3', 'markets:v2'), next);
assert.deepEqual(await readPersistedApiResponse('markets:v2'), previous);
});
6 changes: 5 additions & 1 deletion src/components/DataPrefetcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@

import { usePathname } from 'next/navigation';
import { useMorphoWhitelistStatusQuery } from '@/hooks/queries/useMorphoWhitelistStatusQuery';
import { useRobinhoodTokensQuery } from '@/hooks/queries/useRobinhoodTokensQuery';
import { useTokensQuery } from '@/hooks/queries/useTokensQuery';
import { useDeferredQueryEnable } from '@/hooks/useDeferredQueryEnable';

function DataPrefetcherContent() {
useMorphoWhitelistStatusQuery();
useTokensQuery();
const { hasFetchedTokens, isError } = useTokensQuery();
const enableRobinhoodTokens = useDeferredQueryEnable(hasFetchedTokens || isError, true);
useRobinhoodTokensQuery(enableRobinhoodTokens);

return null;
}
Expand Down
62 changes: 58 additions & 4 deletions src/data-sources/monarch-api/markets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,22 @@ import type { CustomRpcUrls } from '@/stores/useCustomRpc';
import { getMarketIdentityKey } from '@/utils/market-identity';
import { isMarketRegistryEntryAllowed, normalizeMarketUniqueKey } from '@/utils/markets';
import { getMorphoAddress } from '@/utils/morpho';
import { isSupportedChain, type SupportedNetworks } from '@/utils/networks';
import { isSupportedChain, SupportedNetworks } from '@/utils/networks';
import { infoToKey } from '@/utils/tokens';
import type { ERC20Token } from '@/utils/tokens';
import {
resolveTokenInfos,
toRecognizedTokenInfo,
TokenMetadataUnavailableError,
type ResolvedTokenInfo,
type TokenAddressInput,
type TokenMetadataResolution,
} from '@/utils/tokenMetadata';
import type { Market, MarketWarning } from '@/utils/types';
import { UNRECOGNIZED_COLLATERAL, UNRECOGNIZED_LOAN } from '@/utils/warnings';
import { monarchGraphqlFetcher } from './fetchers';

type MonarchMarketRow = {
export type MonarchMarketRow = {
chainId: number;
marketId: string;
loanToken: string;
Expand Down Expand Up @@ -257,12 +259,63 @@ const mapMonarchMarketRows = async (
return { markets, tokenMetadataUnavailable };
};

const applyRecognizedTokens = (market: Market, tokenInfos: ReadonlyMap<string, ResolvedTokenInfo>): Market => {
const chainId = market.morphoBlue.chain.id;
const loanAsset = market.warnings.some(({ type }) => type === UNRECOGNIZED_LOAN.type)
? tokenInfos.get(infoToKey(market.loanAsset.address, chainId))?.token
: undefined;
const collateralAsset = market.warnings.some(({ type }) => type === UNRECOGNIZED_COLLATERAL.type)
? tokenInfos.get(infoToKey(market.collateralAsset.address, chainId))?.token
: undefined;
if (!loanAsset && !collateralAsset) return market;

return {
...market,
loanAsset: loanAsset ?? market.loanAsset,
collateralAsset: collateralAsset ?? market.collateralAsset,
warnings: market.warnings.filter(
({ type }) => !(loanAsset && type === UNRECOGNIZED_LOAN.type) && !(collateralAsset && type === UNRECOGNIZED_COLLATERAL.type),
),
};
};

// Apply the optional catalog to the already-fetched registry rows.
export const mapNewlyRecognizedMarkets = (
rows: MonarchMarketRow[],
markets: Market[],
findToken: (address: string, chainId: number) => ERC20Token | undefined,
): Market[] => {
const tokenInfos = new Map<string, ResolvedTokenInfo>();
for (const { address, chainId } of getMarketTokenInputs(rows)) {
const key = infoToKey(address, chainId);
if (tokenInfos.has(key)) continue;
const token = findToken(address, chainId);
if (token) tokenInfos.set(key, toRecognizedTokenInfo(address, token));
}

const resolution = { tokenInfos, unavailableTokenKeys: new Set<string>() };
const marketsByKey = new Map(markets.map((market) => [getMarketIdentityKey(market.morphoBlue.chain.id, market.uniqueKey), market]));
let changed = false;
for (const row of rows) {
const marketId = normalizeMarketUniqueKey(row.marketId);
if (!marketId) continue;
const key = getMarketIdentityKey(row.chainId, marketId);
const existing = marketsByKey.get(key);
const market = existing ? applyRecognizedTokens(existing, tokenInfos) : mapMonarchMarketToMarket(row, resolution, marketsByKey);
if (market && market !== existing) {
marketsByKey.set(key, market);
changed = true;
}
}
return changed ? [...marketsByKey.values()] : markets;
};

// If `network` is omitted, this fetches the merged multi-chain market registry in one query path.
export const fetchMonarchMarkets = async (
network?: SupportedNetworks,
customRpcUrls: CustomRpcUrls = {},
options: MapMonarchMarketRowsOptions = {},
): Promise<MonarchMarketsResult> => {
): Promise<MonarchMarketsResult & { robinhoodRows: MonarchMarketRow[] }> => {
const query = buildEnvioMarketsPageQuery({
useChainIdFilter: network !== undefined,
});
Expand Down Expand Up @@ -290,7 +343,8 @@ export const fetchMonarchMarkets = async (
offset += rows.length;
}

return mapMonarchMarketRows(allRows, customRpcUrls, options);
const result = await mapMonarchMarketRows(allRows, customRpcUrls, options);
return { ...result, robinhoodRows: allRows.filter(({ chainId }) => chainId === SupportedNetworks.Robinhood) };
};

export const fetchMonarchMarket = async (
Expand Down
52 changes: 52 additions & 0 deletions src/data-sources/robinhood-api/assets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { z } from 'zod';
import { SupportedNetworks } from '@/utils/supported-networks';

const ROBINHOOD_ASSETS_URL = 'https://api.robinhood.com/rhj/assets';
const ROBINHOOD_ASSETS_TIMEOUT_MS = 8_000;

const addressSchema = z
.string()
.regex(/^0x[0-9a-f]{40}$/i)
.transform((address) => address.toLowerCase());
export const robinhoodStockTokensSchema = z.array(
z.object({
address: addressSchema,
symbol: z.string().trim().min(1),
decimals: z.number().int().min(0).max(255),
logoUrl: z.string().url().startsWith('https://'),
}),
);

type RobinhoodStockToken = z.infer<typeof robinhoodStockTokensSchema>[number];
const upstreamAssetSchema = z.object({
tokenSymbol: robinhoodStockTokensSchema.element.shape.symbol,
tokenDecimals: robinhoodStockTokensSchema.element.shape.decimals,
logoUrl: robinhoodStockTokensSchema.element.shape.logoUrl,
status: z.enum(['ASSET_STATUS_ACTIVE', 'ASSET_STATUS_INACTIVE', 'ASSET_STATUS_UNSPECIFIED']),
deployments: z.array(z.object({ contractAddress: addressSchema, chainId: z.number().int() })),
});
const upstreamSchema = z.object({ assets: z.array(upstreamAssetSchema) });

/** Returns canonical active Robinhood Chain deployments. Request failures and malformed catalogs reject. */
export async function fetchRobinhoodStockTokens(): Promise<RobinhoodStockToken[]> {
const response = await fetch(ROBINHOOD_ASSETS_URL, {
credentials: 'omit',
cache: 'no-store',
signal: AbortSignal.timeout(ROBINHOOD_ASSETS_TIMEOUT_MS),
});
if (!response.ok) throw new Error(`Robinhood Stock Token API returned ${response.status}.`);

const { assets } = upstreamSchema.parse(await response.json());
const tokens = new Map<string, RobinhoodStockToken>();
for (const { status, deployments, tokenSymbol, tokenDecimals, logoUrl } of assets) {
if (status !== 'ASSET_STATUS_ACTIVE') continue;

for (const { chainId, contractAddress } of deployments) {
if (chainId !== SupportedNetworks.Robinhood || tokens.has(contractAddress)) continue;
tokens.set(contractAddress, { address: contractAddress, symbol: tokenSymbol, decimals: tokenDecimals, logoUrl });
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still lets an empty catalog, or any partially malformed catalog with at least one valid row, return successfully. The route then caches the empty/truncated result for 30 minutes, so recognized stock markets can disappear instead of retaining the last complete catalog. Treat catalog-integrity failures as errors (at minimum an unexpected empty list; ideally malformed records too) so unstable_cache can preserve the last successful value.

if (tokens.size === 0) throw new Error('Robinhood Stock Token API returned no active Robinhood Chain tokens.');
return [...tokens.values()];
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export function MarketsTableActions({ onRefresh, isRefetching, isTableLoading, i
variant="ghost"
size="sm"
onClick={onRefresh}
aria-label="Refresh markets"
disabled={isTableLoading || shouldShowRefreshLoading}
className="text-secondary min-w-0 px-2"
>
Expand Down
3 changes: 1 addition & 2 deletions src/features/markets/markets-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,7 @@ export default function Markets() {
}, []);

const handleRefresh = useCallback(async () => {
const result = await refetch();
if (result.isSuccess && !result.data.tokenMetadataUnavailable) {
if (await refetch()) {
toast.success('Markets refreshed', 'Markets refreshed successfully');
}
}, [refetch, toast]);
Expand Down
Loading