Skip to content

feat: optimize rebalance modal#145

Merged
antoncoding merged 3 commits intomasterfrom
opt/rebalance
May 18, 2025
Merged

feat: optimize rebalance modal#145
antoncoding merged 3 commits intomasterfrom
opt/rebalance

Conversation

@antoncoding
Copy link
Copy Markdown
Owner

@antoncoding antoncoding commented May 18, 2025

Summary by CodeRabbit

  • New Features

    • Added sorting functionality to the "toMarkets" table, allowing users to sort by APY, Total Supply, and LLTV.
    • Introduced star indicators for markets and user supply icons in the "toMarkets" table.
    • Added a new hook for managing starred markets, enabling users to star or unstar markets with persistent storage and notifications.
  • UI Improvements

    • Merged collateral and LLTV columns in market tables, with improved display and symbol truncation.
    • Updated badge and input border styles for a more consistent and modern appearance.
    • Enhanced max amount calculation and button disabling logic in "fromMarkets" for better accuracy and clarity.

@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented May 18, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
monarch ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 18, 2025 5:56am

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 18, 2025

📝 Walkthrough

Walkthrough

Starred market management is refactored to use a new useStaredMarkets hook, removing local state and handlers from the Markets component. The "toMarkets" table in FromAndToMarkets gains sorting and improved UI, with merged columns and new icons. Badge and border styles are updated in related components.

Changes

File(s) Change Summary
app/markets/components/markets.tsx Refactored starred market logic to use the new useStaredMarkets hook, removing local state and callbacks for starring/un-starring.
src/hooks/useStaredMarkets.ts Added a new hook for managing starred market IDs with local storage persistence and toast notifications.
app/positions/components/FromAndToMarkets.tsx Added sorting to the "toMarkets" table, merged collateral and LLTV columns, added star and user icons, improved max amount logic, and introduced a SortableHeader component.
app/positions/components/MarketBadge.tsx Updated badge styling: changed border radius and color scheme from orange to gray.
app/positions/components/RebalanceActionInput.tsx Changed border style from dashed/primary to solid/gray for the main container.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MarketsComponent
    participant useStaredMarkets (Hook)
    participant LocalStorage
    participant Toast

    User->>MarketsComponent: Clicks star/unstar
    MarketsComponent->>useStaredMarkets: Calls starMarket/unstarMarket
    useStaredMarkets->>LocalStorage: Read/update starred IDs
    useStaredMarkets->>Toast: Show notification
    useStaredMarkets-->>MarketsComponent: Return updated IDs
Loading
sequenceDiagram
    participant User
    participant FromAndToMarkets
    participant SortableHeader

    User->>SortableHeader: Click column header
    SortableHeader->>FromAndToMarkets: Trigger sort state update
    FromAndToMarkets->>FromAndToMarkets: Sort toMarkets data
    FromAndToMarkets-->>User: Render sorted table
Loading

Possibly related PRs

  • antoncoding/monarch#81: Introduces a MarketsProvider context and changes to market data fetching, which overlaps with this PR's refactor of market state management in the Markets component.

Poem

A hook for stars, a badge less bold,
Sorting tables, stories told.
Borders shift from dashed to gray,
Markets shine in a brand new way.
Click, sort, and see at last—
Refactor done, the old surpassed!

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Docstrings were successfully generated. (🔄 Check again to generate docstrings again)- [ ] Create PR with Unit Tests
  • Commit Unit Tests in branch opt/rebalance
  • Post Copyable Unit Tests in Comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

🧹 Nitpick comments (3)
app/positions/components/FromAndToMarkets.tsx (3)

62-86: Add minimal a11y metadata to sortable headers

<th>s change order but screen-readers get no hint.
Setting aria-sort when isSorted is true adds almost no cost and keeps the component accessible.

-  return (
-    <th
-      className={`${className} cursor-pointer hover:text-primary-500`}
-      onClick={() => onClick(column)}
-    >
+  return (
+    <th
+      className={`${className} cursor-pointer hover:text-primary-500`}
+      onClick={() => onClick(column)}
+      {...(isSorted && { 'aria-sort': currentSortDirection === 1 ? 'ascending' : 'descending' })}
+    >

111-118: Use functional updater to avoid stale state on rapid clicks

setToSortDirection(toSortDirection * -1) closes over the old value; two fast clicks can race and leave the direction unchanged.
A functional update is immune to this.

-    if (toSortColumn === column) {
-      setToSortDirection(toSortDirection * -1);
+    if (toSortColumn === column) {
+      setToSortDirection((d) => d * -1);

134-166: Minor: avoid repeated BigInt conversions in sort

BigInt(a.state.supplyAssets) runs for every comparison. Caching once per element keeps the sort O(n log n) but halves the constant factor.

-    let sorted = [...filteredToMarkets];
+    const sorted = filteredToMarkets.map((m) => ({
+      ...m,
+      supplyAssetsBig: BigInt(m.state.supplyAssets),
+      lltvBig: BigInt(m.lltv),
+    }));

…and use the pre-computed fields in the comparator.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2a43280 and 89338ef.

📒 Files selected for processing (5)
  • app/markets/components/markets.tsx (2 hunks)
  • app/positions/components/FromAndToMarkets.tsx (8 hunks)
  • app/positions/components/MarketBadge.tsx (1 hunks)
  • app/positions/components/RebalanceActionInput.tsx (1 hunks)
  • src/hooks/useStaredMarkets.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
app/markets/components/markets.tsx (1)
src/hooks/useStaredMarkets.ts (1)
  • useStaredMarkets (16-45)
src/hooks/useStaredMarkets.ts (1)
src/hooks/useStyledToast.tsx (1)
  • useStyledToast (6-20)
app/positions/components/FromAndToMarkets.tsx (6)
src/hooks/useStaredMarkets.ts (1)
  • useStaredMarkets (16-45)
app/positions/components/RebalanceModal.tsx (1)
  • PER_PAGE (27-27)
src/components/TokenIcon.tsx (1)
  • TokenIcon (15-52)
src/utils/external.ts (1)
  • getAssetURL (8-17)
src/components/common/Button.tsx (1)
  • Button (4-53)
src/components/TooltipContent.tsx (1)
  • TooltipContent (12-35)
🔇 Additional comments (10)
src/hooks/useStaredMarkets.ts (5)

6-14: Well-implemented initialization function with error handling

The getInitialStaredMarkets helper handles localStorage initialization properly with good error handling for JSON parsing failures.


16-19: Good state initialization and hook structure

The hook properly initializes state from localStorage and uses the styled toast hook. Clean implementation.


20-30: Proper implementation of the star functionality

The starMarket function:

  • Prevents redundant operations with an early return
  • Updates state and synchronizes with localStorage
  • Provides user feedback through toast notifications
  • Uses proper dependency management with useCallback

32-42: Proper implementation of the unstar functionality

The unstarMarket function correctly handles removal from starred markets with the same good practices as the star function.


44-45: Clean hook interface

The hook exposes a simple, intuitive API with all necessary functionality.

app/positions/components/RebalanceActionInput.tsx (1)

33-33: Improved border styling for better visual consistency

The border styling change from a dashed primary border to a solid gray border with dark mode support creates better visual harmony with other UI components.

app/positions/components/MarketBadge.tsx (1)

15-15: Enhanced badge styling for visual consistency

The badge styling changes (rounded-md instead of rounded-full, gray tones instead of orange) create a more neutral and consistent appearance across the application.

app/markets/components/markets.tsx (2)

18-18: Good extraction of starred markets functionality

Adding the import for the new hook centralizes this functionality.


53-53: Effective implementation of the hook

Successfully replaced local state management with the centralized hook, improving code organization and reusability.

app/positions/components/FromAndToMarkets.tsx (1)

350-370: Pagination: controlled vs uncontrolled prop mismatch

from table uses page, the to table uses initialPage.
With sorting or external page resets, Pagination won’t update because initialPage is only read once.

-                initialPage={toPagination.currentPage}
+                page={toPagination.currentPage}

Comment on lines +290 to 298
isDisabled={maxTransferableAmount <= 0n}
onClick={(e) => {
e.stopPropagation();
onFromMarketSelect(marketPosition.market.uniqueKey);
const remainingAmount =
BigInt(marketPosition.state.supplyAssets) +
BigInt(marketPosition.pendingDelta);
if (remainingAmount > 0n) {
if (maxTransferableAmount > 0n) {
onSelectMax?.(
marketPosition.market.uniqueKey,
Number(remainingAmount),
Number(maxTransferableAmount),
);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

BigInt → Number may lose precision for large token amounts

Number(maxTransferableAmount) silently rounds once the value exceeds 2⁵³-1.
Pass the bigint (or a string) to onSelectMax instead.

-                                  Number(maxTransferableAmount),
+                                  maxTransferableAmount, // keep as bigint

If the callback expects a number, consider formatUnits before converting so the value fits inside JS safe range.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
isDisabled={maxTransferableAmount <= 0n}
onClick={(e) => {
e.stopPropagation();
onFromMarketSelect(marketPosition.market.uniqueKey);
const remainingAmount =
BigInt(marketPosition.state.supplyAssets) +
BigInt(marketPosition.pendingDelta);
if (remainingAmount > 0n) {
if (maxTransferableAmount > 0n) {
onSelectMax?.(
marketPosition.market.uniqueKey,
Number(remainingAmount),
Number(maxTransferableAmount),
);
isDisabled={maxTransferableAmount <= 0n}
onClick={(e) => {
e.stopPropagation();
onFromMarketSelect(marketPosition.market.uniqueKey);
if (maxTransferableAmount > 0n) {
onSelectMax?.(
marketPosition.market.uniqueKey,
maxTransferableAmount, // keep as bigint
);
🤖 Prompt for AI Agents
In app/positions/components/FromAndToMarkets.tsx around lines 290 to 298, the
code converts a bigint maxTransferableAmount to a Number, which can lose
precision for large values. To fix this, pass maxTransferableAmount as a bigint
or convert it to a string before passing to onSelectMax. If onSelectMax requires
a number, use a formatting function like formatUnits to convert the bigint into
a safe numeric range before passing it.

coderabbitai Bot added a commit that referenced this pull request May 18, 2025
Docstrings generation was requested by @antoncoding.

* #145 (comment)

The following files were modified:

* `app/markets/components/markets.tsx`
* `app/positions/components/FromAndToMarkets.tsx`
* `app/positions/components/MarketBadge.tsx`
* `app/positions/components/RebalanceActionInput.tsx`
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 18, 2025

Note

Generated docstrings for this pull request at #146

@antoncoding antoncoding merged commit c303bc7 into master May 18, 2025
4 checks passed
@antoncoding antoncoding deleted the opt/rebalance branch May 18, 2025 05:59
@coderabbitai coderabbitai Bot mentioned this pull request Aug 19, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Nov 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant