Skip to content

Conversation

jjramirezn
Copy link
Contributor

@jjramirezn jjramirezn commented Dec 16, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for user validation and API responses.
    • Introduction of a new type for better type safety in API interactions.
    • Added functionality for cashout link submissions.
  • Bug Fixes

    • Updated KYC status checks in multiple components to improve user experience.
    • Improved error messaging for unselected bank accounts and KYC status updates.
  • Documentation

    • Updated documentation to reflect changes in method naming for clarity.
  • Refactor

    • Renamed methods for better clarity and updated parameters accordingly.
    • Consolidated import statements for improved code organization.
  • Style

    • Minor adjustments to CSS class orders for better styling consistency.

Copy link

vercel bot commented Dec 16, 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 1 resolved Dec 17, 2024 10:15am

Copy link

@jjramirezn jjramirezn requested a review from Hugo0 December 16, 2024 16:59
Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

Walkthrough

This pull request introduces a comprehensive set of changes across multiple files in the peanut-ui repository. The primary modifications focus on updating the KYC status check from 'verified' to 'approved', renaming the updateBridgeCustomerId method to updateBridgeCustomerData, and enhancing error handling and user validation in various components. The changes aim to improve the clarity of user data management, authentication processes, and overall user experience across the application.

Changes

File Change Summary
docs/high_level_overview.md Updated documentation with method renaming
src/app/api/bridge/user/new/get-status/route.ts Enhanced user validation and response handling
src/app/api/peanut/user/get-user-from-cookie/route.ts Modified API URL construction and request headers
src/app/api/peanut/user/get-user/route.ts File removed
src/app/api/peanut/user/update-user/route.ts Added kycStatus to request body
src/components/Cashout/Components/Initial.view.tsx Updated KYC status check and error handling
src/components/Claim/Link/Initial.view.tsx Modified KYC status condition
src/components/Global/Header/components/index.tsx Minor CSS class order change
src/components/Global/KYCComponent/index.tsx Replaced updateBridgeCustomerId with updateBridgeCustomerData
src/components/Global/LinkAccountComponent/index.tsx Updated KYC status checks
src/components/Kyc/index.tsx Modified KYC status rendering condition
src/components/LinkAccount/index.tsx Updated KYC status condition
src/components/Profile/index.tsx Changed KYC status display logic
src/context/authContext.tsx Renamed method and updated implementation
src/utils/cashout.utils.ts Added new type and updated method signatures

Possibly related PRs

Suggested reviewers

  • Hugo0

Poem

🐰 A rabbit's tale of code so bright,
Renaming methods with pure delight,
From 'verified' to 'approved' we leap,
Cleaning up paths, no errors to keep!
KYC dancing with newfound grace,
A refactor with a bunny's embrace! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

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

Line range hint 172-427: Consider security implications of extensive logging

The debug logging statements might expose sensitive user information. Consider:

  1. Removing or conditionally enabling these logs based on environment
  2. Ensuring sensitive data is properly redacted
-console.log('User accounts:', user.accounts)
+if (process.env.NODE_ENV === 'development') {
+  console.log('User accounts:', user.accounts.map(acc => ({ 
+    ...acc, 
+    account_identifier: '***' 
+  })))
+}

Extract address validation logic

The address validation logic is complex and could be extracted into a separate utility function for better maintainability and reusability.

// utils/address.ts
export const findValidAccountAddress = (
  accounts: Array<any>,
  requiredFields = ['street', 'city', 'state', 'postalCode']
): any | undefined => {
  return accounts.find(account => {
    if (!account.account_details) return false;
    
    const details = typeof account.account_details === 'string'
      ? JSON.parse(account.account_details)
      : account.account_details;
      
    return requiredFields.every(field => 
      details[field] && 
      typeof details[field] === 'string' && 
      details[field].trim() !== ''
    );
  });
};

Consider using TypeScript interfaces for account details

The account details handling could benefit from proper TypeScript interfaces to ensure type safety.

interface AccountDetails {
  street: string;
  city: string;
  state: string;
  postalCode: string;
  country?: string;
}

interface UserAccount {
  account_identifier: string;
  account_details?: string | AccountDetails;
}
🧹 Nitpick comments (8)
src/app/api/bridge/user/new/get-status/route.ts (1)

12-31: Refactor to reuse authentication logic without creating a new NextRequest

The current implementation creates a new NextRequest to invoke getUserFromCookie, which adds unnecessary complexity and overhead. Consider directly importing the authentication logic or refactoring it into a reusable function or middleware. This would improve performance and maintainability by avoiding redundant request creation.

src/app/api/peanut/user/get-user-from-cookie/route.ts (1)

5-5: Clarify unused _request parameter

The parameter request has been renamed to _request, indicating it's unused. Since NextRequest is not used in the function, consider removing it entirely for cleaner code.

Apply this diff to remove the unused parameter:

- export async function GET(_request: NextRequest) {
+ export async function GET() {
src/components/LinkAccount/index.tsx (2)

41-41: Use constant for kycStatus comparison

Hardcoding the string 'approved' can lead to maintenance issues and typos. Consider using a constant or enum for KYC statuses to improve code readability and maintainability.

Apply this diff to use a constant:

+ const KYC_STATUS_APPROVED = 'approved';

...

) : user && user?.user?.kycStatus !== KYC_STATUS_APPROVED ? (

41-41: Provide user feedback for pending KYC status

Currently, users with a KYC status not equal to 'approved' are prompted to complete KYC. Consider handling different KYC statuses (e.g., 'pending', 'rejected') to provide more specific feedback to the user.

src/context/authContext.tsx (1)

Line range hint 129-141: Consider enhancing error handling and user feedback.

While the implementation is functionally correct, it could benefit from consistent error handling patterns seen in other methods like updateUserName.

Consider applying this improvement:

 const updateBridgeCustomerData = async (customer: GetUserLinksResponse) => {
     if (!user) return
 
     try {
+        if (toastIdRef.current) {
+            toast.close(toastIdRef.current)
+        }
+        toastIdRef.current = toast({
+            status: 'loading',
+            title: 'Updating user data...',
+        }) as ToastId
         const response = await fetch('/api/peanut/user/update-user', {
             method: 'POST',
             headers: {
                 'Content-Type': 'application/json',
             },
             body: JSON.stringify({
                 bridge_customer_id: customer.id,
                 userId: user.user.userId,
                 kycStatus: customer.kyc_status,
             }),
         })
 
         if (response.ok) {
             const updatedUserData: any = await response.json()
             if (updatedUserData.success) {
+                toast.close(toastIdRef.current)
+                toastIdRef.current = toast({
+                    status: 'success',
+                    title: 'User data updated successfully',
+                }) as ToastId
                 fetchUser()
             }
         } else {
+            throw new Error('Failed to update user')
-            console.error('Failed to update user')
         }
     } catch (error) {
         console.error('Error updating user', error)
+        toast.close(toastIdRef.current ?? '')
+        toastIdRef.current = toast({
+            status: 'error',
+            title: 'Failed to update user data',
+            description: 'Please try again later',
+        }) as ToastId
     }
 }
src/components/Global/KYCComponent/index.tsx (1)

262-265: Consider combining customer object updates.

The customer object update and bridge customer data update could potentially be combined to reduce state updates.

-setCustomerObject({ ..._customerObject, customer_id: customer.id })
-await updateBridgeCustomerData(customer)
+const updatedCustomer = { ..._customerObject, customer_id: customer.id, ...customer }
+setCustomerObject(updatedCustomer)
+await updateBridgeCustomerData(updatedCustomer)
src/components/Profile/index.tsx (1)

399-401: Consider using type-safe KYC status checks

The KYC status check is correct, but could benefit from using a type-safe enum or constant for status values to prevent typos and ensure consistency.

+// Add at the top of the file or in a shared constants file
+const KYC_STATUS = {
+  APPROVED: 'approved'
+} as const;

-className={`kyc-badge select-none ${user?.user?.kycStatus === 'approved' ? 'bg-kyc-green px-2 py-1 text-black' : 'bg-gray-1 text-white hover:ring-2 hover:ring-gray-2'} w-max`}
+className={`kyc-badge select-none ${user?.user?.kycStatus === KYC_STATUS.APPROVED ? 'bg-kyc-green px-2 py-1 text-black' : 'bg-gray-1 text-white hover:ring-2 hover:ring-gray-2'} w-max`}
src/components/Claim/Link/Initial.view.tsx (1)

235-235: Consider enhancing error handling for KYC status checks

While the KYC status check is correct, the error handling could be more informative for users who don't meet the KYC requirements.

-if (user?.user.kycStatus === 'approved') {
+const KYC_STATUS = {
+  APPROVED: 'approved'
+} as const;
+
+if (user?.user.kycStatus === KYC_STATUS.APPROVED) {
  // ... existing code ...
} else {
+  const errorMessage = !user?.user.kycStatus 
+    ? 'KYC verification required'
+    : 'KYC verification pending approval';
+  setErrorState({
+    showError: true,
+    errorMessage
+  });
  // ... existing code ...
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0793b4d and a1709ea.

📒 Files selected for processing (15)
  • docs/high_level_overview.md (1 hunks)
  • src/app/api/bridge/user/new/get-status/route.ts (2 hunks)
  • src/app/api/peanut/user/get-user-from-cookie/route.ts (1 hunks)
  • src/app/api/peanut/user/get-user/route.ts (0 hunks)
  • src/app/api/peanut/user/update-user/route.ts (2 hunks)
  • src/components/Cashout/Components/Initial.view.tsx (1 hunks)
  • src/components/Claim/Link/Initial.view.tsx (1 hunks)
  • src/components/Global/Header/components/index.tsx (1 hunks)
  • src/components/Global/KYCComponent/index.tsx (5 hunks)
  • src/components/Global/LinkAccountComponent/index.tsx (3 hunks)
  • src/components/Kyc/index.tsx (1 hunks)
  • src/components/LinkAccount/index.tsx (1 hunks)
  • src/components/Profile/index.tsx (1 hunks)
  • src/context/authContext.tsx (4 hunks)
  • src/utils/cashout.utils.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • src/app/api/peanut/user/get-user/route.ts
✅ Files skipped from review due to trivial changes (1)
  • src/components/Global/Header/components/index.tsx
🔇 Additional comments (12)
src/app/api/bridge/user/new/get-status/route.ts (1)

61-61: Verify the inclusion of sensitive data in the response

Returning both id and kyc_status may expose sensitive information. Ensure that including data.customer_id in the response is necessary and complies with data privacy policies.

Run the following script to audit usages of customer_id:

✅ Verification successful

Let me gather more context about how this data is used and protected.


Let me check one more thing about the authentication and route protection.


Based on the code analysis, I can now provide the final response:

The customer_id exposure in the response is secure and necessary

The endpoint implements proper security measures:

  • Validates user authentication through cookie verification
  • Performs authorization check by comparing the requested userId with the authenticated user's bridge_customer_id
  • Only returns customer_id when explicitly requested via type='customer_id'
  • The customer_id is only returned to the same authenticated user it belongs to
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search the codebase for usages of `customer_id` to ensure it is handled securely.

# Find all occurrences of `customer_id` in the codebase
rg 'customer_id'

Length of output: 2038


Script:

#!/bin/bash
# Check the route handler's security measures and context
ast-grep --pattern 'export async function GET(request: Request) {
  $$$
}'  src/app/api/bridge/user/new/get-status/route.ts

# Check if there's authentication middleware or protected routes
rg -B 2 -A 2 "middleware" 

Length of output: 4132


Script:

#!/bin/bash
# Check the content of the get-status route handler for authentication
cat src/app/api/bridge/user/new/get-status/route.ts

# Check for auth utilities
rg -B 2 -A 2 "getServerSession|auth\(" src/

Length of output: 2738

src/app/api/peanut/user/get-user-from-cookie/route.ts (2)

10-10: Handle missing environment variables securely

If apiKey is missing, returning a 400 Bad Request with details may expose sensitive information. Consider returning a generic error message to avoid leaking configuration details.

[security_issue]

Apply this diff to generalize the error message:

- return new NextResponse('Bad Request: missing required parameters', { status: 400 })
+ return new NextResponse('Bad Request', { status: 400 })

14-14: Ensure PEANUT_API_URL is properly configured

Using consts.PEANUT_API_URL is a good practice. Verify that this constant is correctly set in all environments (development, staging, production) to prevent misrouting API calls.

Run the following script to check the constant definition:

✅ Verification successful

PEANUT_API_URL is properly configured with fallback

The constant is correctly defined in src/constants/general.consts.ts with a proper fallback mechanism:

  • Uses environment variable process.env.PEANUT_API_URL if available
  • Falls back to https://api.peanut.to if not set
  • Includes trailing slash prevention

The implementation is robust and follows best practices for API URL configuration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `PEANUT_API_URL` is defined in the constants file.

# Display the definition of PEANUT_API_URL
rg 'PEANUT_API_URL' src/constants.ts

Length of output: 93


Script:

#!/bin/bash
# Let's first find where constants or configuration files might be located
fd -t f -e ts -e js consts config constants

# Then search for PEANUT_API_URL across all files
rg "PEANUT_API_URL" --type ts --type js

Length of output: 4703


Script:

#!/bin/bash
# Let's check the content of the constants file to see how PEANUT_API_URL is configured
cat src/constants/general.consts.ts

# Also check for any environment variable configurations
fd -t f -e ts -e js env config

Length of output: 4006

src/app/api/peanut/user/update-user/route.ts (1)

6-6: Validate kycStatus before processing

Ensure that kycStatus is properly validated and sanitized before including it in the request body to prevent potential security issues or invalid data being sent to the API.

src/context/authContext.tsx (1)

6-6: LGTM! Type safety improvements.

The change from a simple string parameter to a strongly-typed GetUserLinksResponse improves type safety and better represents the data structure.

Also applies to: 14-14

src/components/Kyc/index.tsx (1)

42-42: LGTM! KYC status check updated correctly.

The change from 'verified' to 'approved' aligns with the authentication fixes.

docs/high_level_overview.md (2)

89-89: LGTM! Documentation updated to reflect API changes.

The auth context documentation correctly reflects the renamed method updateBridgeCustomerData.


Line range hint 42-42: Verify KYC status check consistency across the codebase.

Let's ensure all KYC status checks have been updated from 'verified' to 'approved'.

✅ Verification successful

Let me check the actual usage context of these KYC status checks to ensure they're consistently using 'approved'.


KYC status checks are consistently using 'approved' across the codebase

The verification shows that all KYC status checks have been properly updated to use 'approved' instead of 'verified'. No instances of 'verified' status remain, and all components consistently use 'approved' for KYC status checks in their conditional logic and UI rendering.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining instances of 'verified' KYC status checks
rg -l "kycStatus.*['\"]verified['\"]" || echo "No files found with 'verified' status"

# Search for new 'approved' KYC status checks for verification
rg -l "kycStatus.*['\"]approved['\"]"

Length of output: 515


Script:

#!/bin/bash
# Check the context of KYC status checks in the files
for file in src/components/Cashout/Components/Initial.view.tsx \
           src/components/Profile/index.tsx \
           src/components/LinkAccount/index.tsx \
           src/components/Kyc/index.tsx \
           src/components/Global/KYCComponent/index.tsx \
           src/components/Global/IframeWrapper/index.tsx \
           src/components/Global/LinkAccountComponent/index.tsx \
           src/components/Claim/Link/Initial.view.tsx; do
    echo "=== $file ==="
    rg -A 2 -B 2 "kycStatus.*approved" "$file"
done

Length of output: 7200

src/components/Global/KYCComponent/index.tsx (1)

50-50: LGTM: Method rename reflects enhanced functionality.

The rename from updateBridgeCustomerId to updateBridgeCustomerData better represents its purpose of updating the complete customer data object.

src/components/Cashout/Components/Initial.view.tsx (1)

166-166: LGTM: KYC status check aligned with type definition.

The KYC status check now correctly uses 'approved' which matches the kyc_status type definition in GetUserLinksResponse.

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

117-131: LGTM: Well-defined type for user links response.

The GetUserLinksResponse type clearly defines the shape of the response and includes proper type definitions for the KYC status.


132-132: LGTM: Enhanced type safety with Promise return type.

The getUserLinks function now properly specifies its return type as Promise<GetUserLinksResponse>, improving type safety.

Comment on lines +28 to +30
if (userId !== user?.bridge_customer_id) {
return new NextResponse('Forbidden', { status: 403 })
}
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 consistency when comparing userId and bridge_customer_id

To prevent potential mismatches due to type differences, ensure that both userId and user.bridge_customer_id are strings before comparing. This avoids incorrect authorization failures if one is a number and the other is a string.

Apply this diff to enforce type consistency:

- if (userId !== user?.bridge_customer_id) {
+ if (String(userId) !== String(user?.bridge_customer_id)) {
📝 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
if (userId !== user?.bridge_customer_id) {
return new NextResponse('Forbidden', { status: 403 })
}
if (String(userId) !== String(user?.bridge_customer_id)) {
return new NextResponse('Forbidden', { status: 403 })
}

Comment on lines +17 to +18
...request.headers,
},
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

Avoid potential header conflicts when spreading headers

Spreading request.headers after explicitly setting the cookie header may lead to duplicate or conflicting headers, especially if cookie is already present in request.headers. To prevent this, remove the spread operator or ensure that headers are merged without duplication.

Apply this diff to adjust the headers:

headers: {
    cookie: request.headers.get('cookie') ?? '',
-   ...request.headers,
},
📝 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
cookie: request.headers.get('cookie') ?? '',
...request.headers,
cookie: request.headers.get('cookie') ?? '',

userId,
username,
bridge_customer_id,
kycStatus,
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

Handle undefined kycStatus gracefully

If kycStatus is undefined or null, it could cause issues with the API request. Consider setting a default value or conditionally including it in the request body.

Apply this diff to include kycStatus conditionally:

body: JSON.stringify({
    userId,
    username,
    bridge_customer_id,
-   kycStatus,
+   ...(kycStatus && { kycStatus }),
}),

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

}
} else {
let data = await utils.getUserLinks(inputFormData)
await updateBridgeCustomerData(data)
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Error handling is inconsistent across updateBridgeCustomerData calls

The verification reveals inconsistent error handling patterns:

  • In handleKYCStatus and the last call, the function is within a try-catch block with proper error logging and user feedback
  • However, the first two calls (in the else block and handleTOSStatus) lack explicit error handling, which could lead to unhandled promise rejections

Locations needing attention:

  • Line 99: Missing try-catch block in the else clause
  • Line 132: Missing try-catch in handleTOSStatus
  • Line 187: Has proper error handling (keep as is)
🔗 Analysis chain

Verify consistent error handling across all updateBridgeCustomerData calls.

The function is called in multiple places with potentially different data shapes. Ensure error handling is consistent across all calls.

Also applies to: 132-132, 187-187


Let me check the error handling implementation by looking for try-catch blocks around these calls.


Let me try a different approach to check the error handling context.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check error handling consistency across updateBridgeCustomerData calls.

# Search for all updateBridgeCustomerData calls and their surrounding error handling
rg -A 5 -B 5 'updateBridgeCustomerData\(' 

Length of output: 3838


Script:

#!/bin/bash
# Search for try-catch blocks containing updateBridgeCustomerData calls
ast-grep --pattern 'try {
  $$$
  updateBridgeCustomerData($$$)
  $$$
} catch ($$$) {
  $$$
}'

Length of output: 96


Script:

#!/bin/bash
# Get more context around the function calls to see error handling patterns
rg -A 15 -B 15 'updateBridgeCustomerData\(' src/components/Global/KYCComponent/index.tsx

Length of output: 4894

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
src/components/Claim/Link/Onchain/Confirm.view.tsx (1)

Line range hint 38-83: Enhance error handling and transaction flow

A few suggestions to improve the error handling and transaction flow:

  1. The generic error message "Error claiming link" could be more descriptive.
  2. Consider moving the localStorage save operation after confirming the transaction success.
  3. Add error type discrimination for better error messages.

Here's a suggested improvement:

 if (claimTxHash) {
+    try {
+        // Wait for transaction confirmation
+        await utils.waitForTransaction(claimTxHash)
+        
         utils.saveClaimedLinkToLocalStorage({
             address: recipient ? recipient.address : (address ?? ''),
             data: {
                 ...claimLinkData,
                 depositDate: new Date(),
                 USDTokenPrice: tokenPrice,
                 points: estimatedPoints,
                 txHash: claimTxHash,
                 message: attachment.message ? attachment.message : undefined,
                 attachmentUrl: attachment.attachmentUrl ? attachment.attachmentUrl : undefined,
             },
         })
         setTransactionHash(claimTxHash)
         onNext()
         refetchBalances()
+    } catch (error) {
+        throw new Error('Transaction failed after submission. Please check your wallet for status.')
+    }
 } else {
-    throw new Error('Error claiming link')
+    throw new Error('Transaction was not submitted. Please try again.')
 }
🧹 Nitpick comments (3)
src/components/Claim/Link/Onchain/Confirm.view.tsx (3)

Line range hint 223-242: Track points estimation implementation as a separate issue

The commented-out code block with TODO indicates pending work for points estimation. Instead of keeping commented code, consider tracking this as a separate issue for better maintainability.

Would you like me to create a GitHub issue to track the implementation of the points estimation feature?


Line range hint 245-254: Improve loading state management

The current loading state implementation could be enhanced to handle edge cases and provide better user feedback:

  1. Consider adding a timeout for long-running operations
  2. Add recovery mechanism for stuck loading states
  3. Show more detailed progress information for cross-chain operations

Here's a suggested improvement:

+ const TIMEOUT_DURATION = 60000; // 1 minute timeout
+ useEffect(() => {
+    let timeoutId: NodeJS.Timeout;
+    if (isLoading) {
+        timeoutId = setTimeout(() => {
+            setLoadingState('Idle');
+            setErrorState({
+                showError: true,
+                errorMessage: 'Operation timed out. Please try again.',
+            });
+        }, TIMEOUT_DURATION);
+    }
+    return () => clearTimeout(timeoutId);
+ }, [isLoading]);

 <button className="btn-purple btn-xl" onClick={handleOnClaim} disabled={isLoading}>
     {isLoading ? (
         <div className="flex w-full flex-row items-center justify-center gap-2">
-            <Loading /> {loadingState}
+            <Loading /> {selectedRoute ? `${loadingState} (Cross-chain transfer)` : loadingState}
         </div>
     ) : (
         'Claim'
     )}
 </button>

Line range hint 1-270: Consider splitting component for better maintainability

The component handles multiple responsibilities including regular claims, cross-chain claims, and attachment handling. Consider:

  1. Splitting into smaller, focused components
  2. Moving attachment handling logic to a separate component
  3. Creating a dedicated utility for file type operations

Suggested component structure:

// AttachmentView.tsx
export const AttachmentView = ({ message, attachmentUrl }) => {
    const [fileType] = useFileType(attachmentUrl);
    return (
        // Attachment rendering logic
    );
};

// ClaimDetailsView.tsx
export const ClaimDetailsView = ({ claimLinkData, selectedRoute, recipient }) => {
    return (
        // Claim details rendering logic
    );
};

// ConfirmClaimLinkView.tsx
export const ConfirmClaimLinkView = (props) => {
    return (
        <div className="flex w-full flex-col items-center justify-center gap-6 text-center">
            <AttachmentView 
                message={props.attachment.message} 
                attachmentUrl={props.attachment.attachmentUrl}
            />
            <ClaimDetailsView 
                claimLinkData={props.claimLinkData}
                selectedRoute={props.selectedRoute}
                recipient={props.recipient}
            />
            {/* Rest of the component */}
        </div>
    );
};

This structure would improve maintainability and make the code easier to test.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a1709ea and 16eb9e8.

📒 Files selected for processing (4)
  • src/components/Claim/Link/Initial.view.tsx (3 hunks)
  • src/components/Claim/Link/Onchain/Confirm.view.tsx (2 hunks)
  • src/components/Create/Link/Confirm.view.tsx (2 hunks)
  • src/components/Request/Pay/Views/Initial.view.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/components/Create/Link/Confirm.view.tsx
  • src/components/Request/Pay/Views/Initial.view.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Claim/Link/Initial.view.tsx

import { NextResponse } from 'next/server'
import { NextResponse, NextRequest } from 'next/server'
import * as interfaces from '@/interfaces'
import { GET as getUserFromCookie } from '@/app/api/peanut/user/get-user-from-cookie/route'
Copy link
Contributor

Choose a reason for hiding this comment

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

eww

throw new Error('BRIDGE_API_KEY is not defined')
}

const getUserFromCookieRequest = new NextRequest(
Copy link
Contributor

Choose a reason for hiding this comment

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

this plus { GET as getUserFromCookie } ? oof

},
}
)
const getUserFromCookieResponse = await getUserFromCookie(getUserFromCookieRequest)
Copy link
Contributor

Choose a reason for hiding this comment

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

what's going on here, why

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We need the user data, of the calling user, so we need to ensure that the user is authenticated and get its data. We can't trust on input

@jjramirezn jjramirezn merged commit 69bf238 into main Dec 17, 2024
4 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jun 17, 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.

3 participants