Skip to content

Fix/cashout rework#388

Merged
Hugo0 merged 3 commits intodevelopfrom
fix/cashout-rework
Sep 25, 2024
Merged

Fix/cashout rework#388
Hugo0 merged 3 commits intodevelopfrom
fix/cashout-rework

Conversation

@Hugo0
Copy link
Copy Markdown
Contributor

@Hugo0 Hugo0 commented Sep 20, 2024

WIP

missing:

  • make sure confirm view works + add types
  • link cashout?
  • QA
  • small misc:
  • sizing of X thing
  • save offramp link to localStorage straight after creating it (and before finalizing everth else) just in case

Summary by CodeRabbit

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced cashout process with defined limits ($10 minimum, $101,000 maximum).
    • New chat support button added in the FAQ section.
    • Updated instructions for payment requests to clarify user actions.
  • Improvements

    • Streamlined user interface for bank account selection and cashout options.
    • Enhanced error messaging for cashout limits.
    • Improved accessibility of login fields with autofill attributes.
    • Added logging for successful fetching of liquidation addresses.
  • Bug Fixes

    • Adjusted Sentry configuration to conditionally activate based on the environment.
  • Maintenance

    • Updated various dependencies to improve functionality and security.
    • Added functionality to update offramp links in local storage.

@vercel
Copy link
Copy Markdown

vercel bot commented Sep 20, 2024

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

Name Status Preview Comments Updated (UTC)
peanut-ui 🛑 Canceled (Inspect) Sep 25, 2024 10:09am

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Sep 20, 2024

Caution

Review failed

The pull request is closed.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several changes across multiple files, including updates to configuration files, enhancements to user interface components, and modifications to the handling of dependencies. Key changes include the addition of a .gitignore entry for .patch files, conditional exports for Sentry configurations based on the environment, updates to various dependencies in package.json, and improvements in user interface components related to cashout processes and login functionalities.

Changes

File(s) Change Summary
.gitignore Added entry to ignore **.patch files.
next.config.js Modified to conditionally export Sentry configuration based on NODE_ENV.
package.json Updated multiple dependencies to newer versions, including libraries like next, axios, and typescript.
sentry.server.config.ts Enabled the spotlight option in Sentry configuration based on NODE_ENV.
src/components/Cashout/Components/Confirm.view.tsx Introduced new functions for fetching necessary details and processing link details, enhancing the organization and clarity of the code.
src/components/Cashout/Components/Faq.comp.tsx Restructured content display in the FAQ component, simplifying the presentation and adding a chat support button.
src/components/Cashout/Components/Initial.view.tsx Implemented cashout limits and improved bank account selection UI, including error handling for cashout limits.
src/components/Global/Header/index.tsx Updated className property to include a higher z-index for the header component.
src/components/Global/LoginComponent/index.tsx Enhanced input fields for email and password with additional attributes for better accessibility.
src/components/Request/Create/Views/Initial.view.tsx Updated text in labels to clarify payment request instructions.
src/config/peanut.config.tsx Commented out LogRocket initialization and added console log for NODE_ENV.
src/config/wagmi.config.tsx Modified Web3 modal configuration to disable email authentication and commented out social authentication options.

Possibly related PRs

  • Fix/cashout rework #388: This PR directly relates to the main PR as it also modifies the .gitignore file by adding the line **.patch, indicating that both PRs are addressing the same change in the .gitignore 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
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 8

Outside diff range and nitpick comments (4)
src/config/wagmi.config.tsx (1)

71-72: Remove the console log statement before deploying to production.

The console log statement is used for debugging purposes and should be removed before deploying to production to avoid cluttering the console.

Apply this diff to remove the console log statement:

-console.log('Created Web3modal')
src/components/Cashout/Components/Initial.view.tsx (2)

365-366: Simplify the disabled condition by removing unnecessary double negation.

The variables isBelowMinLimit and isExceedingMaxLimit are booleans. The use of double negation (!!) is unnecessary. You can simplify the disabled condition by removing the !!.

Apply this diff to simplify the code:

 disabled={
     !_tokenValue ||
     (!selectedBankAccount && !newBankAccount) ||
     !xchainAllowed ||
-    !!isBelowMinLimit ||
-    !!isExceedingMaxLimit
+    isBelowMinLimit ||
+    isExceedingMaxLimit
 }

215-215: Use lowercase 'fiat' for consistency.

The term 'fiat' is commonly written in lowercase as it is not an acronym. For consistency and readability, consider changing 'FIAT' to 'fiat'.

Apply this diff to make the change:

-Convert your crypto to FIAT. From any token, any chain, directly to your bank account.
+Convert your crypto to fiat. From any token, any chain, directly to your bank account.
src/components/Cashout/Components/Confirm.view.tsx (1)

282-282: Add TypeScript type annotations to 'error' parameter for better type safety

In line 282, the handleError function lacks a type annotation for its error parameter, which can help with type checking and code readability.

Apply this diff to add a type annotation:

-        const handleError = (error) => {
+        const handleError = (error: unknown) => {

Consider using a more specific type if possible, such as Error or a custom error type.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3e22bb9 and c4e0996.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (12)
  • .gitignore (1 hunks)
  • next.config.js (2 hunks)
  • package.json (3 hunks)
  • sentry.server.config.ts (1 hunks)
  • src/components/Cashout/Components/Confirm.view.tsx (5 hunks)
  • src/components/Cashout/Components/Faq.comp.tsx (1 hunks)
  • src/components/Cashout/Components/Initial.view.tsx (8 hunks)
  • src/components/Global/Header/index.tsx (1 hunks)
  • src/components/Global/LoginComponent/index.tsx (2 hunks)
  • src/components/Request/Create/Views/Initial.view.tsx (1 hunks)
  • src/config/peanut.config.tsx (1 hunks)
  • src/config/wagmi.config.tsx (3 hunks)
Additional comments not posted (29)
.gitignore (1)

8-8: LGTM!

Adding the **.patch entry to .gitignore is a good practice to avoid committing temporary patch files. The entry is correctly formatted and uses the double asterisk wildcard appropriately.

sentry.server.config.ts (1)

18-18: LGTM!

Enabling Spotlight in the development environment is a good change. It can improve the developer experience and debugging capabilities without impacting production.

src/config/peanut.config.tsx (2)

14-14: LGTM!

Commenting out the unused import statement for LogRocket is a good cleanup.


22-22: Verify logging and monitoring requirements.

Commenting out the LogRocket initialization code is fine if LogRocket is no longer needed. However, please ensure that any necessary logging and monitoring functionalities are still in place using alternative tools or methods to maintain observability into the application.

Run the following script to check for other logging and monitoring tools:

Verification successful

Sentry is used for monitoring and error tracking

The removal of LogRocket initialization is justified as the codebase is using Sentry for monitoring and error tracking. Sentry is imported in multiple files, including:

  • sentry.server.config.ts
  • sentry.edge.config.ts
  • sentry.client.config.ts
  • src/config/peanut.config.tsx
  • src/app/global-error.jsx

This indicates that proper error monitoring is in place. However, due to technical limitations in the verification environment, we couldn't check for console.log usage. If console.log statements are a concern, please manually verify their presence and ensure they are appropriate for the production environment.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other logging and monitoring tools in the codebase.

# Test: Search for common logging and monitoring libraries. Expect: At least one match.
rg --type typescript $'import.*\b(winston|bunyan|pino|log4js|morgan|sentry|newrelic|datadog|prometheus)\b'

Length of output: 140


Script:

#!/bin/bash
# Description: Check for other logging and monitoring tools in the codebase using multiple methods.

# Method 1: Use fd to find TypeScript and JavaScript files, then grep for logging/monitoring imports
echo "Method 1: fd + grep"
fd -e ts -e tsx -e js -e jsx --exec grep -H -E 'import.*\b(winston|bunyan|pino|log4js|morgan|sentry|newrelic|datadog|prometheus)\b' {} +

# Method 2: Use ast-grep to search for import statements related to logging/monitoring
echo "Method 2: ast-grep"
ast-grep --lang javascript --pattern 'import $_ from "$_"' | grep -E '\b(winston|bunyan|pino|log4js|morgan|sentry|newrelic|datadog|prometheus)\b'

# Method 3: Use rg with explicit file extensions
echo "Method 3: rg with file extensions"
rg -t js -t jsx -t ts -t tsx 'import.*\b(winston|bunyan|pino|log4js|morgan|sentry|newrelic|datadog|prometheus)\b'

# Additional search for console.log statements
echo "Additional: Search for console.log statements"
rg -t js -t jsx -t ts -t tsx 'console\.log'

Length of output: 9710

src/config/wagmi.config.tsx (2)

Line range hint 58-70: LGTM!

The added comment serves as a helpful reminder to run the build command after making changes to the Web3 modal configuration.


45-49: Verify the impact of disabling email-based authentication.

Setting email to false disables email-based authentication. Please ensure that this aligns with the desired user sign-up options and does not limit user onboarding.

Run the following script to verify the usage of email-based authentication:

Additionally, consider removing the commented socials array to keep the code clean, as it is not being used currently.

Apply this diff to remove the commented socials array:

-    // socials: ['google', 'github', 'apple', 'email', 'discord', 'facebook']
Verification successful

Disabling email-based authentication is consistent with the codebase.

The verification process confirms that setting email: false in src/config/wagmi.config.tsx aligns with the current state of the codebase. No instances of enabled email-based authentication were found, supporting this change.

As suggested earlier, consider removing the commented socials array to keep the code clean:

-    // socials: ['google', 'github', 'apple', 'email', 'discord', 'facebook']

This removal will improve code readability without affecting functionality, as the array is currently not in use.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of email-based authentication.

# Test: Search for the usage of email-based authentication. Expect: No occurrences.
rg --type typescript -A 5 $'email.*:.*true'

Length of output: 79


Script:

#!/bin/bash
# Description: Verify the usage of email-based authentication using multiple approaches.

# Approach 1: Use rg without file type specification
echo "Approach 1: Generic search with rg"
rg -i 'email.*:.*true' -A 5

# Approach 2: Use fd to find TypeScript files and grep to search within them
echo "Approach 2: fd + grep for TypeScript files"
fd -e ts -e tsx | xargs grep -i 'email.*:.*true' -A 5

# Approach 3: Use ast-grep to search for email configuration in TypeScript files
echo "Approach 3: ast-grep search for email configuration"
ast-grep --lang typescript --pattern 'email: true'

# Approach 4: Search for any email-related configuration
echo "Approach 4: Search for any email-related configuration"
rg -i 'email.*:' -A 5

Length of output: 19139

src/components/Cashout/Components/Faq.comp.tsx (1)

21-45: Great work on simplifying the FAQ content and improving user interaction!

The changes made to the FAQ component enhance the user experience and code maintainability:

  • Replacing Chakra UI components with standard HTML elements simplifies the structure and improves readability.
  • The updated content provides clear and concise information about cashout requirements, fees, and processing time.
  • The addition of the support chat button is a valuable feature that allows users to easily get help if needed.

The code segment does not introduce any apparent issues or bugs.

package.json (18)

12-12: LGTM!

The minor version update for @calcom/embed-react looks good. It should bring in bug fixes or small enhancements while maintaining compatibility.


15-15: LGTM!

The patch version update for @dicebear/collection looks good. It should bring in bug fixes while maintaining compatibility.


16-16: LGTM!

The patch version update for @dicebear/core looks good. It should bring in bug fixes while maintaining compatibility.


20-20: LGTM!

The minor version update for @sentry/nextjs looks good. It should bring in new features or enhancements while maintaining compatibility.


22-22: LGTM!

The minor version update for @tanstack/react-query looks good. It should bring in new features or enhancements while maintaining compatibility.


25-25: LGTM!

The patch version update for @vercel/og looks good. It should bring in bug fixes while maintaining compatibility.


26-26: LGTM!

The patch version update for @web3modal/wagmi looks good. It should bring in bug fixes while maintaining compatibility.


28-28: LGTM!

The patch version update for axios looks good. It should bring in bug fixes while maintaining compatibility.


32-32: LGTM!

The patch version update for eslint-config-next looks good. It should bring in bug fixes while maintaining compatibility.


35-35: LGTM!

The minor version update for i18n-iso-countries looks good. It should bring in new features or enhancements while maintaining compatibility.


37-37: LGTM!

The patch version update for libphonenumber-js looks good. It should bring in bug fixes while maintaining compatibility.


41-41: LGTM!

The patch version update for next looks good. It should bring in bug fixes while maintaining compatibility.


64-64: LGTM!

The minor version update for viem looks good. It should bring in new features or enhancements while maintaining compatibility.


73-73: LGTM!

The patch version update for @types/react looks good. It should bring in bug fixes while maintaining compatibility.


80-80: LGTM!

The patch version update for @types/validator looks good. It should bring in bug fixes while maintaining compatibility.


81-81: LGTM!

The patch version update for postcss looks good. It should bring in bug fixes while maintaining compatibility.


84-84: LGTM!

The patch version update for tailwindcss looks good. It should bring in bug fixes while maintaining compatibility.


85-85: LGTM!

The minor version update for typescript looks good. It should bring in new features or enhancements while maintaining compatibility.

next.config.js (1)

116-155: LGTM!

The change to conditionally export the Sentry configuration based on the environment is a good practice. It ensures that Sentry is only used in non-development environments, preventing unnecessary usage and potential costs.

The condition correctly checks if the NODE_ENV is not set to 'development' before applying the Sentry configuration. The Sentry options remain unchanged, and the overall structure of the configuration is maintained.

This change will not affect the functionality of the application and is a positive addition to the codebase.

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

127-128: LGTM!

The addition of autoComplete="username" and name="email" attributes to the email input field is a good practice. It enhances the accessibility and functionality of the input field by providing the browser with hints for autofill capabilities and identifying the field when submitting the form data.


138-139: LGTM!

Similar to the email input field, the addition of autoComplete="current-password" and name="password" attributes to the password input field is a good practice. It enhances the accessibility and functionality of the input field by providing the browser with hints for autofill capabilities and identifying the field when submitting the form data.

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

122-123: LGTM!

The updated label text provides clear instructions to the user about the steps involved in creating a payment request. It aligns with the overall functionality of requesting payment to the user's wallet and provides the flexibility to add an invoice.

Comment on lines +26 to +27
console.log('NODE_ENV:', process.env.NODE_ENV)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Avoid using console log statements in production code.

The console log statement is likely added for debugging purposes. However, it's generally not recommended to keep console log statements in production code as they can impact performance and clutter the console output.

Consider using a proper logging library that can be controlled based on the environment and log levels. For example, you can use the debug library:

-console.log('NODE_ENV:', process.env.NODE_ENV)
+import debug from 'debug';
+const log = debug('peanut:config');
+log('NODE_ENV: %s', process.env.NODE_ENV);

This way, you can enable the log output only when needed by setting the DEBUG environment variable:

DEBUG=peanut:config npm start

Comment on lines +301 to +302
className="z-[9999] text-h6"
zIndex={9999} // always on top
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Remove redundant z-index and consider a lower value.

Setting both className and zIndex to the same value (9999) is redundant. Remove the zIndex property to keep the code clean and maintainable.

Also, consider using a lower z-index value to avoid potential issues with other components that may need to be rendered on top of the NavBarContainer. A value of 9999 is extremely high and may cause unintended overlapping or obstruction of other elements.

Apply this diff to remove the redundant zIndex property:

-           zIndex={9999} // always on top
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
className="z-[9999] text-h6"
zIndex={9999} // always on top
className="z-[9999] text-h6"

import { useCreateLink } from '@/components/Create/useCreateLink'
import { GlobalLoginComponent } from '@/components/Global/LoginComponent'
import { Icon } from '@chakra-ui/react'
import { Icon as ChakraIcon } from '@chakra-ui/react'
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fix incorrect usage of ChakraIcon's name prop.

The ChakraIcon component from @chakra-ui/react does not support a name prop. To display specific icons, you should import the desired icon from @chakra-ui/icons and use it directly or with the as prop. Please replace ChakraIcon with the appropriate icon component.

Apply this diff to fix the issue:

+import { WarningIcon } from '@chakra-ui/icons';

...

-<ChakraIcon name="warning" className="-mt-0.5" />
+<WarningIcon className="-mt-0.5" />

Update all instances where ChakraIcon is used with the name prop to use the correct icon component.

Also applies to: 386-386, 391-391, 398-398

Comment on lines +313 to +329
<label className="text-left text-h8 font-light">
Cashout to a new bank account:
</label>
<div className="flex w-full cursor-pointer border border-black p-2">
<label className="ml-2 text-right">To:</label>
<input
type="text"
className="ml-2 w-full border-none outline-none"
placeholder="IBAN / US account number"
value={newBankAccount}
onChange={(e) => setNewBankAccount(e.target.value)}
onFocus={() => setActiveInput('newBankAccount')}
spellCheck="false"
autoComplete="iban"
/>
</div>
</motion.div>
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Refactor duplicated code for new bank account input into a reusable component.

The code for the "Cashout to a new bank account" input field is duplicated in both the logged-in and logged-out states. To improve maintainability and reduce code duplication, consider extracting this code into a separate reusable component.

Also applies to: 335-348

Comment on lines +62 to +66
const peanutAccount = user.accounts.find(
(account) =>
account.account_identifier?.toLowerCase().replaceAll(' ', '') ===
offrampForm?.recipient?.toLowerCase().replaceAll(' ', '')
)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Handle potential undefined 'user.accounts' before calling 'find'

In line 62, user.accounts is accessed without checking if user.accounts is defined. If user.accounts is undefined, this could result in a runtime error.

Apply this diff to safeguard against user.accounts being undefined:

+            if (!user.accounts) {
+                throw new Error('User accounts not found')
+            }
             const peanutAccount = user.accounts.find(
                 (account) =>
                     account.account_identifier?.toLowerCase().replaceAll(' ', '') ===
                     offrampForm?.recipient?.toLowerCase().replaceAll(' ', '')
             )
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
const peanutAccount = user.accounts.find(
(account) =>
account.account_identifier?.toLowerCase().replaceAll(' ', '') ===
offrampForm?.recipient?.toLowerCase().replaceAll(' ', '')
)
if (!user.accounts) {
throw new Error('User accounts not found')
}
const peanutAccount = user.accounts.find(
(account) =>
account.account_identifier?.toLowerCase().replaceAll(' ', '') ===
offrampForm?.recipient?.toLowerCase().replaceAll(' ', '')
)

</div>
<span className="flex flex-row items-center justify-center gap-1 text-center text-sm font-normal leading-4">
{offrampForm.recipient}
{offrampForm.recipient.toUpperCase()}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Safely handle 'offrampForm.recipient' to prevent errors when undefined

In line 399, calling offrampForm.recipient.toUpperCase() without ensuring offrampForm.recipient is defined can result in a runtime error if it is undefined or null.

Apply this diff to safeguard against undefined offrampForm.recipient:

-                                    {offrampForm.recipient.toUpperCase()}
+                                    {offrampForm.recipient ? offrampForm.recipient.toUpperCase() : ''}
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
{offrampForm.recipient.toUpperCase()}
{offrampForm.recipient ? offrampForm.recipient.toUpperCase() : ''}

Comment on lines +119 to +120
const chainId = utils.getChainIdFromBridgeChainName(chainName) ?? ''
const tokenAddress = utils.getTokenAddressFromBridgeTokenName(chainId ?? '10', tokenName) ?? ''
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Validate 'chainId' and 'tokenAddress' to prevent unexpected behavior

In lines 119-120, if getChainIdFromBridgeChainName or getTokenAddressFromBridgeTokenName return undefined, setting default values to empty strings '' may cause issues in subsequent code that expects valid IDs.

Consider handling cases where chainId or tokenAddress might be undefined, and provide appropriate error handling. For example:

             const chainId = utils.getChainIdFromBridgeChainName(chainName)
             const tokenAddress = utils.getTokenAddressFromBridgeTokenName(chainId ?? '10', tokenName)

+            if (!chainId || !tokenAddress) {
+                throw new Error('Unable to determine chainId or tokenAddress')
+            }

Committable suggestion was skipped due to low confidence.

data: {
...claimLinkData,
depositDate: new Date(),
USDTokenPrice: parseFloat(usdValue ?? ''),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Ensure 'usdValue' is valid before parsing to prevent 'NaN'

In line 256, parseFloat(usdValue ?? '') may result in NaN if usdValue is undefined or an empty string. This could cause issues when USDTokenPrice is expected to be a valid number.

Apply this diff to validate usdValue before parsing:

-                    USDTokenPrice: parseFloat(usdValue ?? ''),
+                    USDTokenPrice: usdValue ? parseFloat(usdValue) : 0,

Alternatively, handle the case where usdValue is undefined or invalid:

+            const usdTokenPrice = parseFloat(usdValue ?? '')
+            if (isNaN(usdTokenPrice)) {
+                throw new Error('Invalid USD value')
+            }
             utils.saveOfframpLinkToLocalstorage({
                 data: {
-                    USDTokenPrice: parseFloat(usdValue ?? ''),
+                    USDTokenPrice: usdTokenPrice,

Committable suggestion was skipped due to low confidence.

@coderabbitai coderabbitai bot mentioned this pull request Feb 21, 2025
@Hugo0 Hugo0 deleted the fix/cashout-rework branch July 3, 2025 18:21
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.

1 participant