Skip to content

refactor: api#496

Merged
antoncoding merged 3 commits intomasterfrom
refactor/api
Apr 13, 2026
Merged

refactor: api#496
antoncoding merged 3 commits intomasterfrom
refactor/api

Conversation

@antoncoding
Copy link
Copy Markdown
Owner

@antoncoding antoncoding commented Apr 13, 2026

Summary by CodeRabbit

  • Refactor

    • Transitioned market metrics and token metadata resolution to an external data API integration.
    • Extended market metrics cache refresh interval from 5 to 15 minutes.
  • Chores

    • Updated image optimization configuration with increased cache TTL.
    • Restricted remote image sources to Google Cloud Storage.

@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented Apr 13, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
monarch Ready Ready Preview, Comment Apr 13, 2026 4:49pm

Request Review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 13, 2026

Warning

Rate limit exceeded

@antoncoding has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 32 minutes and 46 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 32 minutes and 46 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 6d92e4d6-040c-4f79-adb3-98b14019fc57

📥 Commits

Reviewing files that changed from the base of the PR and between ad4e73d and a8dce33.

📒 Files selected for processing (1)
  • next.config.js
📝 Walkthrough

Walkthrough

Replaces internal API proxy routes (/api/monarch/metrics, /api/token-metadata) with direct external API integration using a new NEXT_PUBLIC_DATA_API_BASE_URL environment variable. Removes Monarch-specific utilities and server-side caching, updates market metrics refresh cadence from 5 to 15 minutes, and adjusts image optimization settings.

Changes

Cohort / File(s) Summary
Environment & Configuration
.env.local.example, src/utils/urls.ts, next.config.js
Added NEXT_PUBLIC_DATA_API_BASE_URL environment variable; created DATA_API_BASE_URL constant with trailing-slash trimming; restricted image remote patterns to Google Cloud Storage and set 31-day cache TTL.
API Route Removal
app/api/monarch/metrics/route.ts, app/api/token-metadata/route.ts, app/api/monarch/utils.ts
Removed internal proxy routes and supporting utilities that forwarded requests to Monarch metrics and token metadata endpoints.
Token Metadata Migration
src/utils/tokenMetadata.ts, src/server/token-metadata-cache.ts
Removed server-side caching layer; updated fetching to batch token requests (size 200) and POST directly to external API endpoint (/v1/tokens/metadata) via DATA_API_BASE_URL with parallel batch processing.
Market Metrics Client
src/hooks/queries/useMarketMetricsQuery.ts
Added dynamic URL builder using DATA_API_BASE_URL; switched from hardcoded /api/monarch/metrics to external endpoint (/v1/markets/metrics); increased cache/revalidation interval from 5 to 15 minutes.
UI Rendering
src/features/markets/components/filters/asset-filter.tsx
Added unoptimized prop to Next.js Image component for token icons.
Documentation
docs/TECHNICAL_OVERVIEW.md
Updated references from /api/monarch/metrics to external data API /v1/markets/metrics endpoint.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

feature request

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'refactor: api' is too vague to clearly convey the main changes, which involve removing Monarch API integrations and switching to an external data API. Use a more specific title like 'refactor: replace Monarch metrics/token APIs with external data API' to clarify the core change.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/api

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot added the feature request Specific feature ready to be implemented label Apr 13, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
src/utils/tokenMetadata.ts (1)

109-123: Normalize deserialized addresses before calling infoToKey.

Line 117 is the only key path here that skips normalizeAddress(). If the data API returns checksum-cased chainId:address keys, later lookups miss and the corresponding market gets dropped.

♻️ Proposed fix
-        if (Number.isInteger(chainId) && address) {
-          return [infoToKey(address, chainId), resolvedTokenInfo] satisfies [string, ResolvedTokenInfo];
+        if (Number.isInteger(chainId) && address) {
+          return [infoToKey(normalizeAddress(address), chainId as SupportedNetworks), resolvedTokenInfo] satisfies [string, ResolvedTokenInfo];
         }
As per coding guidelines: All market/token/route identity checks must be chain-scoped using canonical identifiers (chainId + market.uniqueKey or chainId + address).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/utils/tokenMetadata.ts` around lines 109 - 123,
deserializeResolvedTokenInfos currently calls infoToKey(address, chainId) with
the raw address when splitting keys like "chainId:address", which can be
checksum-cased and break later lookups; update the branch inside
deserializeResolvedTokenInfos to normalize the address (using normalizeAddress)
before calling infoToKey so keys are stored in the canonical, chain-scoped form;
ensure you import/avail normalizeAddress and use it for the [chainIdRaw,
address] path prior to infoToKey(address, chainId).
src/hooks/queries/useMarketMetricsQuery.ts (1)

112-124: Wire the query cancellation signal into the new fetch path.

This direct data-API version can spawn several page requests, but queryFn never passes TanStack Query's signal down to fetch(). If the view unmounts or params change mid-flight, those requests keep running for no reason.

♻️ Proposed fix
-const fetchMarketMetricsPage = async (params: MarketMetricsParams, limit: number, offset: number): Promise<MarketMetricsResponse> => {
+const fetchMarketMetricsPage = async (
+  params: MarketMetricsParams,
+  limit: number,
+  offset: number,
+  signal?: AbortSignal,
+): Promise<MarketMetricsResponse> => {
@@
-  const response = await fetch(getMarketMetricsClientUrl(searchParams));
+  const response = await fetch(getMarketMetricsClientUrl(searchParams), { signal });
@@
-const fetchAllMarketMetrics = async (params: MarketMetricsParams): Promise<MarketMetricsResponse> => {
+const fetchAllMarketMetrics = async (params: MarketMetricsParams, signal?: AbortSignal): Promise<MarketMetricsResponse> => {
@@
-  const firstPage = await fetchMarketMetricsPage(params, PAGE_SIZE, 0);
+  const firstPage = await fetchMarketMetricsPage(params, PAGE_SIZE, 0, signal);
@@
-    pagePromises.push(fetchMarketMetricsPage(params, PAGE_SIZE, i * PAGE_SIZE));
+    pagePromises.push(fetchMarketMetricsPage(params, PAGE_SIZE, i * PAGE_SIZE, signal));
@@
-    queryFn: () => fetchAllMarketMetrics({ chainId, sortBy, sortOrder }),
+    queryFn: ({ signal }) => fetchAllMarketMetrics({ chainId, sortBy, sortOrder }, signal),

Also applies to: 194-198

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/queries/useMarketMetricsQuery.ts` around lines 112 - 124,
fetchMarketMetricsPage currently calls fetch(getMarketMetricsClientUrl(...))
without an AbortSignal; update its signature to accept an optional signal:
(params: MarketMetricsParams, limit: number, offset: number, signal?:
AbortSignal), and pass that signal into fetch as
fetch(getMarketMetricsClientUrl(searchParams), { signal }); then update the
caller (the queryFn that receives TanStack Query's signal) to forward its signal
into fetchMarketMetricsPage so in-flight page requests are aborted when the
query is cancelled; apply the identical change to the other page-fetching
function in this module that mirrors lines ~194-198.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.env.local.example:
- Around line 60-63: The README/example env note incorrectly says
NEXT_PUBLIC_DATA_API_BASE_URL is production-only; change the comment in
.env.local.example to state that NEXT_PUBLIC_DATA_API_BASE_URL is required for
any environment that renders markets (not just production) because
useMarketMetricsQuery and tokenMetadata resolution in
src/hooks/queries/useMarketMetricsQuery.ts and src/utils/tokenMetadata.ts will
throw if it's missing; update the explanatory copy to instruct developers to set
a valid base URL for metrics and token metadata in all local/dev/staging
environments that work with markets.

In `@docs/TECHNICAL_OVERVIEW.md`:
- Line 193: The docs still mix responsibilities between the new
/v1/markets/metrics endpoint and the older Monarch backend: update all remaining
references that call out "Monarch API" and "5 min stale" (e.g., the lines that
currently mention Monach API / 5 min stale) to point to /v1/markets/metrics
where market metrics live, and ensure admin stats remain documented under
useMonarchTransactions (remove any phrasing on Line 435 implying the metrics
endpoint owns admin stats). Search for and replace inconsistent mentions (e.g.,
"Monarch API", "5 min stale", "admin stats" phrasing) so the page consistently
shows /v1/markets/metrics as the market metrics backend and
useMonarchTransactions as the owner of admin transaction stats.

In `@src/utils/tokenMetadata.ts`:
- Around line 276-315: The current fetchResolvedUnknownTokenInfosFromServer
logic swallows failed batch fetches (Promise.allSettled + skip) which loses
token metadata instead of falling back; update
fetchResolvedUnknownTokenInfosFromServer to (1) track which token inputs failed
per-batch when a response is rejected, (2) after Promise.allSettled, build a
list of unresolved token addresses (use the same TokenAddressInput shape and
dedupeTokenInputs helper) and call a shared RPC resolution routine (e.g., a new
resolveTokensViaRpcMulticall that performs chain-scoped multicalls keyed by
canonical chainId+address and returns a Map<string, ResolvedTokenInfo>), (3)
merge the server-resolved Map (from deserializeResolvedTokenInfos) with the
RPC-resolved Map, preferring server values but using RPC for missing entries,
and (4) if any required token remains unresolved after RPC, throw (fail closed)
instead of returning incomplete results; apply the same fix to the similar block
referenced around lines 318-328 so both paths use the RPC fallback and propagate
failures rather than silently omitting tokens.

---

Nitpick comments:
In `@src/hooks/queries/useMarketMetricsQuery.ts`:
- Around line 112-124: fetchMarketMetricsPage currently calls
fetch(getMarketMetricsClientUrl(...)) without an AbortSignal; update its
signature to accept an optional signal: (params: MarketMetricsParams, limit:
number, offset: number, signal?: AbortSignal), and pass that signal into fetch
as fetch(getMarketMetricsClientUrl(searchParams), { signal }); then update the
caller (the queryFn that receives TanStack Query's signal) to forward its signal
into fetchMarketMetricsPage so in-flight page requests are aborted when the
query is cancelled; apply the identical change to the other page-fetching
function in this module that mirrors lines ~194-198.

In `@src/utils/tokenMetadata.ts`:
- Around line 109-123: deserializeResolvedTokenInfos currently calls
infoToKey(address, chainId) with the raw address when splitting keys like
"chainId:address", which can be checksum-cased and break later lookups; update
the branch inside deserializeResolvedTokenInfos to normalize the address (using
normalizeAddress) before calling infoToKey so keys are stored in the canonical,
chain-scoped form; ensure you import/avail normalizeAddress and use it for the
[chainIdRaw, address] path prior to infoToKey(address, chainId).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 690276d7-869b-4f4c-9974-5f14701eda59

📥 Commits

Reviewing files that changed from the base of the PR and between 4a375aa and ad4e73d.

📒 Files selected for processing (11)
  • .env.local.example
  • app/api/monarch/metrics/route.ts
  • app/api/monarch/utils.ts
  • app/api/token-metadata/route.ts
  • docs/TECHNICAL_OVERVIEW.md
  • next.config.js
  • src/features/markets/components/filters/asset-filter.tsx
  • src/hooks/queries/useMarketMetricsQuery.ts
  • src/server/token-metadata-cache.ts
  • src/utils/tokenMetadata.ts
  • src/utils/urls.ts
💤 Files with no reviewable changes (4)
  • app/api/token-metadata/route.ts
  • src/server/token-metadata-cache.ts
  • app/api/monarch/metrics/route.ts
  • app/api/monarch/utils.ts

Comment thread .env.local.example
Comment thread docs/TECHNICAL_OVERVIEW.md
Comment thread src/utils/tokenMetadata.ts
@antoncoding antoncoding merged commit 50be305 into master Apr 13, 2026
4 checks passed
@antoncoding antoncoding deleted the refactor/api branch April 13, 2026 16:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature request Specific feature ready to be implemented

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant