Skip to content

feat: pie chart and concentration chart#302

Merged
antoncoding merged 7 commits intomasterfrom
feat/charts-refactoring
Jan 15, 2026
Merged

feat: pie chart and concentration chart#302
antoncoding merged 7 commits intomasterfrom
feat/charts-refactoring

Conversation

@antoncoding
Copy link
Copy Markdown
Owner

@antoncoding antoncoding commented Jan 15, 2026

  • suppliers and borrowers pie chart
  • concentration chart
  • collateral at risk

Additional

  • memorize user tab choice

Summary by CodeRabbit

  • New Features

    • Added supplier and borrower pie charts, concentration and collateral-at-risk visualizations to Market Details.
    • Introduced a new Trend tab and persistent tab preference for market details.
    • Added hooks to fetch all market suppliers/borrowers and integrated them into charts and summaries.
    • Charts include interactive legends, tooltips, expand/collapse for “Other” segments, and loading/empty states.
  • Chores

    • Added palette and risk color constants for chart theming.
  • Behavior

    • Market position queries now exclude zero-share entries by default.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented Jan 15, 2026

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

Project Deployment Review Updated (UTC)
monarch Ready Ready Preview, Comment Jan 15, 2026 8:58am

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jan 15, 2026

📝 Walkthrough

Walkthrough

Adds four new market-detail charts (borrowers/suppliers pie charts, concentration chart, collateral-at-risk area chart), new hooks to fetch all market positions, a persistent tab preference store, and small defaults/parameter changes to existing position hooks and market view integration.

Changes

Cohort / File(s) Summary
Chart Colors
src/constants/chartColors.ts
Added PIE_COLORS (10-color readonly array) and RISK_COLORS (stroke + gradient config) exports.
Pie Charts
src/features/market-detail/components/charts/borrowers-pie-chart.tsx, src/features/market-detail/components/charts/suppliers-pie-chart.tsx
New client components rendering top‑8 segments + expandable “Other” bucket, custom tooltips/legend, loading and empty states, token icons and address/name resolution. Review big-int value math and click-to-expand behavior.
Risk & Concentration Charts
src/features/market-detail/components/charts/collateral-at-risk-chart.tsx, src/features/market-detail/components/charts/concentration-chart.tsx
New Area/Composed charts: collateral-at-risk computes cumulative debt across price-drop thresholds and interpolates risk metrics; concentration chart computes cumulative vs ideal distributions and top‑N metrics. Check interpolation, gradient defs, and tooltip math.
Market View Integration
src/features/market-detail/market-view.tsx
Replaced positions tables with chart layouts (pie + concentration + collateral-at-risk), wired new hooks and concentration computations, added controlled tab state via new preferences store, adjusted minShares initialization. Verify tab state persistence and new data loading paths.
Position Fetch Hooks
src/hooks/useAllMarketPositions.ts
New hooks useAllMarketBorrowers and useAllMarketSuppliers fetching up to 1000 positions (Morpho API preferred, Subgraph fallback). Returns normalized items, totalCount, loading/error. Confirm API fallbacks and pagination keys.
Hook Defaults / Filtering
src/hooks/useMarketBorrowers.ts, src/hooks/useMarketSuppliers.ts
Default minShares changed from '0' to '1'; introduced effectiveMinShares to ensure zeros are excluded across query keys, API calls, and prefetch. Review potential effect on existing pagination and UIs.
Preferences Store
src/stores/useMarketDetailPreferences.ts
New Zustand persistent store useMarketDetailPreferences with selectedTab (`'trend'

Sequence Diagram(s)

sequenceDiagram
  actor User
  participant MarketView
  participant Hooks as useAllMarketPositions
  participant API as Morpho/Subgraph
  participant Charts as Pie/Concentration/Collateral

  User->>MarketView: open market detail (selects tab)
  MarketView->>Hooks: request borrowers & suppliers (marketId, network)
  Hooks->>API: fetch positions (Morpho preferred, fallback to Subgraph)
  API-->>Hooks: return items & totalCount
  Hooks-->>MarketView: provide normalized data
  MarketView->>Charts: pass data + oraclePrice
  Charts->>Charts: compute segments/metrics and render
  User->>Charts: click "Other" segment
  Charts->>Charts: toggle expansion and show detailed list
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main additions: new pie chart components (suppliers and borrowers) and a concentration chart visualization.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/charts-refactoring

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 feature request Specific feature ready to be implemented ui User interface labels Jan 15, 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: 1

🤖 Fix all issues with AI agents
In `@src/features/market-detail/components/charts/collateral-at-risk-chart.tsx`:
- Around line 51-57: The collateral-to-loan value calculation in
collateralValueInLoan (used to compute currentLTV) ignores token decimal
differences; update the formula in collateral-at-risk-chart.tsx to multiply by
BigInt(10 ** market.collateralAsset.decimals) and divide by BigInt(10 **
market.loanAsset.decimals) along with the existing 10**36 scaling (i.e., adjust
the (collateral * oraclePrice) term to account for
market.collateralAsset.decimals and market.loanAsset.decimals). Apply the same
decimal-adjusted calculation to all LTV/debt conversions in borrowers-table.tsx,
borrowers-pie-chart.tsx and the borrow modal components where
collateralValueInLoan, currentLTV or similar computed values appear (search for
collateralValueInLoan, currentLTV, debtValue, and any direct (collateral *
oraclePrice) expressions) so all LTV math consistently uses
market.collateralAsset.decimals and market.loanAsset.decimals.
🧹 Nitpick comments (1)
src/features/market-detail/components/charts/concentration-chart.tsx (1)

33-34: Minor: Redundant filter condition.

The condition p.percentage > 0 && p.percentage >= MIN_PERCENT_THRESHOLD is redundant since MIN_PERCENT_THRESHOLD is 0.1. The > 0 check is always satisfied when >= 0.1.

Suggested simplification
-    const meaningful = sorted.filter((p) => p.percentage > 0 && p.percentage >= MIN_PERCENT_THRESHOLD);
+    const meaningful = sorted.filter((p) => p.percentage >= MIN_PERCENT_THRESHOLD);
📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3145e72 and b3a3813.

📒 Files selected for processing (3)
  • src/features/market-detail/components/charts/collateral-at-risk-chart.tsx
  • src/features/market-detail/components/charts/concentration-chart.tsx
  • src/features/market-detail/market-view.tsx
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2024-11-25T09:39:42.148Z
Learnt from: antoncoding
Repo: antoncoding/monarch PR: 87
File: app/home/HomePage.tsx:17-39
Timestamp: 2024-11-25T09:39:42.148Z
Learning: In `app/home/HomePage.tsx`, the `useEffect` hook depends on `[showCustomized]` because changing `showCustomized` triggers updates to the yield and risk terms.

Applied to files:

  • src/features/market-detail/components/charts/collateral-at-risk-chart.tsx
  • src/features/market-detail/market-view.tsx
📚 Learning: 2024-10-12T09:23:16.495Z
Learnt from: antoncoding
Repo: antoncoding/monarch PR: 63
File: app/markets/components/MarketRowDetail.tsx:49-52
Timestamp: 2024-10-12T09:23:16.495Z
Learning: When rendering oracle feeds in `ExpandedMarketDetail` (`app/markets/components/MarketRowDetail.tsx`), prefer explicit rendering over iterating keys when dealing with a small number of feeds.

Applied to files:

  • src/features/market-detail/market-view.tsx
🧬 Code graph analysis (1)
src/features/market-detail/components/charts/concentration-chart.tsx (2)
src/components/ui/spinner.tsx (1)
  • Spinner (22-58)
src/features/market-detail/components/charts/chart-utils.tsx (2)
  • ChartGradients (17-43)
  • chartTooltipCursor (124-128)
🔇 Additional comments (4)
src/features/market-detail/components/charts/collateral-at-risk-chart.tsx (1)

1-241: Overall implementation looks good.

The chart correctly visualizes collateral at risk with appropriate handling of edge cases, loading states, and a clear UI. The step function approach for cumulative debt and the risk metrics summary are well-implemented.

src/features/market-detail/market-view.tsx (2)

138-163: Inconsistent fallback values.

When market is undefined, scaledMinSupplierShares and scaledMinBorrowerShares return '1' (lines 148, 161). But when market exists and input is empty, convertAssetToShares returns '0'. This creates inconsistent filtering behavior during initial load vs after market loads.

Was the '1' fallback intentional to filter dust positions, or should it be '0' for consistency?


358-396: Charts integration looks good.

The layout is well-structured with responsive grid columns. Data flows correctly from the hooks through the memoized concentration data to the chart components.

src/features/market-detail/components/charts/concentration-chart.tsx (1)

1-235: Clean implementation overall.

The concentration chart handles multiple edge cases well: loading, empty data, and filtered-out positions. The Lorenz curve comparison with ideal distribution is a nice touch for visualizing concentration.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment on lines +51 to +57
// Calculate collateral value in loan asset terms
const collateralValueInLoan = (collateral * oraclePrice) / BigInt(10 ** 36);
if (collateralValueInLoan === 0n) return null;

// Calculate current LTV as decimal
const currentLTV = Number(borrowAssets) / Number(collateralValueInLoan);
const debtValue = Number(formatUnits(borrowAssets, market.loanAsset.decimals));
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot Jan 15, 2026

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for oracle price usage with decimal adjustments
rg -n "oraclePrice.*10\s*\*\*" --type=ts --type=tsx -B2 -A2

Repository: antoncoding/monarch

Length of output: 90


🏁 Script executed:

#!/bin/bash
# Search for ORACLE_PRICE_SCALE or similar constants
rg -n "ORACLE_PRICE_SCALE|36.*decimal|oracle.*scale" --type=ts --type=tsx -i

Repository: antoncoding/monarch

Length of output: 90


🏁 Script executed:

#!/bin/bash
# Look at market-view.tsx to understand the oracle price adjustment
fd "market-view.tsx" --type=f

Repository: antoncoding/monarch

Length of output: 192


🏁 Script executed:

#!/bin/bash
# Search for how collateral value is calculated in the codebase
rg -n "collateralValue|collateral.*oraclePrice" --type=ts --type=tsx -B2 -A2

Repository: antoncoding/monarch

Length of output: 90


🏁 Script executed:

#!/bin/bash
# Search for oracle price usage with decimal adjustments (broader search)
rg -n "oraclePrice.*10\s*\*\*" -B2 -A2

Repository: antoncoding/monarch

Length of output: 4711


🏁 Script executed:

#!/bin/bash
# Look at the market-view.tsx in market-detail folder around line 123
cat -n src/features/market-detail/market-view.tsx | sed -n '110,140p'

Repository: antoncoding/monarch

Length of output: 1469


🏁 Script executed:

#!/bin/bash
# Check collateral-at-risk-chart.tsx to see full context
cat -n src/features/market-detail/components/charts/collateral-at-risk-chart.tsx | sed -n '1,80p'

Repository: antoncoding/monarch

Length of output: 4030


🏁 Script executed:

#!/bin/bash
# Search for how the oracle price scale is defined or used
rg -n "36|ORACLE" | grep -i "scale\|decimal\|price"

Repository: antoncoding/monarch

Length of output: 50375


🏁 Script executed:

#!/bin/bash
# Look at borrowers-table.tsx around line 54 to see the full context
cat -n src/features/market-detail/components/borrowers-table.tsx | sed -n '45,75p'

Repository: antoncoding/monarch

Length of output: 1303


🏁 Script executed:

#!/bin/bash
# Check if there are any comments or documentation about decimal adjustment
rg -n "collateralAsset.decimals|loanAsset.decimals" -B2 -A2

Repository: antoncoding/monarch

Length of output: 50375


Collateral value calculation needs decimal adjustment for different asset decimals.

The formula (collateral * oraclePrice) / BigInt(10 ** 36) doesn't account for differences between collateral and loan asset decimals. This is inconsistent with how market-view.tsx handles the same oracle price:

const adjusted = (oraclePrice * BigInt(10 ** market.collateralAsset.decimals)) / BigInt(10 ** market.loanAsset.decimals);

The comment in borrowers-table.tsx (line 53) acknowledges this: "oraclePrice is scaled by 10^36, need to adjust for token decimals"—but the adjustment is missing from that file and others. Update the calculation to:

const collateralValueInLoan = (collateral * oraclePrice * BigInt(10 ** market.collateralAsset.decimals)) / (BigInt(10 ** 36) * BigInt(10 ** market.loanAsset.decimals));

Apply this fix to all LTV calculations in collateral-at-risk-chart.tsx, borrowers-table.tsx, borrowers-pie-chart.tsx, and the borrow modals.

🤖 Prompt for AI Agents
In `@src/features/market-detail/components/charts/collateral-at-risk-chart.tsx`
around lines 51 - 57, The collateral-to-loan value calculation in
collateralValueInLoan (used to compute currentLTV) ignores token decimal
differences; update the formula in collateral-at-risk-chart.tsx to multiply by
BigInt(10 ** market.collateralAsset.decimals) and divide by BigInt(10 **
market.loanAsset.decimals) along with the existing 10**36 scaling (i.e., adjust
the (collateral * oraclePrice) term to account for
market.collateralAsset.decimals and market.loanAsset.decimals). Apply the same
decimal-adjusted calculation to all LTV/debt conversions in borrowers-table.tsx,
borrowers-pie-chart.tsx and the borrow modal components where
collateralValueInLoan, currentLTV or similar computed values appear (search for
collateralValueInLoan, currentLTV, debtValue, and any direct (collateral *
oraclePrice) expressions) so all LTV math consistently uses
market.collateralAsset.decimals and market.loanAsset.decimals.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

this is incorrect. oracle.price already absorb the decimals.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for oracle price documentation and comments about decimal handling
rg -n "oracle.*price.*decimal|oracle.*absorb|10\s*\*\*\s*36" -i -B2 -A2

# Look for oracle price type definitions or interfaces
rg -n "oraclePrice.*type|interface.*oracle" -i -B2 -A2

# Find where oracle price is fetched or defined
rg -n "getOraclePrice|fetchOracle|oracle.*=.*price" -B3 -A3

Length of output: 9835


@antoncoding You're absolutely right, and I apologize for the incorrect review comment.

Looking at the codebase, the oracle price in Morpho is scaled by 10^36 and already incorporates the decimal differences between collateral and loan assets. The formula (collateral * oraclePrice) / BigInt(10 ** 36) correctly converts collateral value to loan asset terms without needing additional decimal adjustments.

The decimal adjustment in market-view.tsx line 123 is specifically for display purposes—to format the oracle price as a human-readable ratio—not for LTV calculations. The comment in borrowers-table.tsx line 53 ("need to adjust for token decimals") is misleading since the code correctly doesn't perform that adjustment.

The current implementation across all files is correct as-is.


✏️ Learnings added
Learnt from: antoncoding
Repo: antoncoding/monarch PR: 302
File: src/features/market-detail/components/charts/collateral-at-risk-chart.tsx:51-57
Timestamp: 2026-01-15T09:30:41.378Z
Learning: In Morpho Blue, the oracle price (oraclePrice) is scaled by 10^36 and already incorporates decimal differences between collateral and loan assets. When calculating collateral value in loan asset terms, use `(collateral * oraclePrice) / BigInt(10 ** 36)` without additional decimal adjustments. The decimal adjustment in market-view.tsx is only for display formatting, not for LTV/value calculations.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: antoncoding
Repo: antoncoding/monarch PR: 87
File: app/home/HomePage.tsx:17-39
Timestamp: 2024-11-25T09:39:42.148Z
Learning: In `app/home/HomePage.tsx`, the `useEffect` hook depends on `[showCustomized]` because changing `showCustomized` triggers updates to the yield and risk terms.

@antoncoding antoncoding merged commit 1d4be0a into master Jan 15, 2026
4 checks passed
@antoncoding antoncoding deleted the feat/charts-refactoring branch January 15, 2026 09:29
This was referenced Jan 19, 2026
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 ui User interface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant