Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: only use 1 source wallet | memoize components that call balances #255

Merged
merged 4 commits into from
Feb 7, 2025

Conversation

chalabi2
Copy link
Collaborator

@chalabi2 chalabi2 commented Feb 7, 2025

This PR

  • reverts the omnibus change that supports connecting multiple chains with 1 wallet
  • memoizes the components that pass along the combinedBalances data from the bank page

Summary by CodeRabbit

  • Refactor
    • Enhanced UI performance by streamlining transaction components with improved rendering techniques.
    • Simplified wallet connection and token balance management for a more responsive and efficient user experience.
    • Reduced complexity by removing redundant interface elements, resulting in a cleaner and more maintainable design.
    • Updated handling of balances and props in key components to improve performance and reduce dependencies.
    • Removed unnecessary props related to Osmosis balances across multiple components for a more focused functionality.

Copy link
Contributor

coderabbitai bot commented Feb 7, 2025

Warning

Rate limit exceeded

@chalabi2 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 57 seconds before requesting another review.

⌛ 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.

📥 Commits

Reviewing files that changed from the base of the PR and between a085327 and 62ac1fa.

📒 Files selected for processing (2)
  • .github/workflows/build.yml (1 hunks)
  • components/groups/components/groupControls.tsx (0 hunks)

Walkthrough

The pull request refactors multiple components related to token transfers and wallet connections. Osmosis-specific props have been removed across several components, and component exports are now wrapped with React.memo. Memoization of the balances prop is introduced via useMemo for performance improvements. Additionally, the previous use of multiple chain management with useChains is replaced by the useChain hook for a simpler, single-chain approach in wallet connection handling and balance retrieval.

Changes

File(s) Change Summary
components/bank/components/sendBox.tsx, components/bank/components/tokenList.tsx, components/bank/modals/sendModal.tsx Removed Osmosis-related props; updated exports to use React.memo; introduced memoizedBalances using useMemo to optimize rendering.
components/bank/forms/ibcSendForm.tsx Eliminated Osmosis-specific props; integrated useChain for obtaining the offline signer; simplified fee estimation, balance filtering, and initial token selection logic.
components/react/modal.tsx, components/wallet.tsx, pages/bank.tsx Replaced useChains with useChain to streamline wallet connection management; updated balance retrieval to use the current wallet’s address directly.

Possibly related PRs

Suggested labels

bug, enhancement, render

Suggested reviewers

  • fmorency

Poem

Hop, skip, and code away,
I’m a rabbit celebrating changes today!
Memoized props and React.memo gleam,
Wallets and tokens flow like a dream.
With a twitch of my nose and a joyful bound,
I cheer these refactors with a happy sound!
🐰🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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
Contributor

@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: 0

🧹 Nitpick comments (6)
components/bank/forms/ibcSendForm.tsx (6)

82-84: Check error handling for hooking.
These lines correctly retrieve signer, tx, and fee estimation from the chosen chain, but consider adding fallback or error handling if the chain is unavailable or undefined.


89-89: Remove or replace console.log for production.
It’s best to switch to a logging mechanism or remove console logs to avoid exposing sensitive data in production.

-  console.log(balances);
+  // console.log(balances); // Remove or replace for production

91-91: Handle potential signer retrieval failures.
getOfflineSignerAmino might throw if the chain is not found or user rejects the wallet connection. Consider a try/catch or user feedback.


110-114: Optimize filter for repeated toLowerCase calls.
Filtering balances is straightforward, but repeatedly calling toLowerCase can be factored out for micro-performance gains if the lists or search terms are large.

const lowerCaseSearchTerm = searchTerm.toLowerCase();
return balances?.filter(token => {
  const displayName = token.metadata?.display ?? token.denom;
- return displayName.toLowerCase().includes(searchTerm.toLowerCase());
+ return displayName.toLowerCase().includes(lowerCaseSearchTerm);
});

122-122: Consider showing a loading indicator.
Returning null avoids rendering, but a small loader or user feedback might improve UX when balances are loading or no initial token is found.


216-216: Use a stricter type for user.
(user: { address: any }) is very broad. If possible, define a type with address: string to reduce potential runtime issues.

- addressList: userAddresses.map((user: { address: any }) => user.address),
+ type UserAddress = { address: string; chainID: string };
+ addressList: userAddresses.map((user: UserAddress) => user.address),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 02c576b and e60bfdb.

📒 Files selected for processing (7)
  • components/bank/components/sendBox.tsx (5 hunks)
  • components/bank/components/tokenList.tsx (4 hunks)
  • components/bank/forms/ibcSendForm.tsx (8 hunks)
  • components/bank/modals/sendModal.tsx (5 hunks)
  • components/react/modal.tsx (2 hunks)
  • components/wallet.tsx (2 hunks)
  • pages/bank.tsx (4 hunks)
🔇 Additional comments (23)
components/bank/forms/ibcSendForm.tsx (4)

38-38: Consider verifying chain existence.
When calling useChain(env.chain), ensure that env.chain is a valid ID recognized by @cosmos-kit. Otherwise, getOfflineSignerAmino may fail.


56-56: Clarify the isGroup prop usage.
Confirm that isGroup is properly passed in and used consistently. If it’s optional or toggles group logic, testing edge cases would be advisable.
[approve]


118-119: Ensure fallback for no tokens scenario.
This logic is sound; just confirm the UI or flow is acceptable when balances are empty or selectedDenom is not present.


198-207: Validate userAddresses structure.
Make sure chainID and address are valid. If user input can be manipulated, consider sanitizing or ensuring addresses are valid.

components/bank/modals/sendModal.tsx (5)

1-1: Check for side-effect imports.
useEffect and useMemo were added; ensure they are both necessary and keep your import list minimal and explicit.


22-22: Good use of React.memo.
Wrapping the component in React.memo helps prevent unnecessary re-renders, improving performance.


54-55: Memoize balances array.
Using memoizedBalances is a neat approach. Confirm that balances are not mutated elsewhere, which could break memoization.


95-95: Pass memoizedBalances to child.
This is consistent with the new changes. The child components can now skip re-renders when balances remains unchanged.


129-129: Ensure final export remains typed.
Returning null is valid for SSR checks. Wrapping the entire component with React.memo is correct.

components/bank/components/sendBox.tsx (6)

7-7: Avoid overshadowing React.
If other local variables named React are in use, ensure they're not overshadowed. Otherwise this import is standard practice.


17-17: React.memo for performance.
Wrapping SendBox with React.memo is a good improvement, preventing rerenders when props do not change.


68-68: Use useMemo for balances.
Good practice; helps with performance. Just confirm that the balances array is truly immutable to leverage memo effectively.


128-128: Correct usage of memoizedBalances.
Passing memoizedBalances to IbcSendForm helps ensure we don’t trigger excessive re-renders.


141-141: Consistent memo usage across child forms.
Same logic applies for SendForm. Confirm that references to balances are replaced or updated if we rely on reactivity.


156-156: Finalizing with memo export.
The file’s structure looks clean, and the new export with React.memo is consistent with your optimization approach.

components/bank/components/tokenList.tsx (2)

22-22: Good performance optimization using memoization!

The component is now memoized using React.memo and the balances prop is memoized using useMemo. This will prevent unnecessary re-renders when parent components update with the same balances data.

Also applies to: 84-84


223-223: Consistent usage of memoized value.

The memoized balances are correctly passed to the SendModal component, maintaining the performance optimization throughout the component tree.

components/wallet.tsx (2)

5-5: Good simplification of wallet connection handling!

The switch from useChains to useChain aligns with the single source wallet approach, making the code more focused and easier to maintain.

Also applies to: 40-40


95-98: Clean wallet state management.

Direct access to wallet properties through useChain simplifies the code by removing the need to manage multiple chain states.

pages/bank.tsx (2)

32-32: Good simplification of wallet state management!

Using useChain with a single chain name simplifies the code and aligns with the PR's objective of using a single source wallet.


34-34: Consistent address handling across hooks.

The wallet address is consistently obtained from the single chain and properly used across all hooks and child components.

Also applies to: 39-39, 89-89, 230-230, 242-242

components/react/modal.tsx (2)

95-98: Good simplification of wallet repository access!

Direct access to the current wallet from walletRepo simplifies the code by removing the need to manage multiple chain states.


447-447: Clean disconnect handling.

The disconnect function call is properly updated to use the current wallet's disconnect method directly.

Copy link

codecov bot commented Feb 7, 2025

Codecov Report

Attention: Patch coverage is 77.04918% with 14 lines in your changes missing coverage. Please review.

Project coverage is 55.11%. Comparing base (02c576b) to head (62ac1fa).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
components/bank/forms/ibcSendForm.tsx 70.00% 12 Missing ⚠️
components/react/modal.tsx 50.00% 1 Missing ⚠️
components/wallet.tsx 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #255      +/-   ##
==========================================
+ Coverage   55.06%   55.11%   +0.04%     
==========================================
  Files         205      205              
  Lines       17654    17432     -222     
==========================================
- Hits         9722     9608     -114     
+ Misses       7932     7824     -108     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (3)
components/bank/forms/__tests__/ibcSendForm.test.tsx (1)

46-74: Consider updating defaultProps and adding new test cases.

Given the reversion to single chain usage:

  1. Consider removing unused multi-chain related props from defaultProps (e.g., chains object with multiple entries).
  2. Add test cases for error scenarios specific to single chain usage.
components/bank/components/sendBox.tsx (2)

38-63: Consider using local assets consistently across all chains.

While Manifest and Osmosis icons are now using local assets with proper leading slashes, the Axelar icon still uses an external URL. This inconsistency could lead to loading issues if the external resource is unavailable.

Consider downloading and serving the Axelar icon locally:

-        icon: 'https://github.com/cosmos/chain-registry/raw/refs/heads/master/axelar/images/axl.svg',
+        icon: '/axelar.svg',

68-68: Consider optimizing the balances memoization.

The current memoization just wraps the balances array. If the parent component ensures stable references for the balances array, this memoization might be unnecessary.

Verify if the parent component already provides a stable reference for balances. If not, consider transforming the data within the memoization to make it more useful:

-  const memoizedBalances = useMemo(() => balances, [balances]);
+  const memoizedBalances = useMemo(() => 
+    balances.map(balance => ({
+      ...balance,
+      // Add derived/computed properties here if needed
+    })), 
+    [balances]
+  );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e60bfdb and a085327.

📒 Files selected for processing (3)
  • components/bank/components/__tests__/sendBox.test.tsx (0 hunks)
  • components/bank/components/sendBox.tsx (6 hunks)
  • components/bank/forms/__tests__/ibcSendForm.test.tsx (2 hunks)
💤 Files with no reviewable changes (1)
  • components/bank/components/tests/sendBox.test.tsx
🔇 Additional comments (5)
components/bank/forms/__tests__/ibcSendForm.test.tsx (3)

19-26: LGTM! Well-structured mock for next/image.

The mock follows best practices by providing a simple img element replacement and proper ESModule configuration.


169-170: LGTM! Test skip aligns with PR objectives.

The test is correctly skipped as it's no longer applicable due to the reversion to single chain usage, as mentioned in the PR objectives.


172-172: LGTM! Simplified async call.

Good simplification of the async/await pattern while maintaining the core test functionality.

components/bank/components/sendBox.tsx (2)

1-37: LGTM! Good use of React.memo and props cleanup.

The component signature changes align well with the PR objectives. Wrapping with React.memo will help prevent unnecessary re-renders, and removing Osmosis-specific props simplifies the interface.


84-156: LGTM! Consistent use of memoizedBalances.

The component correctly uses the memoized balances in both forms while maintaining the existing conditional rendering logic.

@fmorency fmorency merged commit fef7ff8 into main Feb 7, 2025
10 checks passed
@fmorency fmorency deleted the chalabi/one-wallet branch February 7, 2025 21:39
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.

2 participants