Skip to content

Conversation

kushagrasarathe
Copy link
Contributor

@kushagrasarathe kushagrasarathe commented Feb 20, 2025

  • fixes TASK-8696 : fixed token selector to show usd value of token always and fallback to token value when usd value not available with tokeyn symbol
  • also fixes TASK-8846 : to show 0 fee when sending using peanut wallet, for request flow will implement in req v2 pr
  • also fixes fixes TASK-9108 : hide kyc badge if kyc is not approved

Summary by CodeRabbit

  • Style

    • Improved balance formatting by removing the extra space between the dollar sign and amount.
    • Refined token and USDC presentations for consistent precision.
    • Updated profile display to show the approved KYC badge only.
  • New Features

    • Enhanced transaction cost display for peanut wallets—showing $0 when applicable.
    • Upgraded the token selector to optionally display the token’s USD value.

Copy link

vercel bot commented Feb 20, 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 Feb 21, 2025 1:21pm

Copy link

Copy link

Copy link

Copy link
Contributor

coderabbitai bot commented Feb 20, 2025

Walkthrough

This pull request refines the UI and utility logic across several components. It removes the space after the dollar sign in wallet balance displays, adds an isPeanutWallet property for conditional transaction cost logic, and enhances the token selector by introducing a tokenUsdValue prop. The changes also update KYC badge rendering in profiles, improve balance formatting utilities using a dedicated decimal constant, and modify chain constants to be dynamically populated via a spread operator.

Changes

File(s) Change Summary
src/app/(mobile-ui)/wallet/page.tsx, src/components/Create/Link/Confirm.view.tsx, src/components/Profile/Components/ProfileSection.tsx Updated balance display by removing extra space after $; added isPeanutWallet to control transaction cost display and simplified KYC badge rendering.
src/components/Global/TokenSelector/Components/AdvancedButton.tsx, src/components/Global/TokenSelector/TokenSelector.tsx Introduced new optional tokenUsdValue prop and adjusted rendering logic to display formatted token USD values.
src/utils/balance.utils.ts, src/utils/general.utils.ts Revised formatting functions to floor values and updated constant usage (using PEANUT_WALLET_TOKEN_DECIMALS); reorganized import order and improved amount formatting.
src/constants/chains.consts.ts Modified chain export to use the spread operator to dynamically include all values from wagmiChains instead of a static list.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant C as ConfirmView Component
    participant W as useWallet Hook
    U->>C: Open Confirm View
    C->>W: Retrieve wallet details (address, isPeanutWallet, etc.)
    alt Peanut Wallet
      C->>C: Display transaction cost as "$0"
    else Other Wallet
      C->>C: Display transaction cost based on transactionCostUSD
    end
Loading
sequenceDiagram
    participant U as User
    participant T as TokenSelector
    participant A as AdvancedButton
    U->>T: Interact with token selector
    T->>T: Get selectedBalance and compute tokenUsdValue
    T->>A: Pass tokenUsdValue prop (or fallback balance) to AdvancedButton
    A->>A: Render token amount with appropriate formatting
Loading

Possibly related PRs

Suggested reviewers

  • Hugo0

Poem

Hoppin’ through the code with glee,
Dollar signs stick tight, you see.
Peanut wallets get a brand new flair,
Token values shine with formatted care.
Lines of logic hop in a row –
A clean code field where rabbits go!
🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

🔭 Outside diff range comments (1)
src/constants/chains.consts.ts (1)

96-104: 🛠️ Refactor suggestion

Remove @ts-ignore and fix type safety.

The @ts-ignore comment suggests potential type issues. Consider fixing the type safety by:

  1. Explicitly typing the spread result
  2. Using type assertions properly
-//@ts-ignore
-export const chains = [
-    ...Object.values(wagmiChains),
-    milkomeda,
-    milkomedaTestnet,
-    baseTestnet,
-    taikoGrimsvotn,
-    ZKSyncSepolia,
-] as [Chain, ...Chain[]]
+export const chains = [
+    ...(Object.values(wagmiChains) as Chain[]),
+    milkomeda,
+    milkomedaTestnet,
+    baseTestnet,
+    taikoGrimsvotn,
+    ZKSyncSepolia,
+] as [Chain, ...Chain[]]
🧹 Nitpick comments (2)
src/utils/balance.utils.ts (1)

107-113: Rename function to better reflect its purpose.

The function name 'printableUsdc' is misleading as it's used for general token values, not just USDC. Consider renaming it to something more generic like 'formatTokenValueUSD' or 'printableTokenValue'.

-export const printableUsdc = (balance: bigint): string => {
+export const formatTokenValueUSD = (balance: bigint): string => {

Additionally, consider adding input validation to handle edge cases:

 export const printableUsdc = (balance: bigint): string => {
+    if (balance < 0n) {
+        throw new Error('Balance cannot be negative');
+    }
     const formatted = formatUnits(balance, PEANUT_WALLET_TOKEN_DECIMALS)
     // floor the formatted value
     const value = Number(formatted)
     const flooredValue = Math.floor(value * 100) / 100
     return flooredValue.toFixed(2)
 }
src/components/Global/TokenSelector/Components/AdvancedButton.tsx (1)

59-72: Improve accessibility for the token selector button.

Consider enhancing the accessibility of the button:

  1. Add aria-expanded to indicate dropdown state
  2. Add aria-controls to associate with the dropdown menu
 <section
     role="button"
     tabIndex={0}
     aria-label="Open token selector"
+    aria-expanded={isVisible}
+    aria-controls="token-selector-dropdown"
     className={`flex w-full ${!isStatic && ' cursor-pointer '} h-18 flex-row items-center justify-between border border-n-1 px-4 py-2 hover:bg-grey-1/10 dark:border-white ${classNameButton}`}
     onClick={() => {
         !isStatic && onClick()
     }}
     onKeyDown={(e) => {
         if (e.key !== 'Enter' && e.key !== ' ') return
         !isStatic && onClick()
     }}
 >
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2c19f61 and 360c9bc.

📒 Files selected for processing (8)
  • src/app/(mobile-ui)/wallet/page.tsx (2 hunks)
  • src/components/Create/Link/Confirm.view.tsx (2 hunks)
  • src/components/Global/TokenSelector/Components/AdvancedButton.tsx (3 hunks)
  • src/components/Global/TokenSelector/TokenSelector.tsx (1 hunks)
  • src/components/Profile/Components/ProfileSection.tsx (1 hunks)
  • src/constants/chains.consts.ts (1 hunks)
  • src/utils/balance.utils.ts (2 hunks)
  • src/utils/general.utils.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/app/(mobile-ui)/wallet/page.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Deploy-Preview
🔇 Additional comments (9)
src/components/Profile/Components/ProfileSection.tsx (1)

32-36: LGTM! KYC badge visibility logic updated correctly.

The implementation correctly addresses TASK-9108 by hiding the KYC badge when KYC approval has not been granted.

src/constants/chains.consts.ts (1)

96-98:

❓ Verification inconclusive

Verify the implications of including all chains from wagmiChains.

While using spread operator simplifies chain management, it could potentially include unwanted chains or miss required chains if the wagmiChains module changes. Consider:

  1. Explicitly listing required chains to maintain control over supported networks.
  2. Adding validation to ensure critical chains are available.

🏁 Script executed:

#!/bin/bash
# Description: Check which chains are being included and if any critical chains might be missing

# List all exported chains from wagmi
echo "Checking available chains in wagmi:"
node -e "
const wagmi = require('wagmi/chains');
console.log('Available chains:', Object.keys(wagmi).join(', '));
"

# Search for chain usage in the codebase to identify critical chains
echo -e "\nChecking chain usage in the codebase:"
rg -l "chainId.*[\"'](?:1|10|100|137|8453|5000|42161|56)[\"']" --type ts

Length of output: 1358


Action Required: Reconsider Chain Inclusion Strategy

The current implementation uses the spread operator to include all values from wagmiChains, which raises concerns over accidentally incorporating unintended chains. Our verification attempt to list available chains via wagmi/chains failed (due to a module resolution issue), and a scan of the codebase revealed explicit references to critical chain IDs across several files (e.g., in src/components/Offramp/Confirm.view.tsx, src/constants/cashout.consts.ts, etc.).

Please consider one or both of the following actions:

  • Explicit Chain Listing: Enumerate the supported chains directly rather than spreading all available chains. This approach prevents inadvertent inclusion of unsupported or experimental chains if the underlying wagmiChains module changes.
  • Validation Mechanism: Implement a validation step to ensure that all critical chain IDs (as referenced in various parts of the codebase) are present and correctly configured.

Review and adjust the implementation at src/constants/chains.consts.ts (around lines 96–98) to ensure that your chain inclusion strategy remains predictable and secure across future dependency updates.

src/components/Global/TokenSelector/Components/AdvancedButton.tsx (1)

100-109: LGTM! Token value display logic implemented correctly.

The implementation correctly addresses the requirement to show USD values for tokens with a proper fallback to token balance when USD value is not available.

src/components/Create/Link/Confirm.view.tsx (3)

76-76: LGTM!

The addition of isPeanutWallet to the destructured properties from useWallet hook is appropriate for implementing the fee display logic.


318-324: LGTM!

The conditional logic for displaying network cost is well-structured and handles all cases:

  • Shows $0 for peanut wallet
  • Shows $0 for zero transaction cost
  • Shows $<0.01 for very small costs
  • Shows formatted amount for other cases

327-332: LGTM!

The MoreInfo text is appropriately updated to reflect whether the transaction is sponsored by peanut based on the wallet type.

src/components/Global/TokenSelector/TokenSelector.tsx (1)

327-327: LGTM!

The addition of tokenValue={selectedBalance?.value} to the AdvancedTokenSelectorButton component enables USD value display in the token selector, aligning with the PR objectives.

src/utils/general.utils.ts (2)

2-4: LGTM!

The imports are correctly updated to include required dependencies.


299-304:

❓ Verification inconclusive

Verify the impact of flooring token amounts.

The addition of flooring logic in formatTokenAmount ensures consistent display of token values by removing sub-decimal precision. However, this change could affect display of very small token amounts.

Run the following script to check usage of this function with small token amounts:


🏁 Script executed:

#!/bin/bash
# Description: Find calls to formatTokenAmount with small values
rg -A 2 "formatTokenAmount\(" | grep -E "0\.[0-9]{8,}|1e-[0-9]+"

Length of output: 66


Action: Reassess the impact of flooring token amounts before finalizing.

The automated search did not reveal any instances where formatTokenAmount is called with very small token values (e.g., values matching "0.[0-9]{8,}" or scientific notation like "1e-[0-9]+"). However, because the search returned no output, it's uncertain whether such cases exist or if they were missed by the query. Please perform a manual verification or extend the analysis to ensure that the flooring logic does not inadvertently drop significant digits for extremely small amounts.

  • Next steps:
    • Manually verify code paths using formatTokenAmount to confirm they do not pass token amounts that rely on sub-decimal precision.
    • Consider augmenting tests or adding usage examples with very small values to validate the intended behavior.

contracts: {},
} as const satisfies Chain

//@ts-ignore
Copy link
Contributor

Choose a reason for hiding this comment

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

booooooooooooooooooooo

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 (1)
src/components/Global/TokenSelector/Components/AdvancedButton.tsx (1)

104-105: Consider using a more robust USD value formatting approach.

The current string concatenation with $ could be improved for better internationalization support.

Consider using a dedicated currency formatting utility:

-`$${utils.formatTokenAmount(parseFloat(tokenUsdValue), 2)}`
+utils.formatUsdValue(tokenUsdValue)

This would encapsulate the currency symbol and decimal places in a reusable utility function.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 360c9bc and 8cc14ad.

📒 Files selected for processing (2)
  • src/components/Global/TokenSelector/Components/AdvancedButton.tsx (3 hunks)
  • src/components/Global/TokenSelector/TokenSelector.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Global/TokenSelector/TokenSelector.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Deploy-Preview
🔇 Additional comments (2)
src/components/Global/TokenSelector/Components/AdvancedButton.tsx (2)

15-15: Consider a more explicit prop name.

The prop name tokenUsdValue could be more explicit to clearly indicate it represents the USD value.

Consider renaming to tokenBalanceInUsd or tokenValueInUsd for better clarity.


100-109: LGTM! Clear implementation with good fallback logic.

The balance display logic aligns well with the PR objectives, showing USD value when available and falling back to token balance. The comments clearly explain the logic.

@kushagrasarathe kushagrasarathe merged commit 0072a59 into peanut-wallet-dev Feb 21, 2025
5 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Mar 22, 2025
@Hugo0 Hugo0 deleted the fix/token-selector branch July 3, 2025 18:24
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