Skip to content

Conversation

jjramirezn
Copy link
Contributor

Fixes

  • Take symbol and logo from fetch price in case is not in the sdk constants
  • Disable the confirm button again if deleting the value from the input

Refactor

Did a performance focused refactor on the Request Pay view, instead of making all calls one after another and wait for all to be finished, now we do in parallel what doesn't depend on each other and render progressively

Load logo and symbol correctly from mobula if not found in sdk, also
added some type safety to the tokenPriceData.

Refs: #79
Avoid "A component is changing an uncontrolled input to be controlled"
error
Go into initial view immediately after the request link data is fetched.
Then fetch the price, gas and points as the necessary data is available.
Parallel when possible.
Copy link

vercel bot commented Oct 7, 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 Oct 7, 2024 4:25pm

Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several enhancements to various components and hooks within the application. Key changes include improved error handling in the useCreateLink hook for fetching token prices, updates to state management in the InitialView component, and modifications to the Pay component to handle token price data more effectively. Additionally, new type definitions for token price data are introduced, and existing interfaces are updated to reflect these changes. Overall, the modifications focus on enhancing robustness, clarity, and maintainability in the codebase.

Changes

File Path Change Summary
src/components/Create/useCreateLink.tsx Enhanced error handling in estimateGasFee and user balance checks in checkUserHasEnoughBalance. Updated control flow in prepareCreateLinkWrapper.
src/components/Request/Pay/Pay.consts.ts Changed tokenPrice to optional tokenPriceData of type ITokenPriceData in IPayScreenProps. Updated IRequestLinkState to include 'READY_TO_PAY'.
src/components/Request/Pay/Pay.tsx Replaced tokenPrice with tokenPriceData, updated calculations, and introduced fetchRecipientAddress for ENS resolution. Enhanced error management in request link state.
src/components/Request/Pay/Views/GeneralViews/Error.view.tsx Replaced NotFoundClaimLink with a new ErrorView component that accepts a dynamic errorMessage.
src/components/Request/Pay/Views/GeneralViews/index.ts Updated exports to replace NotFound.view with Error.view.
src/components/Request/Pay/Views/Initial.view.tsx Renamed tokenPrice to tokenPriceData, added state variables for token logo and symbol, and updated transaction fee estimation logic.

Possibly related PRs

Suggested labels

Being worked on

Suggested reviewers

  • Hugo0

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d188d3f and 181f48a.

📒 Files selected for processing (2)
  • src/components/Request/Pay/Pay.tsx (5 hunks)
  • src/components/Request/Pay/Views/GeneralViews/Error.view.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Request/Pay/Pay.tsx
🧰 Additional context used
🔇 Additional comments (2)
src/components/Request/Pay/Views/GeneralViews/Error.view.tsx (2)

6-6: Great job addressing the previous review comment and improving component flexibility!

The component has been successfully renamed to ErrorView, addressing the issue of shadowing the global Error object. Additionally, the introduction of the errorMessage prop enhances the component's reusability by allowing dynamic error messages.

Also applies to: 10-10


35-35: Default export correctly updated

The default export has been properly updated to reflect the new component name ErrorView. This change maintains consistency throughout the file.


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.

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

🧹 Outside diff range and nitpick comments (5)
src/components/Request/Pay/Pay.consts.ts (1)

Line range hint 1-58: Summary: Improved token price data handling

The changes in this file represent a positive step towards more detailed and flexible token price data handling. The shift from a simple number type to a more complex ITokenPriceData type aligns well with the PR objectives and should allow for better handling of token symbols and logos.

Key points:

  1. The new import and interface change maintain type safety and follow TypeScript best practices.
  2. The tokenPriceData property is now optional, which provides more flexibility but may require additional null checks in component logic.
  3. These changes may necessitate updates in components that use the IPayScreenProps interface.

Consider adding a brief comment above the IPayScreenProps interface to explain the purpose of tokenPriceData and why it's optional. This would help other developers understand the design decision and how to properly use this property.

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

36-37: Consider using a more descriptive name for _tokenValue

While the changes effectively address the PR objectives and improve the component's robustness, consider using a more descriptive name for the _tokenValue state variable. A name like inputTokenValue or currentTokenValue might better convey its purpose and relationship to the input field.

This is a minor suggestion for improved code readability and doesn't affect the functionality of the changes.

Also applies to: 160-160

src/interfaces/interfaces.ts (1)

66-69: LGTM with a minor suggestion.

The new ITokenPriceData type effectively combines token information with chain-specific price data, which aligns with the PR objective of fetching symbol and logo from price data.

However, there's a potential property duplication. The IToken interface already includes a chainId property, so extending it and adding chainId again might be redundant.

Consider modifying the type definition to avoid duplication:

export type ITokenPriceData = IToken & {
    price: number
}

This change ensures that chainId is only defined once, reducing the risk of inconsistencies.

src/utils/fetch.utils.ts (1)

Line range hint 95-97: Include error details in the catch block logging

Currently, the catch block logs a generic message without the error details. Including the error object can provide more context for debugging.

Consider updating the log statement:

 } catch (error) {
-    console.log('error fetching token price for token ' + tokenAddress + ' on chain ' + chainId)
+    console.error('Error fetching token price for token ' + tokenAddress + ' on chain ' + chainId + ':', error)
     return undefined
 }
src/components/Request/Pay/Pay.tsx (1)

134-142: Improve error handling when estimating gas fees

In the estimateGasFee call, errors are only logged to the console. This might not provide sufficient feedback to the user if gas estimation fails.

Consider handling the error more proactively by setting an error state or informing the user about the failure to estimate gas fees. This will improve the user experience by providing meaningful feedback.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 062ca50 and de8ebd5.

📒 Files selected for processing (8)
  • src/components/Create/useCreateLink.tsx (2 hunks)
  • src/components/Request/Create/Views/Initial.view.tsx (2 hunks)
  • src/components/Request/Pay/Pay.consts.ts (2 hunks)
  • src/components/Request/Pay/Pay.tsx (4 hunks)
  • src/components/Request/Pay/Views/Initial.view.tsx (12 hunks)
  • src/context/tokenSelector.context.tsx (4 hunks)
  • src/interfaces/interfaces.ts (1 hunks)
  • src/utils/fetch.utils.ts (2 hunks)
🧰 Additional context used
📓 Learnings (3)
src/components/Request/Create/Views/Initial.view.tsx (1)
Learnt from: Hugo0
PR: peanutprotocol/peanut-ui#413
File: src/components/Request/Pay/Views/Initial.view.tsx:71-72
Timestamp: 2024-10-04T13:10:49.199Z
Learning: In `src/components/Request/Pay/Views/Initial.view.tsx`, it's acceptable to use the `!` operator in TypeScript to assert that `selectedTokenData` is not `null` or `undefined`, and potential runtime errors from accessing its properties without checks can be disregarded.
src/components/Request/Pay/Views/Initial.view.tsx (2)
Learnt from: Hugo0
PR: peanutprotocol/peanut-ui#413
File: src/components/Request/Pay/Views/Initial.view.tsx:71-72
Timestamp: 2024-10-04T13:10:49.199Z
Learning: In `src/components/Request/Pay/Views/Initial.view.tsx`, it's acceptable to use the `!` operator in TypeScript to assert that `selectedTokenData` is not `null` or `undefined`, and potential runtime errors from accessing its properties without checks can be disregarded.
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#410
File: src/components/Request/Pay/Views/Initial.view.tsx:87-93
Timestamp: 2024-10-03T14:57:44.520Z
Learning: When refactoring to eliminate code duplication, prioritize readability and consider whether the change significantly improves the code. If it doesn't enhance readability or maintainability, it's acceptable to keep the existing code structure.
src/context/tokenSelector.context.tsx (2)
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#413
File: src/context/tokenSelector.context.tsx:118-123
Timestamp: 2024-10-04T13:40:16.067Z
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.
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#404
File: src/context/tokenSelector.context.tsx:121-121
Timestamp: 2024-10-03T09:57:43.885Z
Learning: In `TokenContextProvider` within `tokenSelector.context.tsx`, when token data is loaded from preferences, it's acceptable to set `isTokenPriceFetchingComplete` to `true` because the token data is already available.
🔇 Additional comments (10)
src/components/Request/Pay/Pay.consts.ts (1)

3-3: LGTM: New import for ITokenPriceData

The new import statement is correctly formatted and follows TypeScript best practices. It's a necessary addition to support the changes in the IPayScreenProps interface.

src/context/tokenSelector.context.tsx (5)

7-7: LGTM: New import for ITokenPriceData

The addition of this import is consistent with the changes in the component's state management. It's good practice to import only what's necessary.


42-42: LGTM: Consistent state type for selectedTokenData

The update of the selectedTokenData state type to ITokenPriceData | undefined is consistent with the earlier context type change. This maintains type consistency between the state and the context.


Line range hint 146-146: LGTM: Added selectedTokenData to context value

The addition of selectedTokenData to the context provider value is consistent with the earlier changes and makes this data available to consuming components. This change completes the integration of the new ITokenPriceData type throughout the component.


27-27: Verify consistency of ITokenPriceData usage

The type change for selectedTokenData to ITokenPriceData | undefined is appropriate given the new import. This change suggests a shift in the data structure being used for token information.

Please ensure this type change is consistently applied throughout the component. Run the following script to verify:

✅ Verification successful

Consistent Update of ITokenPriceData Verified

The type change for selectedTokenData to ITokenPriceData | undefined is appropriately reflected throughout the codebase. No remaining usages of ITokenData were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of ITokenPriceData

# Test: Search for occurrences of ITokenPriceData
rg --type typescript 'ITokenPriceData'

# Test: Search for any remaining occurrences of ITokenData
rg --type typescript 'ITokenData'

Length of output: 142


Script:

#!/bin/bash
# Description: Check for consistent usage of ITokenPriceData

# Test: Search for occurrences of ITokenPriceData in TypeScript files
rg --type ts 'ITokenPriceData'
rg --type tsx 'ITokenPriceData'

# Test: Search for any remaining occurrences of ITokenData in TypeScript files
rg --type ts 'ITokenData'
rg --type tsx 'ITokenData'

Length of output: 1190


Script:

#!/bin/bash
# Description: Check for consistent usage of ITokenPriceData and ITokenData in .ts and .tsx files

# Find all .ts and .tsx files and search for ITokenPriceData
fd -e ts -e tsx | xargs rg 'ITokenPriceData'

# Find all .ts and .tsx files and search for ITokenData
fd -e ts -e tsx | xargs rg 'ITokenData'

Length of output: 1103


82-82: Verify tokenPriceResponse structure

The direct assignment of tokenPriceResponse to selectedTokenData simplifies the code and aligns with the new ITokenPriceData type. This change is good for maintaining data consistency.

To ensure robustness, please verify that tokenPriceResponse always conforms to the ITokenPriceData interface. Consider adding a type check or using a type guard. Run the following script to check the structure of tokenPriceResponse:

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

36-37: Improved state initialization for _tokenValue

This change enhances the robustness of the component by ensuring that _tokenValue is always initialized as a string. By providing a default empty string when the computed value is undefined, it prevents potential type-related issues and aligns with TypeScript best practices.

This modification also addresses the PR objective of reinstating the functionality to disable the confirm button when the value is deleted from the input field, as an empty string will be falsy in the button's disabled condition.


160-160: Updated disabled condition for confirm button

This change successfully implements the PR objective of disabling the confirm button when the value is deleted from the input field. By using _tokenValue in the disabled condition, it correctly reflects the current state of the input, including when it's an empty string.

The modification maintains the existing checks for valid recipient, input changing state, and loading state, ensuring that all necessary conditions are met before enabling the button.

src/interfaces/interfaces.ts (1)

Line range hint 1-70: File structure and organization look good.

The addition of the ITokenPriceData type is well-placed within the file, maintaining a logical organization of related interfaces and types. The new type doesn't introduce any breaking changes to existing interfaces, and the overall file structure remains consistent and organized.

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

250-253: Validate nativeTokenPrice.price before using it

This issue is the same as described in lines 227-230. Ensure that nativeTokenPrice.price is validated before performing calculations to prevent potential errors.

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.

Please resolve all the comments - otherwise looks good

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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 (2)
src/components/Request/Pay/Views/Initial.view.tsx (2)

4-4: LGTM! Minor suggestion for prop naming consistency.

The addition of useMemo and the renaming of tokenPrice to tokenPriceData are good improvements. They suggest performance optimization and better data structure representation.

Consider updating other occurrences of tokenPrice to tokenPriceData throughout the codebase for consistency, if not already done.

Also applies to: 24-24


125-145: LGTM! Improved token info handling. Minor safety suggestion.

The new logic for setting tokenRequestedLogoURI and tokenRequestedSymbol enhances the UI's ability to display accurate token information. The fallback to fetchTokenSymbol ensures that the symbol is always available.

Consider adding a null check before calling toUpperCase() to prevent potential runtime errors:

- ?.symbol.toUpperCase() ??
+ ?.symbol?.toUpperCase() ??
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between de8ebd5 and edb6dfd.

📒 Files selected for processing (1)
  • src/components/Request/Pay/Views/Initial.view.tsx (12 hunks)
🧰 Additional context used
📓 Learnings (1)
src/components/Request/Pay/Views/Initial.view.tsx (1)
Learnt from: Hugo0
PR: peanutprotocol/peanut-ui#413
File: src/components/Request/Pay/Views/Initial.view.tsx:71-72
Timestamp: 2024-10-04T13:10:49.199Z
Learning: In `src/components/Request/Pay/Views/Initial.view.tsx`, it's acceptable to use the `!` operator in TypeScript to assert that `selectedTokenData` is not `null` or `undefined`, and potential runtime errors from accessing its properties without checks can be disregarded.
🔇 Additional comments (5)
src/components/Request/Pay/Views/Initial.view.tsx (5)

76-78: LGTM! Good use of useMemo for performance optimization.

The memoization of calculatedFee is a smart performance optimization. It ensures that the fee is only recalculated when its dependencies change.


Line range hint 114-124: LGTM! Improved cross-chain detection and optimization.

The updates to the isXChain logic and the early return condition in the useEffect hook enhance the accuracy of cross-chain transaction detection and prevent unnecessary calculations.


170-170: LGTM! Consistent use of renamed prop.

The replacement of tokenPrice with tokenPriceData in the handleOnNext function maintains consistency with the earlier prop renaming.


296-302: LGTM! Improved consistency and UI responsiveness.

The updates in the JSX return statement, including the use of tokenPriceData, tokenRequestedSymbol, and the additional check for calculatedFee in the button's disabled state, enhance the overall consistency and responsiveness of the component.

Also applies to: 319-319, 338-342, 364-368, 387-392


Line range hint 1-424: Overall, excellent improvements to the InitialView component.

The changes in this file significantly enhance token handling, error management, and UI responsiveness. The introduction of new state variables, memoization for performance, and improved logic for cross-chain detection are all positive additions. The code is well-structured and follows good practices.

A few minor suggestions were made:

  1. Add error handling to the fetchTokenSymbol function.
  2. Add a null check before calling toUpperCase() on the token symbol.
  3. Ensure consistency in prop naming across the codebase.

Great work on these improvements!

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 3

🧹 Outside diff range and nitpick comments (1)
src/components/Request/Pay/Views/Initial.view.tsx (1)

296-302: LGTM: Improved token display and button state handling

The updates to the JSX improve the consistency of token price and symbol display. The use of tokenRequestedSymbol and tokenPriceData aligns with the earlier changes. The enhanced button disabled state logic is a good improvement.

Consider extracting the complex disabled state logic into a separate variable for improved readability:

+ const isButtonDisabled = linkState === RequestStatus.LOADING ||
+    linkState === RequestStatus.NOT_FOUND ||
+    isLoading ||
+    (linkState === RequestStatus.CLAIM && !calculatedFee);

<button
    className="wc-disable-mf btn-purple btn-xl "
-    disabled={
-        linkState === RequestStatus.LOADING ||
-        linkState === RequestStatus.NOT_FOUND ||
-        isLoading ||
-        (linkState === RequestStatus.CLAIM && !calculatedFee)
-    }
+    disabled={isButtonDisabled}
    onClick={() => {
        if (!isConnected) handleConnectWallet()
        else if (RequestStatus.CLAIM === linkState) handleOnNext()
    }}
>

This change would make the JSX more readable and the disabled state logic easier to understand at a glance.

Also applies to: 319-319, 338-342, 387-392

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between edb6dfd and 2d15956.

📒 Files selected for processing (1)
  • src/components/Request/Pay/Views/Initial.view.tsx (12 hunks)
🧰 Additional context used
📓 Learnings (1)
src/components/Request/Pay/Views/Initial.view.tsx (1)
Learnt from: Hugo0
PR: peanutprotocol/peanut-ui#413
File: src/components/Request/Pay/Views/Initial.view.tsx:71-72
Timestamp: 2024-10-04T13:10:49.199Z
Learning: In `src/components/Request/Pay/Views/Initial.view.tsx`, it's acceptable to use the `!` operator in TypeScript to assert that `selectedTokenData` is not `null` or `undefined`, and potential runtime errors from accessing its properties without checks can be disregarded.
🔇 Additional comments (4)
src/components/Request/Pay/Views/Initial.view.tsx (4)

4-4: LGTM: Import and prop updates enhance functionality

The addition of useMemo and the renaming of tokenPrice to tokenPriceData are good improvements. These changes suggest better performance optimization and more comprehensive token price handling.

Also applies to: 24-24


Line range hint 79-124: LGTM: Improved error handling and state management

The updates to the useEffect hook enhance the component's ability to handle cross-chain transactions and various error scenarios. The state updates and error handling are comprehensive, improving the overall robustness of the component.


170-170: LGTM: Consistent renaming of tokenPrice to tokenPriceData

The change from tokenPrice to tokenPriceData in the handleOnNext function is consistent with the earlier prop renaming. The overall logic for handling transactions remains intact and appears to be functioning correctly.


Line range hint 1-420: Overall assessment: Good improvements with minor suggestions

The changes to the InitialView component significantly enhance its functionality, particularly in terms of token information handling, fee calculation, and error management. The use of useMemo for performance optimization and the improved state management are commendable.

Key improvements:

  1. Better handling of token symbol and logo URI
  2. Enhanced fee calculation with cross-chain support
  3. Improved error handling and state management
  4. Consistent updates to use tokenPriceData instead of tokenPrice

The suggested changes in the review comments, such as adding error handling to fetchTokenSymbol and ensuring consistent return types in calculatedFee, will further improve the robustness of the component.

Overall, these changes represent a solid improvement to the codebase. Once the minor suggestions are addressed, this PR will be ready for merge.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 2

🧹 Outside diff range and nitpick comments (4)
src/components/Request/Pay/Views/GeneralViews/Error.view.tsx (1)

35-35: Update the default export name if you rename the component.

If you rename the component as suggested earlier, make sure to update the default export as well.

Here's the change you should make if you rename the component:

-export default Error
+export default ErrorView
src/components/Request/Pay/Views/Initial.view.tsx (1)

125-145: Updated useEffect for token data

This useEffect hook has been significantly modified to handle setting the tokenRequestedLogoURI and tokenRequestedSymbol. It now includes fallback logic and uses the new fetchTokenSymbol function when necessary.

However, there's a potential improvement:

Consider extracting the logic for setting tokenRequestedLogoURI and tokenRequestedSymbol into separate functions to improve readability:

const setTokenRequestedData = () => {
    const chainDetails = consts.peanutTokenDetails.find((chain) => chain.chainId === requestLinkData.chainId)
    const logoURI =
        chainDetails?.tokens.find((token) =>
            utils.areTokenAddressesEqual(token.address, requestLinkData.tokenAddress)
        )?.logoURI ?? tokenPriceData?.logoURI
    setTokenRequestedLogoURI(logoURI)

    let tokenSymbol =
        requestLinkData.tokenSymbol ??
        chainDetails?.tokens.find((token) => utils.areTokenAddressesEqual(token.address, requestLinkData.tokenAddress))
            ?.symbol?.toUpperCase() ??
        tokenPriceData?.symbol
    
    if (tokenSymbol) {
        setTokenRequestedSymbol(tokenSymbol)
    } else {
        fetchTokenSymbol(requestLinkData.chainId, requestLinkData.tokenAddress)
    }
}

useEffect(() => {
    setTokenRequestedData()
}, [requestLinkData, tokenPriceData])
src/components/Create/useCreateLink.tsx (2)

227-229: Improved error handling, but consider using Number.isNaN

The changes improve error handling by checking if nativeTokenPrice is valid before using it. This addresses the PR objective of ensuring proper data fetching. However, consider using Number.isNaN instead of isNaN for safer type checking.

Consider updating the condition as follows:

- if (!nativeTokenPrice || typeof nativeTokenPrice.price !== 'number' || isNaN(nativeTokenPrice.price)) {
+ if (!nativeTokenPrice || typeof nativeTokenPrice.price !== 'number' || Number.isNaN(nativeTokenPrice.price)) {
    throw new Error('Failed to fetch token price')
}

This change will make the type checking more robust and avoid potential issues with type coercion.

🧰 Tools
🪛 Biome

[error] 227-227: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


250-253: Consider adding additional checks for consistency

The error handling improvements in the catch block are good, but they're not as comprehensive as the checks added earlier in the function. For consistency and robustness, consider adding the same level of checking here as well.

Consider updating the condition in the catch block as follows:

- if (!nativeTokenPrice) {
+ if (!nativeTokenPrice || typeof nativeTokenPrice.price !== 'number' || Number.isNaN(nativeTokenPrice.price)) {
    throw new Error('Failed to fetch token price')
}

This will ensure consistent error handling throughout the function.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2d15956 and d188d3f.

📒 Files selected for processing (6)
  • src/components/Create/useCreateLink.tsx (2 hunks)
  • src/components/Request/Pay/Pay.consts.ts (3 hunks)
  • src/components/Request/Pay/Pay.tsx (5 hunks)
  • src/components/Request/Pay/Views/GeneralViews/Error.view.tsx (2 hunks)
  • src/components/Request/Pay/Views/GeneralViews/index.ts (1 hunks)
  • src/components/Request/Pay/Views/Initial.view.tsx (12 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/components/Request/Pay/Views/GeneralViews/index.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Request/Pay/Pay.consts.ts
  • src/components/Request/Pay/Pay.tsx
🧰 Additional context used
📓 Learnings (1)
src/components/Request/Pay/Views/Initial.view.tsx (3)
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#422
File: src/components/Request/Pay/Views/Initial.view.tsx:76-78
Timestamp: 2024-10-07T15:28:25.280Z
Learning: In `src/components/Request/Pay/Views/Initial.view.tsx`, both `txFee` and `utils.formatTokenAmount(estimatedGasCost, 3)` return strings, ensuring consistent return types for `calculatedFee`.
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#422
File: src/components/Request/Pay/Views/Initial.view.tsx:76-78
Timestamp: 2024-10-07T15:25:45.170Z
Learning: In `src/components/Request/Pay/Views/Initial.view.tsx`, both `txFee` and `utils.formatTokenAmount(...)` return strings, ensuring that `calculatedFee` consistently returns a string without the need for additional type conversion.
Learnt from: Hugo0
PR: peanutprotocol/peanut-ui#413
File: src/components/Request/Pay/Views/Initial.view.tsx:71-72
Timestamp: 2024-10-04T13:10:49.199Z
Learning: In `src/components/Request/Pay/Views/Initial.view.tsx`, it's acceptable to use the `!` operator in TypeScript to assert that `selectedTokenData` is not `null` or `undefined`, and potential runtime errors from accessing its properties without checks can be disregarded.
🪛 Biome
src/components/Create/useCreateLink.tsx

[error] 227-227: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

src/components/Request/Pay/Views/GeneralViews/Error.view.tsx

[error] 6-6: Do not shadow the global "Error" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

🔇 Additional comments (14)
src/components/Request/Pay/Views/GeneralViews/Error.view.tsx (2)

10-10: Good job implementing dynamic error message display.

The change from a static message to a dynamic one using the errorMessage prop improves the component's flexibility and reusability.


Line range hint 6-35: Overall, good improvements to error handling and component flexibility.

The changes in this file align well with the PR objectives of improving error handling. The new Error component (which I suggest renaming to ErrorView) provides more flexibility by accepting a dynamic error message. This enhancement improves the reusability of the component across different error scenarios.

The structure and styling of the component have been maintained, ensuring consistency with the previous version. The addition of the dynamic error message display is a positive change that will make error reporting more informative and adaptable.

Once the naming issue is addressed, these changes will contribute to a more robust and maintainable codebase.

🧰 Tools
🪛 Biome

[error] 6-6: Do not shadow the global "Error" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

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

4-4: New import added

The useMemo hook has been imported from 'react'. This is a good addition as it can help optimize performance by memoizing expensive computations.


24-24: Prop name change

The prop tokenPrice has been renamed to tokenPriceData. This change improves clarity by indicating that the prop contains more than just the price.


44-45: New state variables added

Two new state variables, tokenRequestedLogoURI and tokenRequestedSymbol, have been introduced. These variables will help manage the logo URI and symbol of the requested token, improving the component's ability to display token information.


54-54: Updated property access

The tokenAddress property has been replaced with address when accessing selectedTokenData. This change aligns with the updated data structure and improves consistency.

Also applies to: 61-61


76-78: New memoized value: calculatedFee

The calculatedFee is now computed using useMemo, which is a good optimization. It determines the fee based on whether the transaction is cross-chain or not.


170-170: Updated USD amount calculation

The calculation of amountUsd now uses the tokenPriceData.price instead of tokenPrice.price. This change aligns with the renamed prop and ensures correct USD amount calculation.


296-302: Updated token amount display

The component now uses tokenPriceData instead of tokenPrice for displaying the token amount in USD. If tokenPriceData is not available, it falls back to displaying the amount in the requested token's symbol.


319-319: Updated token symbol display

The component now uses tokenRequestedSymbol for displaying the token symbol, which is more accurate as it's derived from multiple sources including the contract itself if necessary.


338-342: Improved fee display

The component now uses the memoized calculatedFee for displaying the network cost. If the fee is not yet calculated, it shows a loading animation, which improves the user experience.


364-368: Improved points display

Similar to the fee display, the points display now shows a loading animation when the points are not yet calculated. This provides a consistent user experience across the component.


387-392: Updated button disabled state

The Pay button's disabled state now includes a check for calculatedFee. This ensures that the button is not clickable until all necessary data is available, preventing potential errors.

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

Line range hint 1-853: Request for clarification on performance improvements

The changes reviewed contribute to improved error handling and data fetching, which is great. However, the PR objectives mention performance improvements, particularly in handling requests in the Request Pay view. These improvements are not immediately apparent in the visible changes.

Could you please clarify where the performance improvements mentioned in the PR objectives are implemented? Are they in a different file or part of the code that's not visible in this diff?

To help locate these changes, you could run the following command:

This will search for relevant keywords in TypeScript and TSX files, which might help identify where the performance improvements have been implemented.

🧰 Tools
🪛 Biome

[error] 227-227: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@coderabbitai coderabbitai bot mentioned this pull request Mar 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants