Skip to content

Conversation

jjramirezn
Copy link
Contributor

@jjramirezn jjramirezn commented Dec 2, 2024

When creating a claim link, paying a request or cashing out and using the peanut wallet, the user doesn't need to choose a token, the token is already chosen for them

Summary by CodeRabbit

Release Notes

  • New Features

    • Dynamic wallet balance display with real-time calculations.
    • Improved handling of wallet interactions and state management in the cashout process.
    • Introduction of new constants for wallet management, including PEANUT_WALLET_TOKEN.
  • Bug Fixes

    • Refined error handling across various components for better user feedback.
  • Chores

    • Removed deprecated useBalance hook and associated logic.
    • Introduced new utility functions for balance management and processing.
  • Documentation

    • Updated documentation to clarify project structure and functionalities, including App Router capabilities.
    • Removed the high-level overview document, which detailed project structure and usage.

@jjramirezn jjramirezn requested a review from Hugo0 December 2, 2024 01:42
Copy link

vercel bot commented Dec 2, 2024

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 Dec 2, 2024 6:21pm

Copy link

Copy link
Contributor

coderabbitai bot commented Dec 2, 2024

Walkthrough

The pull request involves the removal of the docs/high_level_overview.md file, which contained comprehensive documentation on the Next.js project structure and functionality. Additionally, it introduces various modifications across multiple components to enhance wallet management, balance handling, and error management. Key updates include the removal of the useBalance hook, the enhancement of the useWallet hook, and the introduction of new utility functions for processing wallet balances.

Changes

File Path Change Summary
docs/high_level_overview.md File removed, eliminating a comprehensive resource for understanding the project's architecture and usage.
src/app/(mobile-ui)/wallet/page.tsx Added import for formatUnits from viem. Updated wallet balance display to use formatUnits(selectedWallet?.balance ?? 0n, 6) instead of a hardcoded string.
src/components/Cashout/Components/Initial.view.tsx Expanded context usage with setSelectedChainID and setSelectedTokenAddress. Updated useWallet to retrieve additional properties. Modified logic for determining maximum value using selectedWallet balances. Refined error handling in handleOnNext.
src/components/Claim/Link/Initial.view.tsx Added resetSelectedToken function using useCallback. Adjusted rendering logic for TokenSelector based on isExternalWallet. Enhanced error handling in handleClaimLink and handleIbanRecipient.
src/components/Claim/Link/Onchain/Confirm.view.tsx Updated handleOnClaim to call refetchBalances with address.
src/components/Create/Create.tsx Removed imports for SafeAppsSDK and useBalance.
src/components/Create/Link/Confirm.view.tsx Updated to destructure refetchBalances from useWallet. Modified handleConfirm to call refetchBalances with address.
src/components/Create/Link/Input.view.tsx Enhanced context usage by adding setSelectedChainID and setSelectedTokenAddress. Updated maxValue calculation logic to use selectedWallet.balances.
src/components/Create/useCreateLink.tsx Updated balance checking logic to use selectedWallet context. Modified submitClaimLinkInit to call refetchBalances(address ?? '').
src/components/Global/ChainSelector/index.tsx Removed useBalance and added useWallet. Updated value calculation to use calculateValuePerChain.
src/components/Global/TokenSelector/Components/AdvancedButton.tsx Removed several imports and simplified state management related to token balance handling.
src/components/Global/TokenSelector/TokenSelector.tsx Removed useBalance and updated balance retrieval to use selectedWallet?.balances.
src/components/Home/WalletCard.tsx Removed Link component from 'add' type rendering.
src/components/Home/WalletToggleButton.tsx Changed toggleWallet to a memoized callback using useCallback.
src/components/Request/Create/Views/Initial.view.tsx Replaced useBalance with useWallet to access wallet data. Added state management for setSelectedChainID and setSelectedTokenAddress.
src/components/Request/Pay/Views/Initial.view.tsx Added useCallback to resetTokenAndChain. Updated conditional rendering of TokenSelector based on wallet type.
src/constants/general.consts.ts Removed constant USDC_ARBITRUM_ADDRESS.
src/constants/zerodev.consts.ts Added new constant PEANUT_WALLET_TOKEN for USDC Arbitrum address.
src/context/walletContext/walletContext.tsx Enhanced WalletContextType with refetchBalances and isExternalWallet methods. Updated balance fetching logic.
src/hooks/useBalance.tsx Removed the useBalance hook.
src/interfaces/wallet.interfaces.ts Updated IWallet interface to include optional balances property.
src/utils/balance.utils.ts Introduced utility functions for managing wallet balances, including fetchWalletBalances, balanceByToken, and calculateValuePerChain.
src/utils/index.ts Added export statement for balance.utils.

Possibly related PRs

Suggested labels

Being worked on

🐰 "In the code where wallets play,
We've tidied up the docs today!
With hooks and contexts, all in line,
Our project shines, oh so divine!
So hop along, let’s code and cheer,
For every change brings us near!" 🐇✨


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

### Hooks
The `/hooks` folder contains two custom hooks to help manage wallet functionality:
The `/hooks` folder contains a custom hook to help manage wallet functionality:
Copy link
Contributor

Choose a reason for hiding this comment

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

Q:

  1. why remove this section?
  2. Do we even need these docs? I feel like they're prone to getting outdated / potentially misleading

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think these docs are outdated and frankly I've never read them before. I removed this because ir removed the useBalance hook

Copy link
Contributor

Choose a reason for hiding this comment

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

lets remove then @jjramirezn

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: 5

🧹 Outside diff range and nitpick comments (8)
src/utils/balance.utils.ts (1)

29-29: Specify radix in parseInt to avoid unexpected results

When using parseInt, it's good practice to specify the radix parameter to avoid unexpected parsing behavior.

Apply this diff:

-decimals: parseInt(item.quantity.decimals),
+decimals: parseInt(item.quantity.decimals, 10),
src/components/Cashout/Components/Initial.view.tsx (1)

219-225: Include setSelectedChainID and setSelectedTokenAddress in useEffect dependencies

The useEffect depends on setSelectedChainID and setSelectedTokenAddress functions, but they are not included in the dependency array. This might lead to stale closures or unintended behavior. Include these functions in the dependency array to ensure the effect runs correctly when they change.

Apply this diff to include the dependencies:

-useEffect(() => {
+useEffect(() => {
     if (isPeanutWallet) {
         setSelectedChainID(PEANUT_WALLET_CHAIN.id.toString())
         setSelectedTokenAddress(PEANUT_WALLET_TOKEN)
     }
-}, [isPeanutWallet])
+}, [isPeanutWallet, setSelectedChainID, setSelectedTokenAddress])
src/components/Claim/Link/Initial.view.tsx (1)

Line range hint 459-473: Set autocomplete attribute for bank account inputs as per previous learning

To enhance user experience and align with best practices, set autocomplete="bank-account-number" on the GeneralRecipientInput component when the recipientType is 'us' or 'iban', as advised in the previous learning.

This applies the learning:

Learning: For bank account input fields, use autocomplete="bank-account-number" when the recipient type is 'us' or 'iban'.

Apply this diff:

<GeneralRecipientInput
    className=""
    placeholder="wallet address / ENS / IBAN / US account number"
    recipient={recipient}
    onUpdate={(update: GeneralRecipientUpdate) => {
        // existing code
    }}
+   autocomplete={recipientType === 'us' || recipientType === 'iban' ? 'bank-account-number' : undefined}
    infoText={TOOLTIPS.CLAIM_RECIPIENT_INFO}
/>
src/components/Global/TokenSelector/Components/AdvancedButton.tsx (1)

99-102: Consider improving readability of conditional rendering

While the logic is correct, the nested ternary with null could be more readable.

Consider restructuring like this:

-                        (tokenBalance ? (
-                            <p className="text-xs text-gray-1">
-                                Balance: {utils.formatTokenAmount(tokenBalance ?? 0, 4)}
-                            </p>
-                        ) : null)}
+                        tokenBalance && (
+                            <p className="text-xs text-gray-1">
+                                Balance: {utils.formatTokenAmount(tokenBalance, 4)}
+                            </p>
+                        )}

This approach:

  • Eliminates the nested ternary
  • Removes redundant null check since we're already checking for tokenBalance
  • Maintains the same functionality with cleaner syntax
src/components/Global/ChainSelector/index.tsx (1)

34-37: Consider adding error boundary for balance calculations

While the memoization is good for performance, consider adding error handling for edge cases where balance calculations might fail.

 const valuePerChain = useMemo(
-    () => calculateValuePerChain(selectedWallet?.balances ?? []),
+    () => {
+        try {
+            return calculateValuePerChain(selectedWallet?.balances ?? [])
+        } catch (error) {
+            console.error('Failed to calculate chain values:', error)
+            return []
+        }
+    },
     [selectedWallet?.balances]
 )
src/components/Claim/Link/Onchain/Confirm.view.tsx (1)

28-28: LGTM! Consider handling potential refetch errors.

The addition of refetchBalances ensures wallet balances are updated after a successful claim. However, since this is an async operation, consider handling potential errors to prevent them from being silently ignored.

-refetchBalances(address ?? '')
+try {
+  await refetchBalances(address ?? '')
+} catch (error) {
+  console.error('Failed to refresh balances:', error)
+  // Non-blocking error - don't show to user as the claim was successful
+}

Also applies to: 83-83

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

75-75: LGTM! Consider handling potential refetch errors for consistency.

The addition of refetchBalances ensures wallet balances are updated after successful link creation. For consistency with other components, consider handling potential errors.

-refetchBalances(address ?? '')
+try {
+  await refetchBalances(address ?? '')
+} catch (error) {
+  console.error('Failed to refresh balances:', error)
+  // Non-blocking error - don't show to user as the link creation was successful
+}

Also applies to: 220-220

src/components/Create/Link/Input.view.tsx (1)

331-344: Consider adding loading state for balances.

The conditional rendering for external wallet token selector is good, but consider adding a loading state while balances are being fetched to prevent UI flicker.

-{isExternalWallet && (
+{isExternalWallet && (
   <>
     <TokenSelector classNameButton="w-full" />
-    {selectedWallet!.balances!.length === 0 && (
+    {selectedWallet?.balances ? (
+      selectedWallet.balances.length === 0 && (
         <div
           onClick={() => {
             open()
           }}
           className="cursor-pointer text-h9 underline"
         >
           ( Buy Tokens )
         </div>
+      )
+    ) : (
+      <div className="text-h9">Loading balances...</div>
     )}
   </>
 )}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2181c10 and 7317ecc.

📒 Files selected for processing (23)
  • docs/high_level_overview.md (1 hunks)
  • src/app/(mobile-ui)/wallet/page.tsx (2 hunks)
  • src/components/Cashout/Components/Initial.view.tsx (7 hunks)
  • src/components/Claim/Link/Initial.view.tsx (6 hunks)
  • src/components/Claim/Link/Onchain/Confirm.view.tsx (2 hunks)
  • src/components/Create/Create.tsx (0 hunks)
  • src/components/Create/Link/Confirm.view.tsx (2 hunks)
  • src/components/Create/Link/Input.view.tsx (6 hunks)
  • src/components/Create/useCreateLink.tsx (7 hunks)
  • src/components/Global/ChainSelector/index.tsx (3 hunks)
  • src/components/Global/TokenSelector/Components/AdvancedButton.tsx (1 hunks)
  • src/components/Global/TokenSelector/TokenSelector.tsx (3 hunks)
  • src/components/Home/WalletCard.tsx (1 hunks)
  • src/components/Home/WalletToggleButton.tsx (2 hunks)
  • src/components/Request/Create/Views/Initial.view.tsx (5 hunks)
  • src/components/Request/Pay/Views/Initial.view.tsx (5 hunks)
  • src/constants/general.consts.ts (0 hunks)
  • src/constants/zerodev.consts.ts (1 hunks)
  • src/context/walletContext/walletContext.tsx (7 hunks)
  • src/hooks/useBalance.tsx (0 hunks)
  • src/interfaces/wallet.interfaces.ts (1 hunks)
  • src/utils/balance.utils.ts (1 hunks)
  • src/utils/index.ts (1 hunks)
💤 Files with no reviewable changes (3)
  • src/constants/general.consts.ts
  • src/hooks/useBalance.tsx
  • src/components/Create/Create.tsx
🧰 Additional context used
📓 Learnings (2)
src/components/Global/TokenSelector/TokenSelector.tsx (1)
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#424
File: src/components/Global/TokenSelector/TokenSelector.tsx:197-211
Timestamp: 2024-11-12T09:39:20.720Z
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.
src/components/Claim/Link/Initial.view.tsx (1)
Learnt from: Hugo0
PR: peanutprotocol/peanut-ui#545
File: src/components/Global/GeneralRecipientInput/index.tsx:118-126
Timestamp: 2024-11-26T12:06:11.603Z
Learning: For bank account input fields, use `autocomplete="bank-account-number"` when the recipient type is `'us'` or `'iban'`.
🪛 Gitleaks (8.21.2)
src/constants/zerodev.consts.ts

16-16: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (20)
src/utils/balance.utils.ts (1)

86-88: ⚠️ Potential issue

Avoid unnecessary chain ID splitting in calculateValuePerChain

In the calculateValuePerChain function, balance.chainId has already been processed and does not require splitting. The line const chainId = balance?.chainId ? balance.chainId.split(':')[1] : '1' may lead to incorrect chain IDs. Consider using const chainId = balance.chainId directly.

Apply this diff to fix the issue:

-const chainId = balance?.chainId ? balance.chainId.split(':')[1] : '1'
+const chainId = balance.chainId

Likely invalid or redundant comment.

src/utils/index.ts (1)

5-5: LGTM!

The new export makes the utility functions in balance.utils.ts accessible, and the change is appropriate.

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

15-16: LGTM! Verify USDC contract address.

The addition of PEANUT_WALLET_TOKEN constant aligns with the PR objective. The address appears to be the USDC contract on Arbitrum.

Let's verify the contract address:

✅ Verification successful

USDC Arbitrum address verified across codebase

The USDC contract address (0xaf88d065e77c8cc2239327c5edb3a432268e5831) is consistently used across the codebase:

  • Used in zerodev.consts.ts as PEANUT_WALLET_TOKEN
  • Referenced in cashout.consts.ts
  • Properly associated with Arbitrum network (PEANUT_WALLET_CHAIN)

The address matches the official USDC contract on Arbitrum and is used consistently throughout the project.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other occurrences of this USDC address to ensure consistency
rg -i "0xaf88d065e77c8cc2239327c5edb3a432268e5831"

Length of output: 265


Script:

#!/bin/bash
# Let's check the context of USDC address usage in cashout.consts.ts
rg -B 3 -A 3 "0xaf88d065e77c8cc2239327c5edb3a432268e5831" src/constants/cashout.consts.ts

# Also check if there are any other USDC-related constants or comments
rg -i "usdc" src/constants/

Length of output: 740


Script:

#!/bin/bash
# Let's verify this address against a known source
# First, let's check if there's any documentation or config mentioning Arbitrum USDC
rg -i -B 2 -A 2 "arbitrum.*usdc|usdc.*arbitrum"

# Also check for any test files or documentation that might validate this address
fd -e md -e test.ts -e spec.ts | xargs rg -i "usdc.*arbitrum|arbitrum.*usdc"

Length of output: 438

🧰 Tools
🪛 Gitleaks (8.21.2)

16-16: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

src/components/Home/WalletToggleButton.tsx (1)

Line range hint 8-17: LGTM! Good performance optimization.

The conversion of toggleWallet to use useCallback is a good optimization since the function is used in the onClick event handler. The dependency array is complete and correctly includes all referenced values.

src/interfaces/wallet.interfaces.ts (1)

32-32: LGTM! Verify IUserBalance interface.

The addition of the optional balances property to IWallet interface is well-structured and maintains backward compatibility.

Let's verify the IUserBalance interface exists:

✅ Verification successful

IUserBalance interface exists and is well-defined

The IUserBalance interface is properly defined in src/interfaces/interfaces.ts with all necessary fields for representing wallet balances including chain ID, token details, amounts and values.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for IUserBalance interface definition
ast-grep --pattern 'interface IUserBalance {
  $$$
}'

Length of output: 666

src/components/Home/WalletCard.tsx (1)

39-45: LGTM: Card content structure simplified

The removal of the Link wrapper while maintaining the onClick handler aligns with the PR's objective to streamline wallet interactions. The content remains clear and actionable.

src/app/(mobile-ui)/wallet/page.tsx (1)

12-12: LGTM: Improved balance display with proper formatting

The balance display now properly uses formatUnits for USDC (6 decimals) with appropriate fallback handling and consistent decimal places.

Also applies to: 43-45

src/components/Global/ChainSelector/index.tsx (2)

10-11: LGTM! Good refactor to use centralized wallet context

The change from useBalance hook to useWallet context with utility functions improves code organization and maintainability.


150-150: LGTM! Proper formatting of token amounts

Good use of the formatTokenAmount utility for consistent display of values.

docs/high_level_overview.md (1)

130-132: Consider expanding wallet management documentation

While removing useBalance documentation aligns with the code changes, consider adding more context about the wallet context and its role in balance management.

src/components/Request/Create/Views/Initial.view.tsx (2)

31-40: LGTM! Good use of wallet context

Clean implementation of wallet context with proper destructuring of required properties.


186-186: LGTM! Proper conditional rendering of TokenSelector

Good implementation of hiding token selector for peanut wallet, aligning with PR objectives.

src/components/Create/Link/Input.view.tsx (2)

268-273: LGTM! Robust balance calculation implementation.

The maxValue calculation is well implemented with proper null checks and formatting.


290-295: LGTM! Verify chain/token defaults for peanut wallet.

The automatic setting of chain and token for peanut wallet improves UX, but let's verify the constants are correctly defined.

✅ Verification successful

Let me gather more information about the arbitrum constant to ensure it's correctly defined.


Let me modify the search pattern to find the arbitrum chain definition.


Let me try one more search to find where arbitrum is imported or defined.


Let me verify the USDC token address on Arbitrum.


Chain and token defaults for peanut wallet are correctly configured

The verification confirms:

  • PEANUT_WALLET_CHAIN is set to Arbitrum mainnet (imported from viem/chains)
  • PEANUT_WALLET_TOKEN is set to the official USDC contract address on Arbitrum (0xaf88d065e77c8cc2239327c5edb3a432268e5831)
  • The chain configuration is properly used in the viem client setup
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify PEANUT_WALLET constants are defined correctly

# Check for constant definitions
rg -A 1 "PEANUT_WALLET_CHAIN|PEANUT_WALLET_TOKEN" "src/constants/"

Length of output: 645


Script:

#!/bin/bash
# Check arbitrum chain definition and any imports
rg -A 3 "^export const arbitrum = {" src/constants/

Length of output: 169


Script:

#!/bin/bash
# Check arbitrum chain definition and any imports
rg -A 5 "const arbitrum =" src/constants/

Length of output: 43


Script:

#!/bin/bash
# Search for arbitrum in any context
rg -B 2 -A 2 "arbitrum" src/constants/

Length of output: 1699


Script:

#!/bin/bash
# Search for any other references to the USDC token address
rg "0xaf88d065e77c8cc2239327c5edb3a432268e5831" -B 2 -A 2

Length of output: 422

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

Line range hint 177-245: LGTM! Improved state management by using wallet context.

The changes correctly migrate from the useBalance hook to accessing balances directly from the wallet context, with proper null coalescing for the empty array fallback.


Line range hint 403-405: LGTM! Successfully implements token selector visibility control.

The conditional rendering effectively hides the token selector for peanut wallet users while maintaining it for external wallets with cross-chain support.

src/components/Request/Pay/Views/Initial.view.tsx (2)

341-349: LGTM! Well-structured wallet-specific token/chain reset logic.

The useCallback implementation correctly handles different defaults for peanut and external wallets, with proper memoization dependencies.


351-353: LGTM! Proper handling of wallet type changes.

The useEffect correctly triggers token/chain reset when the wallet type changes to peanut wallet.

src/components/Create/useCreateLink.tsx (2)

50-55: LGTM! Robust balance checking implementation.

The balance check logic properly handles null cases and uses the balanceByToken utility effectively.


744-744: LGTM! Proper balance refresh after link creation.

The refetchBalances call ensures the wallet state remains in sync after the transaction.

Comment on lines +24 to +35
.map((item: any) => ({
chainId: item?.chainId ? item.chainId.split(':')[1] : '1',
address: item?.address ? item.address.split(':')[2] : '0x0000000000000000000000000000000000000000',
name: item.name,
symbol: item.symbol,
decimals: parseInt(item.quantity.decimals),
price: item.price,
amount: parseFloat(item.quantity.numeric),
currency: 'usd',
logoURI: item.iconUrl,
value: item.value.toString(),
}))
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure type safety and handle potential undefined properties during balance processing

The current implementation assumes that properties like item.name, item.quantity.decimals, and item.price are always defined. This could lead to runtime errors if any of these properties are undefined or null. Consider adding checks or default values to handle missing properties, and define proper TypeScript interfaces for item to ensure type safety.

Comment on lines +36 to +44
.map((balance: any) =>
balance.chainId === '8508132'
? { ...balance, chainId: '534352' }
: balance.chainId === '81032'
? { ...balance, chainId: '81457' }
: balance.chainId === '59160'
? { ...balance, chainId: '59144' }
: balance
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor chain ID remapping logic for better readability

The chain ID remapping logic uses nested ternary operators, which can reduce code readability and increase complexity. Consider refactoring this segment using a mapping object or switch statements for clarity.

Apply this diff to refactor the chain ID remapping:

-.map((balance: any) =>
-    balance.chainId === '8508132'
-        ? { ...balance, chainId: '534352' }
-        : balance.chainId === '81032'
-            ? { ...balance, chainId: '81457' }
-            : balance.chainId === '59160'
-                ? { ...balance, chainId: '59144' }
-                : balance
-)
+const chainIdMapping: { [key: string]: string } = {
+    '8508132': '534352',
+    '81032': '81457',
+    '59160': '59144',
+};
+
+.map((balance: any) => {
+    const mappedChainId = chainIdMapping[balance.chainId] || balance.chainId;
+    return { ...balance, chainId: mappedChainId };
+})

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 290 to 297
onClick={() => {
open()
}}
className="cursor-pointer text-h9 underline"
>
( Buy Tokens )
</div>
)}
Copy link
Contributor

@coderabbitai coderabbitai bot Dec 2, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Undefined function open will cause runtime error

In the click handler for the "Buy Tokens" link, the function open() is called, but open is not defined in the current scope, which will lead to a runtime error when the user clicks the link. Ensure that open is properly imported or defined, or replace it with the correct function.

If the intent is to open a modal for buying tokens, ensure that the appropriate function is called, such as signInModal.open() or another defined function.

Apply this diff to fix the issue:

-onClick={() => {
-    open()
-}}
+onClick={() => {
+    signInModal.open()
+}}

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

adding

Copy link
Contributor

Choose a reason for hiding this comment

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

@jjramirezn, glad to hear you've made the change!

(^_^)/


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

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 and nitpick comments (2)
src/components/Cashout/Components/Initial.view.tsx (2)

287-301: Consider using optional chaining for safer null checks

While the code works, using the non-null assertion operator (!) could lead to runtime errors if the assumptions about nullability are wrong.

Consider this safer approach:

-{selectedWallet!.balances!.length === 0 && (
+{selectedWallet?.balances?.length === 0 && (

221-226: Add missing dependencies to useEffect

The effect hook is missing setSelectedChainID and setSelectedTokenAddress in its dependencies array. While these are stable references from context, it's best practice to include them.

-}, [isPeanutWallet])
+}, [isPeanutWallet, setSelectedChainID, setSelectedTokenAddress])
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7317ecc and 67455d9.

📒 Files selected for processing (1)
  • src/components/Cashout/Components/Initial.view.tsx (7 hunks)
🔇 Additional comments (3)
src/components/Cashout/Components/Initial.view.tsx (3)

12-12: LGTM: New imports and context usage align with PR objectives

The added imports and context values provide the necessary functionality to manage default token selection and chain ID.

Also applies to: 21-21, 35-42


76-77: LGTM: Wallet type differentiation is properly implemented

The addition of wallet type flags (isExternalWallet, isPeanutWallet) and wallet state management enables proper handling of different wallet types, which is crucial for the token selector visibility logic.


199-204: LGTM: Balance calculation is properly implemented

The maxValue calculation correctly handles null checks and uses appropriate formatting with floorFixed. The implementation properly integrates with the wallet-specific balance handling.

@Hugo0
Copy link
Contributor

Hugo0 commented Dec 2, 2024

why are all my coommetns pending

Copy link
Contributor

@Hugo0 Hugo0 left a comment

Choose a reason for hiding this comment

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

Q: After this

<Card.Content className="flex h-full flex-row items-center justify-center">
<div className="text-5xl">{'$ 420.69'}</div>
<div className="text-5xl">
$ {Number(formatUnits(selectedWallet?.balance ?? 0n, 6)).toFixed(2)}
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: balance is bigint. Might be a rlly large number with 21 decimal places (js formates as scientific notation). Not sure toFixed(2) would help here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

formatUnit handles part of that, it will return the USD(C) amount. Unless the balance is too big, in that case you are right and we would have problems with scientific notation.
I have this task https://www.notion.so/peanutprotocol/Bug-X-chain-from-amount-formatted-wrongly-to-scientific-notation-141838117579807abd12ee396cbfee97?pvs=4 to deal with that

Comment on lines 69 to 76
export function balanceByToken(
balances: IUserBalance[],
chainId: string,
tokenAddress: string
): IUserBalance | undefined {
if (!chainId || !tokenAddress) return undefined
return balances.find((balance) => balance.chainId === chainId && areAddressesEqual(balance.address, tokenAddress))
}
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: this fetches an individual token balance - I think the name should reflect that better. E.g. getTokenBalance


const maxValue = useMemo(() => {
const balance = balanceByToken(selectedChainID, selectedTokenAddress)
if (!selectedWallet?.balances) return ''
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: wouldnt it be better to add the following check to balanceByToken:
if (!chainId || !tokenAddress || !balances) return undefined

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think the balances missing case must be handled outside. Also I noticed a bug here, fixing


useEffect(() => {
if (isPeanutWallet) {
setSelectedChainID(PEANUT_WALLET_CHAIN.id.toString())
Copy link
Contributor

Choose a reason for hiding this comment

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

nice

useEffect(() => {
if (isPeanutWallet) {
setSelectedChainID(PEANUT_WALLET_CHAIN.id.toString())
setSelectedTokenAddress(PEANUT_WALLET_TOKEN)
Copy link
Contributor

Choose a reason for hiding this comment

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

thought: we miiiiiiiiiiight want to support other tokens in the future. Depends on demand and situation. E.g. maybe we find out ppinta token is great for onboarding and we run a promotion campaign partnering with them. Not sure what the best to do in that case would be here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is a great point and we have to think how we handle it. The idea of PW is absolute abstraction, but that comes with reduced functionality, like you mentioned (and PNT or MORFI are great onboarding tools).

One inmediate issue I can see is what do we do with claim links that contains tokens not supported for x-chain

return valueB - valueA
})

const totalBalance = processedBalances.reduce((acc: number, balance: any) => acc + Number(balance.value), 0)
Copy link
Contributor

Choose a reason for hiding this comment

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

Q: Number instead of bigint? 🤔

Copy link
Contributor

Choose a reason for hiding this comment

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

(balance.value is bigint )

...createDefaultDBWallet(wagmiAddress),
connected: isWalletConnected(createDefaultDBWallet(wagmiAddress)),
balances,
balance: BigInt(Math.floor(totalBalance * 1e6)),
Copy link
Contributor

Choose a reason for hiding this comment

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

Q: why Math.floor(totalBalance * 1e6)? This seems arbitrary and would benefit either of a comment or from implementing in fetchWalletbalances

Copy link
Contributor Author

Choose a reason for hiding this comment

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

balance is expected to be expressed as the base units amount of USDC (in the peanut wallet case) so this converts from the usd amount to that.

Copy link
Contributor

Choose a reason for hiding this comment

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

imo this type of stuff should be commented in the code since it's very idiosyncratic

>
( Buy Tokens )
</div>
{isExternalWallet && (
Copy link
Contributor

Choose a reason for hiding this comment

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

nice

### Hooks
The `/hooks` folder contains two custom hooks to help manage wallet functionality:
The `/hooks` folder contains a custom hook to help manage wallet functionality:
Copy link
Contributor

Choose a reason for hiding this comment

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

lets remove then @jjramirezn

Copy link
Contributor

@Hugo0 Hugo0 left a comment

Choose a reason for hiding this comment

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

Q: After this

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: 1

🧹 Outside diff range and nitpick comments (1)
src/context/walletContext/walletContext.tsx (1)

177-216: Ensure error handling provides meaningful feedback

While the console.error statement logs errors during the refetchBalances operation, consider implementing more robust error handling to inform the user or trigger retries if appropriate. This will enhance the reliability and user experience of the application.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 67455d9 and 45af86b.

📒 Files selected for processing (4)
  • docs/high_level_overview.md (0 hunks)
  • src/components/Cashout/Components/Initial.view.tsx (7 hunks)
  • src/components/Create/Link/Input.view.tsx (6 hunks)
  • src/context/walletContext/walletContext.tsx (7 hunks)
💤 Files with no reviewable changes (1)
  • docs/high_level_overview.md
🧰 Additional context used
📓 Learnings (1)
src/context/walletContext/walletContext.tsx (1)
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#551
File: src/context/walletContext/walletContext.tsx:87-88
Timestamp: 2024-12-02T17:21:45.515Z
Learning: When converting `totalBalance` (in USD) to a `BigInt` balance in `src/context/walletContext/walletContext.tsx`, multiplying by `1e6` is intentional to maintain compatibility with USDC's 6 decimal places. The application displays only 2 decimal places, so this level of precision is sufficient.
🔇 Additional comments (2)
src/components/Create/Link/Input.view.tsx (1)

338-340: ⚠️ Potential issue

Undefined function open will cause runtime error

The open() function used in the onClick handler is not defined in the current scope, which will lead to a runtime error when the user clicks the link. Ensure that open is properly defined or replace it with the correct function.

Apply this diff to fix the issue:

- onClick={() => {
-   open()
- }}
+ onClick={() => {
+   signInModal.open()
+ }}
src/components/Cashout/Components/Initial.view.tsx (1)

292-293: 🛠️ Refactor suggestion

Potential null reference when accessing selectedWallet.balances

Using non-null assertions ! with selectedWallet!.balances!.length might cause a runtime error if selectedWallet or balances is undefined. Consider using optional chaining or adding null checks to prevent potential crashes.

Apply this diff to fix the issue:

-{selectedWallet!.balances!.length === 0 && (
+{selectedWallet?.balances?.length === 0 && (

Comment on lines +336 to +337
{selectedWallet!.balances!.length === 0 && (
<div
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential null reference when accessing selectedWallet.balances

Using non-null assertions ! with selectedWallet!.balances!.length might cause a runtime error if selectedWallet or balances is undefined. Consider using optional chaining or adding null checks to prevent potential crashes.

Apply this diff to fix the issue:

-{selectedWallet!.balances!.length === 0 && (
+{selectedWallet?.balances?.length === 0 && (
📝 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
{selectedWallet!.balances!.length === 0 && (
<div
{selectedWallet?.balances?.length === 0 && (
<div

@jjramirezn jjramirezn merged commit cab3010 into peanut-wallet Dec 3, 2024
4 checks passed
@jjramirezn jjramirezn deleted the feat/default-selection-for-pw branch December 3, 2024 10:23
@coderabbitai coderabbitai bot mentioned this pull request Dec 29, 2024
@coderabbitai coderabbitai bot mentioned this pull request Apr 9, 2025
@coderabbitai coderabbitai bot mentioned this pull request Apr 18, 2025
@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