Skip to content

[TASK-6438] feat: avoid loading tokens that wont be used#814

Merged
kushagrasarathe merged 2 commits intopeanut-wallet-devfrom
feat/not-needed-extra-tokens
Apr 23, 2025
Merged

[TASK-6438] feat: avoid loading tokens that wont be used#814
kushagrasarathe merged 2 commits intopeanut-wallet-devfrom
feat/not-needed-extra-tokens

Conversation

@jjramirezn
Copy link
Copy Markdown
Contributor

@jjramirezn jjramirezn commented Apr 22, 2025

For flows where the user needs to be connected (most of them), only show the tokens that the user has a balance in. This will improve user experience and also reduce the amount of tokens (and their logos) that will be loaded

Summary by CodeRabbit

  • Improvements
    • Enhanced performance and responsiveness of the token selector modal.
    • Tokens are now hidden when a user connection is required.
    • The chain selector is hidden when the user is expected to be connected.
    • Improved state reset and filter clearing when closing the modal for a smoother user experience.
    • Token logos dynamically update based on the selected token, improving visual consistency.

@vercel
Copy link
Copy Markdown

vercel bot commented Apr 22, 2025

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

Name Status Preview Comments Updated (UTC)
peanut-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 22, 2025 8:21pm

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 22, 2025

## Walkthrough

The changes focus on optimizing the `TokenSelector` component in the codebase. The `TokenList` subcomponent is now wrapped with React's `memo` to prevent unnecessary re-renders. The `setToken` handler is refactored to use `useCallback` for stable reference identity. Logic for clearing filters and user chain change state is shifted to a `useEffect` that triggers after the modal closes, synchronized with the modal's close animation. Token and chain selector rendering is now conditional based on the `shouldBeConnected` state, and the memoization logic for the token list is updated accordingly. Additionally, the `AdvancedTokenSelectorButton` component was enhanced to manage its token logo URI dynamically via state and effect hooks.

## Changes

| File(s)                                                     | Change Summary                                                                                                               |
|-------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------|
| src/components/Global/TokenSelector/TokenSelector.tsx       | - Wrapped `TokenList` with `memo` for render optimization.<br>- Refactored `setToken` to use `useCallback`.<br>- Moved filter and state clearing to a `useEffect` triggered by modal visibility.<br>- Updated token list memoization and rendering logic to consider `shouldBeConnected`.<br>- Made `ChainSelector` rendering conditional.<br>- Simplified `onClose` handler. |
| src/components/Global/TokenSelector/Components/AdvancedButton.tsx | - Managed token logo URI as state `_tokenLogoUri` initialized from prop.<br>- Added `useEffect` to update `_tokenLogoUri` dynamically by calling `getTokenLogo`.<br>- Updated rendering to use `_tokenLogoUri` state instead of prop for token logo image. |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
    participant User
    participant TokenSelector
    participant Modal
    participant TokenList

    User->>TokenSelector: Open modal
    TokenSelector->>Modal: Show modal
    Modal->>TokenSelector: User selects token
    TokenSelector->>TokenList: Pass stable setToken handler
    TokenList->>TokenSelector: setToken called (memoized)
    TokenSelector->>Modal: Close modal
    Modal->>TokenSelector: Modal visibility changes to false
    TokenSelector->>TokenSelector: useEffect clears filter and resets state after 200ms

Possibly related PRs

  • peanutprotocol/peanut-ui#424: Refactors and introduces the TokenSelector component, which is directly built upon and further optimized in this PR.
  • peanutprotocol/peanut-ui#401: Also modifies TokenSelector to support token search without balances when no account is connected, related to connection and rendering logic changes.

Suggested labels

Being worked on

Suggested reviewers

  • Hugo0

Poem

In the meadow of code where tokens hop,
Memoization keeps the renderings on top.
With callbacks that never stray,
And filters reset as modals fade away.
Chains hide and show with a bunny’s delight,
Streamlining the flow—oh what a sight!
🐇✨


<!-- walkthrough_end -->


---

<details>
<summary>📜 Recent review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 52ab99e418c0df66e6d4359a5db37340360264ba and 9394d8b82e595832d2f3459f1c6793ecd9ae491d.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `src/components/Global/TokenSelector/Components/AdvancedButton.tsx` (4 hunks)
* `src/components/Global/TokenSelector/TokenSelector.tsx` (7 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary>

* src/components/Global/TokenSelector/TokenSelector.tsx

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🧠 Learnings (2)</summary>

<details>
<summary>📓 Common learnings</summary>

Learnt from: jjramirezn
PR: #424
File: src/components/Global/TokenSelector/TokenSelector.tsx:197-211
Timestamp: 2024-10-11T01:14:15.489Z
Learning: In src/components/Global/TokenSelector/TokenSelector.tsx, when the calculation within functions like byChainAndText is not computationally expensive, it's acceptable to avoid using useCallback for memoization.


Learnt from: jjramirezn
PR: #413
File: src/context/tokenSelector.context.tsx:118-123
Timestamp: 2024-10-08T20:13:42.967Z
Learning: In the TokenContextProvider component within src/context/tokenSelector.context.tsx, in the TypeScript React application, when data changes and before calling fetchAndSetTokenPrice, it is necessary to reset selectedTokenData, selectedTokenPrice, selectedTokenDecimals, and inputDenomination to discard stale data.


</details>
<details>
<summary>src/components/Global/TokenSelector/Components/AdvancedButton.tsx (1)</summary>

Learnt from: jjramirezn
PR: #413
File: src/context/tokenSelector.context.tsx:118-123
Timestamp: 2024-10-08T20:13:42.967Z
Learning: In the TokenContextProvider component within src/context/tokenSelector.context.tsx, in the TypeScript React application, when data changes and before calling fetchAndSetTokenPrice, it is necessary to reset selectedTokenData, selectedTokenPrice, selectedTokenDecimals, and inputDenomination to discard stale data.


</details>

</details><details>
<summary>🧬 Code Graph Analysis (1)</summary>

<details>
<summary>src/components/Global/TokenSelector/Components/AdvancedButton.tsx (1)</summary><blockquote>

<details>
<summary>src/utils/general.utils.ts (1)</summary>

* `getTokenLogo` (1070-1075)

</details>

</blockquote></details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: Deploy-Preview

</details>

<details>
<summary>🔇 Additional comments (4)</summary><blockquote>

<details>
<summary>src/components/Global/TokenSelector/Components/AdvancedButton.tsx (4)</summary>

`2-2`: **Import added for dynamic token logo handling.**

The `getTokenLogo` utility function import enables fetching token logos dynamically based on token symbols.

---

`41-41`: **Good addition of local state for token logo management.**

Creating a local state variable `_tokenLogoUri` initialized with the prop value allows the component to manage the token logo URI internally, enabling dynamic updates when needed.

---

`59-63`: **Well-implemented dynamic token logo fetching logic.**

This `useEffect` implements the key optimization from this PR, fetching token logos only when needed. The conditional check ensures the logo is only fetched when:
1. No logo URI is currently set (`!_tokenLogoUri`)
2. We have the token symbol (`_tokenSymbol`)
3. A token is actually selected (`selectedTokenAddress`)

This approach aligns with the PR objective of avoiding loading tokens that won't be used.

---

`81-82`: **Updated rendering to use the dynamically managed logo state.**

Changing from `tokenLogoUri` to `_tokenLogoUri` ensures the component displays the dynamically fetched logo.

</details>

</blockquote></details>

</details>
<!-- internal state start -->


<!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOYCmGJATmriQCaQDG+Ats2bgFyQAOFk+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEYDEZyAAUASpETZWaCrKNwSPbABsvkCiQBHbGlcSHFcLzpIACIAbWgAQQBlAGkwADYAFgBmAA4AXUgAMxJqLjQJfHh6L3w0WngMIjD8AGsyZFxYakgAd3wMUIEPbEQ6ABpo+2wBZnUaejlIUcpIISEqOf8ALyw0ZFtIDEdhvlyARkzxlEGKRWwGaXRi0txsfxb+bnE57Y8CdpYWr1RrNRphWAeNDcbheeAMajwAYaGCQxjdJr/ZykXDIFZ8Iq1XqdbqhfxBeAfLojMZ8AiQYYKDDkMQTPoIBiwJmIcJ4DzMfA8/hFCE0jwIsaIFEASQwPNK9HwIuBDSa6B8LUBiGu1OW3Fo1A8HXeTy6PQGXnkAI6fXUXLQDLQXkwjxuouWtIA5Mg0AwmNhBugPg1ELC0LI6Ci4Khobw6pz0PBmJ18JAyBjXbr8WmAB7cSjwMiupb+WgPUGMLx4Gh8TD0J2IVNKBj+famtHHZinYWam110WU9CIRsMeCGmr4IiCiE9chRemMlVs7j4GiDMc+eRJuMSCv5ihFfAUZgukhRtHcby+cnBIUxiTaZ0CSLFI9+Ei7ki9dChWC4XDcIgHAAPTAUQdozBoT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WpVIDA1BuCcLfnkH0gARTdqtNdkUAAGpOmCGVfsDjnHxv9R43NWGBteDGFx127sfRFAZrk/JhSLYVNNKmfxV2zyRWis8kyZkLJfPYHZRyggXLJ13b5Xu0NUG4mAmNh8BMu7VmRGFCKUVogxUsPFRKckohqRPBpdKb2nmwKB4GBJprMDBfbHUwEkAemphcTYaUQ5nhYxoHk5wY5nwLQAPr70KpOfALiMaDwjuIJ0A1StC3LoL4Xov4DZbuNwFECQjhfnahkmbStQZKMFZffdnPcoC7eQrsXmlGC/QrLlHEGLhenUatNd4+M1btNq12KZKBW6m6KubpXgGjirnVK2Wg8hHH9gEKuLkJv95JFkJ7orD7F2QIOmNoV0h13OChA+Om2Mzz3yGhg5oPS7mHmGXTo+jPF406/m9+g9IVjtV92QIXU5FdlQ54TOUNB6hvzREeeA4EMAh1yvL9vFuctozlO8KaaIQxhgjBOKcRunhh5H3MWxz7nJjEVGkl4AdISKj4CNfmDPheQGZ9KLZ2OttLIOfP0Qxz789guSZ/gfAblwj6ewYh0g41lKWyVL0i6i7REAj4TxPDnJ5hEbH6eC3I/4PLSBkzk6hC5QI6nhWb+TLadwo4YBlSqaswkgeCIBoBsA8Aq4+jWJgEQEmiEQY5ESGTGRkTWLpRUQEC470RRAKTMR+BoCqSOCE7yBLC8Q6RqB6TCRMGiSMRzC4B87VCIB87+Cfi9B0B85YzXQGRGTSECC0DnCPBoDZDZAMDZACC5C0AuzZAACcAArLkAwE7LQDYekLQAAOzDBZC6EqBWHnDpBoBFCuGuFaEGDSE2FOzeFWEkCZDnD2Euy0BFDpDpAkAuE5A2FWFoA2G0ACDZCuHZCZCWHpAuxOyeEOgiSkSQBWHWGZC0C5BmFOwkBpF2HZCOFOxFB5FpFFD6HpCuGVGiC0DpFRE+H0DEQhHlEKTqDyG0CKHKGFiqG0B87kRaFAA -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details>
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

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.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=peanutprotocol/peanut-ui&utm_content=814):

- 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](https://docs.coderabbit.ai/finishing-touches/docstrings) 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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

@notion-workspace
Copy link
Copy Markdown

@jjramirezn jjramirezn force-pushed the feat/not-needed-extra-tokens branch from bd1cea3 to 52ab99e Compare April 22, 2025 15:05
Copy link
Copy Markdown
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 3

🔭 Outside diff range comments (1)
src/components/Global/TokenSelector/TokenSelector.tsx (1)

4-426: ⚠️ Potential issue

Missing implementation for showOnlyBalanceTokens property

The showOnlyBalanceTokens property added to the TokenSelectorProps interface in the constants file is not being used in this component. This seems to be a critical oversight given the PR objective.

To properly implement this functionality, you need to:

  1. Add the property to the destructured props in the component signature:
const TokenSelector = ({
    classNameButton,
    shouldBeConnected = true,
    showOnlySquidSupported = false,
+   showOnlyBalanceTokens = false,
    onReset,
}: TokenSelectorProps) => {
  1. Use this property to filter tokens with balances in the filteredBalances useMemo:
const filteredBalances = useMemo(() => {
    // initially show all balances and the tokens on the current chain
    if (filterValue.length === 0 && !hasUserChangedChain) return _balancesToDisplay

+   // Filter tokens to only show those with balances if needed
+   const balancesFiltered = showOnlyBalanceTokens 
+       ? _balancesToDisplay.filter(balance => parseFloat(balance.amount) > 0)
+       : _balancesToDisplay;

    const byChainAndText = ({ name, symbol, chainId }: IUserBalance): boolean => {
        // existing filtering logic
    }
    
-   return _balancesToDisplay.filter(byChainAndText)
+   return balancesFiltered.filter(byChainAndText)
}, [_balancesToDisplay, filterValue, selectedChainID, hasUserChangedChain, showOnlyBalanceTokens])
  1. Update the dependency array to include the new property.
🛑 Comments failed to post (3)
src/components/Global/TokenSelector/TokenSelector.consts.ts (1)

11-11: ⚠️ Potential issue

New property added without implementation

The showOnlyBalanceTokens property has been added to the interface, but I don't see it being used in the implementation (TokenSelector.tsx). While the property aligns with the PR objective of "avoiding loading tokens that won't be used," there's no filtering logic based on this flag.

Consider implementing the filtering logic using this property, for example in the filteredBalances useMemo:

const filteredBalances = useMemo(() => {
    // initially show all balances and the tokens on the current chain
    if (filterValue.length === 0 && !hasUserChangedChain) return _balancesToDisplay

+   // Filter by token balance if needed
+   const balancesWithFilter = showOnlyBalanceTokens 
+       ? _balancesToDisplay.filter(balance => parseFloat(balance.amount) > 0)
+       : _balancesToDisplay;

    const byChainAndText = ({ name, symbol, chainId }: IUserBalance): boolean =>
        // rest of your filtering logic
        
-   return _balancesToDisplay.filter(byChainAndText)
+   return balancesWithFilter.filter(byChainAndText)
}, [_balancesToDisplay, filterValue, selectedChainID, hasUserChangedChain, showOnlyBalanceTokens])
📝 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.

const filteredBalances = useMemo(() => {
    // initially show all balances and the tokens on the current chain
    if (filterValue.length === 0 && !hasUserChangedChain) return _balancesToDisplay

    // Filter by token balance if needed
    const balancesWithFilter = showOnlyBalanceTokens
        ? _balancesToDisplay.filter(balance => parseFloat(balance.amount) > 0)
        : _balancesToDisplay

    const byChainAndText = ({ name, symbol, chainId }: IUserBalance): boolean =>
        // rest of your filtering logic

    return balancesWithFilter.filter(byChainAndText)
}, [
    _balancesToDisplay,
    filterValue,
    selectedChainID,
    hasUserChangedChain,
    showOnlyBalanceTokens
])
src/components/Global/TokenSelector/TokenSelector.tsx (2)

395-408: 💡 Verification agent

🧩 Analysis chain

Conditional ChainSelector rendering needs verification

Conditionally rendering the ChainSelector based on !shouldBeConnected means users won't be able to select a chain when they're expected to be connected. This might limit functionality for connected users who want to switch chains.

Let's check if there are other places in the codebase where chain selection is handled for connected users:

Consider documenting this design decision with a more explicit comment to clarify the intent:

{!shouldBeConnected && (
+   // Chain selector is hidden for connected users because they can only 
+   // use tokens from chains where they have balances
    <ChainSelector
        // rest of the code
    />
)}

🏁 Script executed:

#!/bin/bash
# Check for other chain selection mechanisms for connected users

# Look for references to ChainSelector component usage
rg -A 5 -B 5 "ChainSelector" src/components/ --type ts --type tsx

# Look for chain selection logic conditions
rg -A 5 "setSelectedChainID|setChainID" src/components/ --type ts --type tsx

Length of output: 200


This will help us determine if connected users have an alternate chain-selection path elsewhere.


🏁 Script executed:

#!/bin/bash
# Retry searching for ChainSelector usages without relying on --type flags
rg -n 'ChainSelector' --glob '*.tsx' src

# Search for any chain-switching logic or handlers in .tsx files
rg -n 'setSelectedChainID|setChainID|switchChain|onChange.*chain' --glob '*.tsx' src

Length of output: 4899


Clarify why ChainSelector is hidden for connected users

The ChainSelector is only rendered when !shouldBeConnected because once a user connects their wallet, the active chain is locked to their wallet’s network. Please add a comment to explain this design decision.

• File: src/components/Global/TokenSelector/TokenSelector.tsx
• Lines: 395–408

{!shouldBeConnected && (
+  // Only show chain selector when disconnected.
+  // For connected users, the active chain is determined by their wallet network.
  <ChainSelector
    chainsToDisplay={
      showOnlySquidSupported
        ? supportedPeanutChains.filter(
            (chain) => !!supportedSquidChainsAndTokens[chain.chainId]
          )
        : supportedPeanutChains
    }
    onChange={(_chainId) => {
      setUserChangedChain(true)
    }}
  />
)}
📝 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.

                            {!shouldBeConnected && (
+                               // Only show chain selector when disconnected.
+                               // For connected users, the active chain is determined by their wallet network.
                                <ChainSelector
                                    chainsToDisplay={
                                        showOnlySquidSupported
                                            ? supportedPeanutChains.filter(
                                                  (chain) => !!supportedSquidChainsAndTokens[chain.chainId]
                                              )
                                            : supportedPeanutChains
                                    }
                                    onChange={(_chainId) => {
                                        setUserChangedChain(true)
                                    }}
                                />
                            )}

191-194: 💡 Verification agent

🧩 Analysis chain

Clarify early return behavior in selectedChainTokens

While the comment explains the intent, the implementation returns an empty array when shouldBeConnected is true, which seems counterintuitive. If the goal is to show only tokens with balances for connected users, returning an empty array might not be the right approach.

Consider refining this logic to ensure proper token filtering:

// If we expect the user to be connected, then we just want to show the
// tokens where the user has a balance
- if (shouldBeConnected) return []
+ // No need to load tokens without balances when user is connected
+ // The user's actual balances will be displayed from _balancesToDisplay
+ if (shouldBeConnected) return []

Let's verify this behavior with the existing logic:


🏁 Script executed:

#!/bin/bash
# Check how _balancesToDisplay is handling token display logic

rg -A 10 "_balancesToDisplay\s*=" src/components/Global/TokenSelector/

Length of output: 1091


I've requested more context around both the selectedChainTokens computation and the early-return to ensure the intended logic matches what’s implemented.


🏁 Script executed:

# Show the definition and surrounding logic of selectedChainTokens
rg -n "selectedChainTokens" -A10 -B10 src/components/Global/TokenSelector/TokenSelector.tsx

# Show the early return with shouldBeConnected in context
rg -n "if (shouldBeConnected)" -A10 -B10 src/components/Global/TokenSelector/TokenSelector.tsx

Length of output: 2510


🏁 Script executed:

#!/bin/bash
# Locate the definition and usages of shouldBeConnected in this file
rg -n shouldBeConnected -A10 -B10 src/components/Global/TokenSelector/TokenSelector.tsx

Length of output: 4955


Clarify why selectedChainTokens returns an empty list when shouldBeConnected is true

The early return in the selectedChainTokens memo is intentional: when a connection is required, we don’t want to append any “chain‐only” tokens because the user’s actual balances (including any tokens they hold on that chain) are rendered via _balancesToDisplay. To make this explicit, please update the inline comment as follows:

--- a/src/components/Global/TokenSelector/TokenSelector.tsx
+++ b/src/components/Global/TokenSelector/TokenSelector.tsx
@@ -191,4 +191,6
-        // If we expect the user to be connected, then we just want to show the
-        // tokens where the user has a balance
+        // When a wallet connection is required, skip adding chain-only tokens here—
+        // the user’s token balances are shown through _balancesToDisplay.
         if (shouldBeConnected) return []

This makes it clear that returning [] is correct behavior in this context.

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

        // When a wallet connection is required, skip adding chain-only tokens here—
        // the user’s token balances are shown through _balancesToDisplay.
        if (shouldBeConnected) return []

Copy link
Copy Markdown
Contributor

@kushagrasarathe kushagrasarathe left a comment

Choose a reason for hiding this comment

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

@jjramirezn reviewed, one blocking qn, when connected with a wallet where i dont have any tokens, the token selector trigger is shown like this, imo should show default token/chain logos (token logo is missing in this case), and when opened it shows No balances to display! which is good, but then in send flow it also lets me move forward to confirm screen (see second screenshot)

image image

For flows where the user needs to be connected (most of them), only
show the tokens that the user has a balance in. This will improve user
experience and also reduce the amount of tokens (and their logos) that
will be loaded
@jjramirezn jjramirezn force-pushed the feat/not-needed-extra-tokens branch from 52ab99e to 9394d8b Compare April 22, 2025 20:14
@jjramirezn
Copy link
Copy Markdown
Contributor Author

After going back and forward with eliminating external wallets already, came into too many issues for the scope of this so implemented the easy fix. About the confirm, this is an existing issue I think its fixed when send flow changes

Copy link
Copy Markdown
Contributor

@kushagrasarathe kushagrasarathe left a comment

Choose a reason for hiding this comment

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

aprovvedddd

@kushagrasarathe kushagrasarathe merged commit b24cdf8 into peanut-wallet-dev Apr 23, 2025
5 checks passed
@jjramirezn jjramirezn deleted the feat/not-needed-extra-tokens branch April 23, 2025 11:07
@coderabbitai coderabbitai bot mentioned this pull request Apr 30, 2025
7 tasks
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