Skip to content

Conversation

jjramirezn
Copy link
Contributor

No description provided.

Copy link
Contributor

coderabbitai bot commented Sep 4, 2025

Walkthrough

Updated payload amount computation in src/hooks/useCreateOnramp.ts to derive the converted amount from usdAmount. Added runtime currency/minimum-amount validation and centralized errorMessage handling in src/components/Request/views/ReqFulfillBankFlowManager.tsx; UI and flow gating updated accordingly. No exported/public APIs changed.

Changes

Cohort / File(s) Summary
Onramp amount calculation
src/hooks/useCreateOnramp.ts
In the usdAmount branch, compute converted payload amount using Number(usdAmount) (instead of Number(amount)) when applying currency price.
Request fulfill — bank flow & validation
src/components/Request/views/ReqFulfillBankFlowManager.tsx
Added runtime currency/minimum-amount validation using getCurrencyConfig, getMinimumAmount, and getCurrencyPrice; introduced errorMessage state replacing userUpdateError; added effect to revalidate on charge or country change; clear/set errorMessage across flows; disable Continue when errorMessage set; updated imports and UI error rendering.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • kushagrasarathe
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/nan-onramp

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

vercel bot commented Sep 4, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
peanut-wallet Ready Ready Preview Comment Sep 4, 2025 5:39pm

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

🧹 Nitpick comments (6)
src/hooks/useCreateOnramp.ts (6)

48-49: Rounding: verify 2 decimals are correct for the target currency.

If amount is not a fiat with 2 decimals, consider currency-specific precision (e.g., 0, 2, 6). I can help wire a decimals map.


52-57: Avoid sending Bearer undefined.

Set the Authorization header only when the token exists.

-                const response = await fetch('/api/proxy/bridge/onramp/create', {
+                const headers: Record<string, string> = { 'Content-Type': 'application/json' }
+                if (jwtToken) headers.Authorization = `Bearer ${jwtToken}`
+                const response = await fetch('/api/proxy/bridge/onramp/create', {
                     method: 'POST',
-                    headers: {
-                        'Content-Type': 'application/json',
-                        Authorization: `Bearer ${jwtToken}`,
-                    },
+                    headers,

51-67: Add a client-side timeout to the fetch.

Prevent hanging requests with AbortController.

-                const response = await fetch('/api/proxy/bridge/onramp/create', {
+                const controller = new AbortController()
+                const t = setTimeout(() => controller.abort(), 20000)
+                const response = await fetch('/api/proxy/bridge/onramp/create', {
                     method: 'POST',
                     headers,
+                    signal: controller.signal,
                     body: JSON.stringify({
                         amount,
                         chargeId,
                         source: {
                             currency,
                             paymentRail,
                         },
                         recipientAddress,
                     }),
                 })
+                clearTimeout(t)

77-77: Copy tweak: align error text with onramp flow.

“bank transfer” sounds off here.

-                setError('Failed to create bank transfer. Please try again.')
+                setError('Failed to create onramp. Please try again.')

37-49: Runtime guard for missing amount.

If usdAmount is an empty string, amount could remain undefined and be omitted from the payload. Add an explicit check.

             try {
                 const jwtToken = Cookies.get('jwt-token')
 
                 const { currency, paymentRail } = getCurrencyConfig(country.id, 'onramp')
                 if (usdAmount) {
                     // Get currency configuration for the country
                     const price = await getCurrencyPrice(currency)
                     amount = (Number(usdAmount) * price).toFixed(2)
                 }
+                if (amount == null) {
+                  throw new Error('Amount is required')
+                }

41-45: Minor: remove redundant comment.

“Get currency configuration for the country” restates the code; safe to delete.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 688f3fa and 772ae8f.

📒 Files selected for processing (1)
  • src/hooks/useCreateOnramp.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Deploy-Preview
🔇 Additional comments (1)
src/hooks/useCreateOnramp.ts (1)

48-48: Fix eliminates NaN in usdAmount path.

Switching to Number(usdAmount) resolves the NaN caused when amount was undefined. Good catch.

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

🧹 Nitpick comments (3)
src/components/Request/views/ReqFulfillBankFlowManager.tsx (3)

37-37: Don’t conflate validation and submission errors in one state.

errorMessage is used for both amount validation and user-update failures; the amount effect can clear a user-update error. Split into validationError and submitError, and render both as needed.

Apply minimally:

-const [errorMessage, setErrorMessage] = useState<string | null>(null)
+const [validationError, setValidationError] = useState<string | null>(null)
+const [submitError, setSubmitError] = useState<string | null>(null)

Then replace reads/writes accordingly (see related suggestions below).


124-142: Robust error handling for unknown errors; don’t let the amount validation effect clear submit errors.

  • Cast error safely to string.
  • If you keep split states, use setSubmitError here and ensure the amount validation effect only touches validationError.

Apply:

-    setErrorMessage(null)
+    setSubmitError(null)
@@
-  } catch (error: any) {
-      setErrorMessage(error.message)
-      return { error: error.message }
+  } catch (error: unknown) {
+      const msg = error instanceof Error ? error.message : String(error)
+      setSubmitError(msg)
+      return { error: msg }

220-225: Button gating and error rendering are currently tied only to the user-details view.

If the minimum-amount validation is meant to gate the entire onramp flow, also prevent confirming in the OnrampConfirmation step (see earlier suggestion) and consider showing the validation error earlier in the flow.

- disabled={!isUserDetailsFormValid || isUpdatingUser || !!errorMessage}
+ disabled={!isUserDetailsFormValid || isUpdatingUser || !!validationError || !!submitError}

And:

-{errorMessage && <ErrorAlert description={errorMessage} />}
+{(submitError || validationError) && (
+  <ErrorAlert description={(submitError ?? validationError)!} />
+)}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 772ae8f and e5ba47c.

📒 Files selected for processing (1)
  • src/components/Request/views/ReqFulfillBankFlowManager.tsx (7 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
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: 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: Hugo0
PR: peanutprotocol/peanut-ui#420
File: src/components/Offramp/Offramp.consts.ts:27-28
Timestamp: 2024-10-08T20:13:42.967Z
Learning: In `src/components/Offramp/Offramp.consts.ts`, the `MIN_CASHOUT_LIMIT` is set to $10 because smaller amounts are impractical due to approximately $1 fee per cashout.
📚 Learning: 2024-10-07T15:25:45.170Z
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.

Applied to files:

  • src/components/Request/views/ReqFulfillBankFlowManager.tsx
📚 Learning: 2024-10-07T15:28:25.280Z
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`.

Applied to files:

  • src/components/Request/views/ReqFulfillBankFlowManager.tsx
📚 Learning: 2025-08-20T09:08:19.266Z
Learnt from: kushagrasarathe
PR: peanutprotocol/peanut-ui#1112
File: src/components/Claim/Link/views/BankFlowManager.view.tsx:336-343
Timestamp: 2025-08-20T09:08:19.266Z
Learning: In the KYC flow implementation, `setJustCompletedKyc` must be called after `await fetchUser()` in the `handleKycSuccess` callback. Setting `justCompletedKyc` before fetching the user would cause a re-fetching loop because `handleKycSuccess` is set in a useEffect inside the KYC hook, which would cause the UI flow to get stuck in one view.

Applied to files:

  • src/components/Request/views/ReqFulfillBankFlowManager.tsx
🧬 Code graph analysis (1)
src/components/Request/views/ReqFulfillBankFlowManager.tsx (1)
src/app/actions/currency.ts (1)
  • getCurrencyPrice (7-58)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Deploy-Preview
🔇 Additional comments (1)
src/components/Request/views/ReqFulfillBankFlowManager.tsx (1)

74-114: Discard validationError suggestion: variable doesn’t exist in this component. The proposed diff references validationError, but no such variable is declared or used in ReqFulfillBankFlowManager.tsx—please ignore this change.

Likely an incorrect or invalid review comment.

@jjramirezn jjramirezn merged commit 665e4ce into peanut-wallet Sep 4, 2025
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants