Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: currency selection issues #280

Merged
merged 2 commits into from
Dec 19, 2024
Merged

fix: currency selection issues #280

merged 2 commits into from
Dec 19, 2024

Conversation

rodrigopavezi
Copy link
Member

@rodrigopavezi rodrigopavezi commented Dec 19, 2024

Changes

refactor: Clean up imports and improve currency handling in invoice forms

  • Reformatted import statements for better readability.
  • Enhanced currency filtering logic to prevent duplicates and handle specific cases for ISO4217 currencies.
  • Updated the invoice currency dropdown display to simplify the output.
  • Added error handling in balance formatting to improve robustness.

These changes aim to streamline the invoice creation process and enhance user experience.

Screen.Recording.2024-12-18.at.22.01.47.mov

Summary by CodeRabbit

  • New Features

    • Enhanced validation for email addresses and Ethereum addresses in the invoice form.
    • Improved handling of invoice items with dynamic input management.
  • Bug Fixes

    • Added error handling in balance formatting to prevent runtime errors.
    • Enhanced logging for missing parameters in balance checking.
  • Chores

    • Updated version numbers for @requestnetwork/create-invoice-form and @requestnetwork/invoice-dashboard packages.

…orms

- Reformatted import statements for better readability.
- Enhanced currency filtering logic to prevent duplicates and handle specific cases for ISO4217 currencies.
- Updated the invoice currency dropdown display to simplify the output.
- Added error handling in balance formatting to improve robustness.

These changes aim to streamline the invoice creation process and enhance user experience.
…oard, and payment-widget

- Bumped version of @requestnetwork/create-invoice-form from 0.11.14 to 0.11.15.
- Bumped version of @requestnetwork/invoice-dashboard from 0.11.12 to 0.11.13.
- Bumped version of @requestnetwork/payment-widget from 0.3.6 to 0.3.7.

These updates ensure compatibility with the latest features and fixes.
Copy link
Contributor

coderabbitai bot commented Dec 19, 2024

Walkthrough

This pull request encompasses updates across multiple packages within the Request Network ecosystem, focusing on the create-invoice-form and invoice-dashboard packages. The changes primarily involve version increments, improvements to form validation, currency and network handling, and enhanced error management. The modifications aim to refine the user experience and improve the robustness of invoice-related components, with particular attention to input validation, currency selection, and balance formatting.

Changes

File Change Summary
packages/create-invoice-form/package.json Version bumped from 0.11.14 to 0.11.15
packages/create-invoice-form/src/lib/create-invoice-form.svelte - Added filteredSettlementCurrencies variable
- Updated network and currency filtering logic
- Modified handleNetworkChange and handleInvoiceCurrencyChange functions
packages/create-invoice-form/src/lib/invoice/form.svelte - Added email and address validation
- Implemented validationErrors tracking
- Enhanced input handling and dropdown functionality
- Added reactive statements for date defaults
packages/invoice-dashboard/package.json Version bumped from 0.11.12 to 0.11.13
packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte - Added error handling in formatBalance function
- Improved logging in checkBalance function

Sequence Diagram

sequenceDiagram
    participant User
    participant CreateInvoiceForm
    participant CurrencyManager
    participant NetworkSelector
    
    User->>CreateInvoiceForm: Select Invoice Currency
    CreateInvoiceForm->>CurrencyManager: Filter Available Networks
    CurrencyManager-->>CreateInvoiceForm: Return Filtered Networks
    CreateInvoiceForm->>NetworkSelector: Update Available Networks
    User->>CreateInvoiceForm: Select Network
    CreateInvoiceForm->>CurrencyManager: Validate Settlement Currencies
    CurrencyManager-->>CreateInvoiceForm: Return Valid Currencies
Loading

Possibly related PRs

Suggested reviewers

  • sstefdev
  • MantisClone

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.

@rodrigopavezi rodrigopavezi self-assigned this Dec 19, 2024
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 (3)
packages/create-invoice-form/src/lib/create-invoice-form.svelte (3)

68-93: Consider refactoring the currency filtering logic for better maintainability

The current implementation could be improved by:

  1. Extracting the filtering logic into separate functions for ISO4217 and non-ISO4217 currencies
  2. Adding error handling for conversion path validation
 filteredSettlementCurrencies = currencyManager.knownCurrencies.filter(
   (currency: CurrencyTypes.CurrencyDefinition) => {
-    if (!invoiceCurrency) {
-      return false;
-    }
-
-    // For ISO4217 currencies (like EUR)
-    if (invoiceCurrency.type === Types.RequestLogic.CURRENCY.ISO4217) {
-      const hasValidPath =
-        currencyManager?.getConversionPath(
-          invoiceCurrency,
-          currency,
-          currency?.network,
-        )?.length > 0;
-
-      return (
-        currency.type !== Types.RequestLogic.CURRENCY.ISO4217 &&
-        hasValidPath &&
-        currency.network === newNetwork
-      );
-    }
-
-    // For other currency types (like ERC20)
-    return invoiceCurrency.hash === currency?.hash;
+    if (!invoiceCurrency) return false;
+    
+    const isISO4217 = invoiceCurrency.type === Types.RequestLogic.CURRENCY.ISO4217;
+    
+    const filterISO4217Currency = () => {
+      try {
+        const conversionPath = currencyManager?.getConversionPath(
+          invoiceCurrency,
+          currency,
+          currency?.network,
+        );
+        
+        if (!conversionPath?.length) {
+          console.warn(`No conversion path found for ${currency.symbol}`);
+          return false;
+        }
+        
+        return (
+          currency.type !== Types.RequestLogic.CURRENCY.ISO4217 &&
+          currency.network === newNetwork
+        );
+      } catch (error) {
+        console.error(`Error checking conversion path: ${error.message}`);
+        return false;
+      }
+    };
+    
+    return isISO4217 ? filterISO4217Currency() : invoiceCurrency.hash === currency?.hash;
   },
 );

101-109: Optimize currency deduplication using Set

The current implementation could be more efficient using Set for unique values.

-  let defaultCurrencies = Object.values(currencyManager.knownCurrencies.reduce(
-    (unique: { [x: string]: any; }, currency: { symbol: string | number; }) => {
-      if (!unique[currency.symbol] && !currency.symbol.includes('-')) unique[currency.symbol] = currency;
-
-      return unique;
-    },
-    {},
-  ));
+  let defaultCurrencies = Array.from(
+    new Set(
+      currencyManager.knownCurrencies
+        .filter(currency => !currency.symbol.includes('-'))
+        .map(currency => currency.symbol)
+    )
+  ).map(symbol => 
+    currencyManager.knownCurrencies.find(currency => currency.symbol === symbol)
+  );

130-130: Optimize network filtering

The current implementation can be made more concise.

-  networks = currencyManager.knownCurrencies.filter(currency => currency.symbol === invoiceCurrency?.symbol).map(currency => currency.network);
+  networks = currencyManager.knownCurrencies
+    .filter(({ symbol }) => symbol === invoiceCurrency?.symbol)
+    .map(({ network }) => network);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 60bcac0 and a0be792.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • packages/create-invoice-form/package.json (1 hunks)
  • packages/create-invoice-form/src/lib/create-invoice-form.svelte (6 hunks)
  • packages/create-invoice-form/src/lib/invoice/form.svelte (1 hunks)
  • packages/invoice-dashboard/package.json (1 hunks)
  • packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/invoice-dashboard/package.json
  • packages/create-invoice-form/package.json
🧰 Additional context used
📓 Learnings (3)
packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte (1)
Learnt from: MantisClone
PR: RequestNetwork/web-components#141
File: packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte:0-0
Timestamp: 2024-11-12T14:52:33.204Z
Learning: In `packages/invoice-dashboard/src/lib/dashboard/invoice-view.svelte`, mapping payment network IDs to their respective approval functions in the `checkApproval` function is acceptable and can improve readability and maintainability.
packages/create-invoice-form/src/lib/create-invoice-form.svelte (2)
Learnt from: MantisClone
PR: RequestNetwork/web-components#150
File: packages/create-invoice-form/src/lib/create-invoice-form.svelte:81-84
Timestamp: 2024-11-12T14:52:33.204Z
Learning: The `getAccount` function from `@wagmi/core` accepts a configuration parameter. When using `wagmiConfig`, it is appropriate to call `getAccount(wagmiConfig)`.
Learnt from: MantisClone
PR: RequestNetwork/web-components#141
File: packages/create-invoice-form/src/lib/invoice/form.svelte:33-33
Timestamp: 2024-11-19T16:11:41.270Z
Learning: In the TypeScript file `packages/create-invoice-form/src/lib/invoice/form.svelte`, maintain the `any` type for the variables `currencyManager` and `network` without suggesting type replacements.
packages/create-invoice-form/src/lib/invoice/form.svelte (3)
Learnt from: sstefdev
PR: RequestNetwork/web-components#156
File: packages/create-invoice-form/src/lib/invoice/form.svelte:29-39
Timestamp: 2024-11-12T14:52:38.580Z
Learning: In `packages/create-invoice-form/src/lib/invoice/form.svelte`, directly mutating the `validationErrors` object triggers reactive updates in Svelte without needing to reassign the object.
Learnt from: sstefdev
PR: RequestNetwork/web-components#227
File: packages/create-invoice-form/src/lib/invoice/form.svelte:416-435
Timestamp: 2024-12-16T20:16:26.643Z
Learning: In the `packages/create-invoice-form/src/lib/invoice/form.svelte`, the `SearchableDropdown` component for invoice currency already includes validation for invalid selections, so additional error handling is unnecessary.
Learnt from: MantisClone
PR: RequestNetwork/web-components#141
File: packages/create-invoice-form/src/lib/invoice/form.svelte:33-33
Timestamp: 2024-11-19T16:11:41.270Z
Learning: In the TypeScript file `packages/create-invoice-form/src/lib/invoice/form.svelte`, maintain the `any` type for the variables `currencyManager` and `network` without suggesting type replacements.
🔇 Additional comments (4)
packages/create-invoice-form/src/lib/create-invoice-form.svelte (3)

4-8: LGTM! Import organization improves readability


43-44: LGTM! Correct usage of wagmiConfig

Implementation aligns with the established pattern for getAccount usage.


262-262: LGTM! Consistent comma style

packages/create-invoice-form/src/lib/invoice/form.svelte (1)

410-410: LGTM! Simplified currency display

The removal of network information from the currency display makes the selection clearer for users. However, let's verify that this doesn't impact currency disambiguation elsewhere.

✅ Verification successful

Currency display change is safe to proceed

The removal of network information from the invoice currency display in form.svelte is safe because:

  1. The invoice currency selector still maintains network information in the dropdown items (label: ${currency?.symbol ?? "Unknown"} ${currency?.network ? (${currency.network}) : ""})
  2. The settlement currency selector continues to show network information (${currency.value.symbol} (${currency.value.network}))
  3. The payment widget's currency-selector.svelte handles network display separately through dedicated UI elements (currency-info-symbol and currency-network components)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are any other components that might rely on the network information in the currency display
rg -l "currency.*network.*symbol" --type svelte

Length of output: 80


Script:

#!/bin/bash
# Search for any currency-related patterns in the codebase
rg -l "currency.*symbol|symbol.*currency"

Length of output: 647


Script:

#!/bin/bash
# Search for files containing both currency and network references
rg -l "currency.*network|network.*currency"

Length of output: 1039


Script:

#!/bin/bash
# List all files in the repository to understand the structure
fd -t f -e svelte -e js -e ts -e jsx -e tsx

Length of output: 6218


Script:

#!/bin/bash
# Check the specific implementation in currency-selector.svelte since it's likely the main component for currency selection
rg "symbol" packages/payment-widget/src/lib/components/currency-selector.svelte -A 5 -B 5

Length of output: 1091


Script:

#!/bin/bash
# Check the implementation in form.svelte to understand the context of the change
rg "symbol" packages/create-invoice-form/src/lib/invoice/form.svelte -A 5 -B 5

Length of output: 1328


Script:

#!/bin/bash
# Check shared currency utility implementations
rg "symbol" shared/utils/getCurrency.ts -A 5 -B 5

Length of output: 49

@MantisClone
Copy link
Member

When you clear the invoice currency without making a new selection will it still clear the other two fields?

@rodrigopavezi
Copy link
Member Author

It will not until you selected a different one. I think the Dropdown only triggers the handler when selecting

@MantisClone
Copy link
Member

Okay

Copy link
Member

@MantisClone MantisClone left a comment

Choose a reason for hiding this comment

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

I didn't look at the code.

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.

Improve currency selection in invoicing (better filtering)
2 participants