Skip to content

Conversation

@takenagain
Copy link
Collaborator

@takenagain takenagain commented Mar 21, 2025

This PR adds the new address selection widget used by the withdrawal form to the fiat on ramp page, and fixes the issues listed below.

Fiat Form bugs fixed by this PR

  • Pop-up during Ramp fiat onramp covers QR code, blocking onramp process (as reported by kagan in QA group chat)
  • Changing the coin does not update the address field
  • Coin list disappearing
    • Select currency and then quickly open the currency selection dropdown again and scroll down
    • Go over max amount -> Open currency selector -> Scroll down -> observe list disappearing
  • Changing spend value quickly results in the incorrect value (not the last value entered as it should)

Fiat on ramp demo/testing environment

The Ramp and Banxa test/demo/sandbox environments only work for debug builds, so testing needs to be done with a local build rather than preview links, unless testing with real fiat transfers is desired. Preview links, like the one in the comment below, use production APIs and configurations.

Ramp

You can make a test purchase using the guidelines below (demo environment only):

  1. Select EUR as the currency and enter a valid amount.
  2. Select "Manual Bank Transfer" as the payment method if available.
  3. Click "Buy Now" and wait for the popup web view to load the Ramppage.
  4. Ensure that the currency on Ramp is still EUR, and change the country/currency if not.
  5. Ensure that the chosen payment method is "Manual Bank Transfer", and change to it if not.
  6. Continue, the purchase will be created.
  7. Tick the box that says that you've transferred the funds and continue.
  8. Open the transaction summary link.
  9. Click the manual test release button at the bottom of the summary and wait a few moments until the confirmation is processed.

Banxa

See #1362 comment for more information. The relevant notes were copied below:

NB! About Banxa KYC: When you get to the KYC selfie step, scan the QR code to complete it on your mobile device. This will give you additional testing options to simulate success/failure of the selfie check so you can continue without doing the selfie check.

See test info here: https://docs.banxa.com/docs/testing-information

Summary by CodeRabbit

  • Refactor
    • Enhanced financial accuracy in purchase and wallet flows with improved currency calculations using Decimal instead of double.
    • Streamlined asset selection and state management for a smoother, more reliable user experience.
    • Improved event handling and state management in the Fiat Form for better clarity and performance.
    • Updated the handling of payment methods and quotes to ensure accurate financial data representation.
  • Chores
    • Removed redundant validations and outdated fee summary displays in withdrawal forms.
    • Cleaned up import statements and unnecessary code to boost performance and maintainability.

- remove unused functions
- remove duplicate imports
- ignore unused key element parameter
- remove deprecated analysis_options
validators were checking against the old variable field
- add asset, pubkeys and address to fiat form state
- add address selected event to fiat form bloc
- use logging package in fiat form bloc
- improve repository return type hints (don't use abstract type absolutely everywhere)
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 21, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request applies numerous refactoring changes across the codebase. In several files, explicit library names and unused imports have been removed. Method signatures, variable types, and event names have been updated to use more specific types (e.g., converting from generic interfaces or double to Decimal) and to improve clarity. The fiat form functionality has been restructured with new events, state properties, and integration changes utilizing the KomodoDefiSdk. Additionally, legacy methods, redundant test code, and obsolete lint rules have been removed to streamline the code.

Changes

File(s) Change Summary
app_theme/lib/app_theme.dart, lib/views/dex/.../grouped_list_view.dart, lib/views/wallet/coin_details/.../animated_portfolio_charts.dart Removed explicit library naming and redundant imports; deleted obsolete balance calculation code.
lib/bloc/analytics/analytics_repo.dart, lib/bloc/bridge_form/bridge_validator.dart, lib/bloc/taker_form/taker_validator.dart Simplified value conversions and integrated new SDK-based balance checks using KomodoDefiSdk and GetIt.
lib/bloc/fiat/banxa_fiat_provider.dart, lib/bloc/fiat/base_fiat_provider.dart, lib/bloc/fiat/fiat_repository.dart, lib/bloc/fiat/ramp_fiat_provider.dart, lib/bloc/fiat/models/fiat_transaction_limit.dart, lib/model/forms/fiat/fiat_amount_input.dart Updated return types from generic ICurrency/double to specific FiatCurrency/CryptoCurrency and Decimal; adjusted parsing, sorting, and constructor signatures accordingly.
lib/bloc/fiat/fiat_onramp_form/fiat_form_bloc.dart, lib/bloc/fiat/fiat_onramp_form/fiat_form_event.dart, lib/bloc/fiat/fiat_onramp_form/fiat_form_state.dart, lib/views/fiat/fiat_form.dart, lib/views/fiat/fiat_page.dart, lib/views/fiat/fiat_payment_method_group.dart, lib/views/fiat/fiat_payment_methods_grid.dart, lib/views/fiat/fiat_inputs.dart Restructured fiat form functionality: renamed events and methods, updated state properties (e.g., renaming selectedCoin to selectedAsset and adding asset address/pubkeys), and replaced legacy dependencies with KomodoDefiSdk.
lib/bloc/fiat/models/i_currency.dart Enhanced CryptoCurrency model with new factory methods (fromAsset, toAsset) and simplified the abbreviation logic in getAbbr.
lib/bloc/withdraw_form/withdraw_form_bloc.dart, lib/views/wallet/coin_details/coin_addresses.dart, lib/views/wallet/coin_details/withdraw_form/widgets/fill_form/fields/custom_fee/custom_fee_field_evm.dart, lib/views/wallet/coin_details/withdraw_form/widgets/fill_form/fields/fields.dart, lib/views/wallet/coin_details/wallet_manager_search_field.dart, lib/views/wallets_manager/widgets/wallet_creation.dart Removed unused methods (e.g., mixed-case Ethereum address check and fee summary builder), refactored bloc acquisition patterns, and simplified widget constructors (e.g., replacing explicit key with super.key).
lib/views/nfts/nft_tabs/nft_tab.dart, lib/views/settings/widgets/general_settings/app_version_number.dart, lib/views/settings/widgets/security_settings/password_update_page.dart, lib/views/settings/widgets/security_settings/seed_settings/seed_show.dart Updated comments to suppress warnings for unused parameters; adjusted ignore directives to be more specific.
packages/komodo_persistence_layer/analysis_options.yaml Removed lint rules for package_api_docs and unsafe_html to relax documentation and HTML safety restrictions.
Files under test_units/... (e.g., main.dart, total_24_change_test.dart, get_usd_balance_test.dart, test_util.dart) Removed test imports and commented out test invocations; updated test utility function by removing the balance parameter from the Coin constructor.

Sequence Diagram(s)

sequenceDiagram
    participant UI as FiatForm UI
    participant Bloc as FiatFormBloc
    participant SDK as KomodoDefiSdk
    participant Repo as FiatRepository

    UI->>Bloc: Dispatch FiatFormStarted / FiatFormRefreshed
    Bloc->>SDK: Initialize SDK & fetch asset/pubkey info (e.g. in _onCoinSelected)
    SDK-->>Bloc: Return asset details
    Bloc->>UI: Emit updated state (with selectedAsset, updated amounts)
    UI->>Bloc: Dispatch FiatFormSubmitted (trigger order submission)
    Bloc->>Repo: Process submission and fetch order status
    Repo-->>Bloc: Return order status update
    Bloc->>UI: Emit final state with order status
Loading

Suggested reviewers

  • AndrewDelaney
  • smk762
  • ShantanuSharma9873
  • CharlVS

Poem

I’m a happy little rabbit,
Hopping through fields of code so bright,
Changes crisp as freshly mown clover,
Refactored and neat – oh what a delight!
Bugs hop away, leaving our path pure and light.
🐇💻 Hop on, keep coding all day and night!


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.
    • 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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

- bloc events and states were not in line with bloc naming conventions
- double was still being used in places instead of decimal

both changes were made with new&old refactoring efforts in mind
@takenagain
Copy link
Collaborator Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 24, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@takenagain takenagain self-assigned this Mar 24, 2025
seeing as the inputs are not required, the action should not fail if they are empty (as is the case in non-dev feature branches it seems)
@takenagain takenagain added the bug Something isn't working label Mar 24, 2025
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 (12)
test_units/tests/utils/get_usd_balance_test.dart (1)

1-1: Consider adding migration timeline to the TODO comment

The TODO comment indicates these tests should be revisited or migrated to the SDK. Consider adding a more specific timeline or ticket reference to ensure this technical debt is properly tracked.

test_units/main.dart (2)

59-62: Consider adding JIRA/GitHub issue reference to TODOs

The TODO comment mentions re-enabling or migrating tests to the SDK, but lacks specific details about when or how this should be done. Consider adding a ticket reference to ensure this work isn't forgotten.

  group('Utils:', () {
-    // TODO: re-enable or migrate to the SDK
+    // TODO(TICKET-123): re-enable or migrate to the SDK after HD wallet implementation is complete
    // testUsdBalanceFormatter();

69-74: Similar TODO lacks specificity

Similar to the previous comment, this TODO would benefit from additional context such as a ticket reference or timeline.

  group('Helpers: ', () {
    testMaxMinRational();
    testCalculateBuyAmount();
-    // TODO: re-enable or migrate to the SDK
+    // TODO(TICKET-123): re-enable or migrate to the SDK after HD wallet implementation is complete
    // testGetTotal24Change();
app_theme/lib/app_theme.dart (1)

1-1: Consider specifying the library name for better organization.

Changing from a named library (library app_theme;) to an unnamed library (library;) might affect code organization and clarity. Named libraries can help with identification and prevent naming conflicts. Unless there's a specific reason to remove the name, consider maintaining the explicit library name.

-library;
+library app_theme;
lib/bloc/bridge_form/bridge_validator.dart (2)

395-395: Updated balance check to use SDK method.

The balance property access has been replaced with a method call that takes the SDK as an argument, which aligns with the refactoring to use the SDK for data access.

Consider using a small epsilon or dedicated method for checking if the balance is close to zero rather than exact floating-point comparison, which can be prone to precision issues:

-if (parentSell.balance(sdk) == 0.00) return false;
+if (parentSell.balance(sdk) <= 0.001) return false;  // or use a dedicated isZeroBalance method

408-410: Updated balance check for parent buy coin.

Similar to the parent sell coin, the balance check now uses the SDK method instead of a direct property access.

As with the previous balance check, consider using a small epsilon value instead of exact equality for floating-point comparison:

-if (parentBuy.balance(sdk) == 0.00) return false;
+if (parentBuy.balance(sdk) <= 0.001) return false;  // or use a dedicated isZeroBalance method
lib/bloc/fiat/models/fiat_transaction_limit.dart (1)

14-16: Ensure JSON fields are consistently strings to avoid casting issues.
If the backend sometimes returns numeric types for min, max, or weekly, this cast (as String?) might fail. Consider additional checks or conversions for non-string values if the server’s response isn’t guaranteed to be a string.

lib/views/fiat/fiat_inputs.dart (3)

78-93: Efficient text synchronization
This logic properly updates the text field if the new amount differs from the current one. Consider locale-based decimal handling if users enter commas.


98-104: Runtime casting
Casting ICurrency to FiatCurrency or CryptoCurrency could cause runtime errors if newValue is mismatched. Prefer typed sources or typed dropdowns to avoid casts.


185-185: Widget naming mismatch
FiatCurrencyItem is used with a CryptoCurrency, which can be confusing. Consider renaming or introducing a more generalized widget for coin items.

lib/bloc/fiat/fiat_onramp_form/fiat_form_bloc.dart (1)

122-128: _getAmountInputWithBounds
Using Decimal.parse for limit boundaries is correct, but consider using tryParse to avoid potential exceptions if data is malformed.

- minAmount = Decimal.parse(firstLimit.min.toString());
+ final parsedMin = Decimal.tryParse(firstLimit.min.toString());
- maxAmount = Decimal.parse(firstLimit.max.toString());
+ final parsedMax = Decimal.tryParse(firstLimit.max.toString());
lib/bloc/fiat/fiat_onramp_form/fiat_form_event.dart (1)

66-67: Simplified form submission event.

The FiatFormSubmitted event is concise and clearly named. Consider adding a constructor with const modifier for consistency with other events.

-final class FiatFormSubmitted extends FiatFormEvent {}
+final class FiatFormSubmitted extends FiatFormEvent {
+  const FiatFormSubmitted();
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d513ddc and 7c148bb.

📒 Files selected for processing (36)
  • app_theme/lib/app_theme.dart (1 hunks)
  • lib/bloc/analytics/analytics_repo.dart (1 hunks)
  • lib/bloc/bridge_form/bridge_validator.dart (4 hunks)
  • lib/bloc/fiat/banxa_fiat_provider.dart (2 hunks)
  • lib/bloc/fiat/base_fiat_provider.dart (1 hunks)
  • lib/bloc/fiat/fiat_onramp_form/fiat_form_bloc.dart (15 hunks)
  • lib/bloc/fiat/fiat_onramp_form/fiat_form_event.dart (2 hunks)
  • lib/bloc/fiat/fiat_onramp_form/fiat_form_state.dart (5 hunks)
  • lib/bloc/fiat/fiat_repository.dart (2 hunks)
  • lib/bloc/fiat/models/fiat_transaction_limit.dart (3 hunks)
  • lib/bloc/fiat/models/i_currency.dart (3 hunks)
  • lib/bloc/fiat/ramp/ramp_fiat_provider.dart (3 hunks)
  • lib/bloc/taker_form/taker_validator.dart (4 hunks)
  • lib/bloc/withdraw_form/withdraw_form_bloc.dart (0 hunks)
  • lib/model/forms/fiat/fiat_amount_input.dart (2 hunks)
  • lib/views/dex/simple/form/tables/orders_table/grouped_list_view.dart (0 hunks)
  • lib/views/fiat/fiat_form.dart (5 hunks)
  • lib/views/fiat/fiat_inputs.dart (6 hunks)
  • lib/views/fiat/fiat_page.dart (3 hunks)
  • lib/views/fiat/fiat_payment_method_group.dart (1 hunks)
  • lib/views/fiat/fiat_payment_methods_grid.dart (1 hunks)
  • lib/views/nfts/nft_tabs/nft_tab.dart (1 hunks)
  • lib/views/settings/widgets/general_settings/app_version_number.dart (2 hunks)
  • lib/views/settings/widgets/security_settings/password_update_page.dart (2 hunks)
  • lib/views/settings/widgets/security_settings/seed_settings/seed_show.dart (2 hunks)
  • lib/views/wallet/coin_details/coin_details_info/charts/animated_portfolio_charts.dart (0 hunks)
  • lib/views/wallet/coin_details/coin_details_info/coin_addresses.dart (1 hunks)
  • lib/views/wallet/coin_details/withdraw_form/widgets/fill_form/fields/custom_fee/custom_fee_field_evm.dart (0 hunks)
  • lib/views/wallet/coin_details/withdraw_form/widgets/fill_form/fields/fields.dart (0 hunks)
  • lib/views/wallet/wallet_page/wallet_main/wallet_manager_search_field.dart (0 hunks)
  • lib/views/wallets_manager/widgets/wallet_creation.dart (1 hunks)
  • packages/komodo_persistence_layer/analysis_options.yaml (0 hunks)
  • test_units/main.dart (2 hunks)
  • test_units/tests/helpers/total_24_change_test.dart (1 hunks)
  • test_units/tests/utils/get_usd_balance_test.dart (1 hunks)
  • test_units/tests/utils/test_util.dart (0 hunks)
💤 Files with no reviewable changes (8)
  • lib/views/dex/simple/form/tables/orders_table/grouped_list_view.dart
  • test_units/tests/utils/test_util.dart
  • packages/komodo_persistence_layer/analysis_options.yaml
  • lib/bloc/withdraw_form/withdraw_form_bloc.dart
  • lib/views/wallet/coin_details/withdraw_form/widgets/fill_form/fields/fields.dart
  • lib/views/wallet/coin_details/coin_details_info/charts/animated_portfolio_charts.dart
  • lib/views/wallet/wallet_page/wallet_main/wallet_manager_search_field.dart
  • lib/views/wallet/coin_details/withdraw_form/widgets/fill_form/fields/custom_fee/custom_fee_field_evm.dart
🔇 Additional comments (134)
test_units/tests/utils/get_usd_balance_test.dart (1)

12-51: Document the reason for commenting out all test cases

While the TODO comment at the top gives some context, it would be helpful to add a more detailed explanation about why these tests are being commented out rather than deleted or fixed. If these tests validate important functionality, commenting them out could hide potential regressions.

Are these tests being replaced by equivalent tests in the SDK? If so, consider either:

  1. Adding a reference to where the new tests are located
  2. Deleting these tests entirely to avoid confusion
  3. Moving these tests to the SDK repository if that's more appropriate
test_units/main.dart (1)

32-89:

❓ Verification inconclusive

Consider adding test coverage verification

With multiple test functions commented out, it's important to ensure that test coverage hasn't been significantly reduced, especially for critical functionality related to balance and change calculations.


🏁 Script executed:

#!/bin/bash
# Check which files might be affected by removing these tests
echo "Finding potential affected files:"
rg -t dart "getFormattedUsdBalance|getTotal24Change" --files-with-matches

# Check if there are other tests that might provide coverage for these functionalities
echo "Checking for other tests that might cover similar functionality:"
rg -t dart "usdBalance|24Change|UsdFormatter" --files-with-matches

Length of output: 940


Ensure Sufficient Test Coverage for Balance & Change Calculations

It appears that while tests like testUsdBalanceFormatter() and testGetTotal24Change() have been commented out in test_units/main.dart, related functionalities are still being exercised by tests in files such as:

  • test_units/tests/utils/get_usd_balance_test.dart
  • test_units/tests/helpers/total_24_change_test.dart

Additionally, similar keywords are present in several production files (for example, in lib/views/wallet/common/wallet_helper.dart), which suggests that these functionalities remain active in the current coverage suite.

Action Items:

  • Verify that the tests in the aforementioned files adequately cover the balance calculations and 24‑hour change functionalities.
  • If the migration to the SDK (or other changes) is intended, please make sure that the new testing approach maintains or exceeds the current coverage.
  • Update the documentation or add comments as needed to clarify the test coverage strategy for these critical features.
lib/views/settings/widgets/general_settings/app_version_number.dart (2)

39-40: LGTM: Appropriate lint warning suppression for unused parameter.

The added comment properly suppresses the lint warning for an unused constructor parameter in a private class. This is a common pattern in Flutter widget classes where the key parameter is defined by the parent class but not directly used in the child class.


92-93: LGTM: Appropriate lint warning suppression for unused parameter.

This lint suppression is consistent with the approach used for other StatelessWidget classes in the file. It specifically targets the unused parameter warning rather than suppressing broader issues.

lib/views/nfts/nft_tabs/nft_tab.dart (1)

122-123: LGTM: Improved lint suppression specificity.

The change from unused_element to unused_element_parameter makes the lint suppression more precise, which is a good practice. This specificity clearly communicates that only the unused parameter is being suppressed, not the entire element.

lib/views/settings/widgets/security_settings/seed_settings/seed_show.dart (2)

81-82: LGTM: Consistent lint warning suppression.

This lint suppression follows the same pattern as in other files, specifically targeting the unused parameter rather than the entire element or class.


404-405: LGTM: Consistent lint warning suppression.

The lint suppression is appropriately applied to the unused key parameter in the _SelectableSeedWord constructor, following the project's pattern for handling unused parameters in StatelessWidget subclasses.

lib/views/fiat/fiat_payment_method_group.dart (1)

63-63: LGTM: Improved event naming for better clarity.

Renaming from PaymentMethodSelected to FiatFormPaymentMethodSelected improves code clarity by explicitly indicating which component the event belongs to. This change aligns with best practices for event naming in a complex application.

lib/views/fiat/fiat_payment_methods_grid.dart (1)

46-47:

❓ Verification inconclusive

Property reference updated to use selectedAsset instead of selectedCoin.

This change aligns with the broader refactoring effort to use "asset" terminology instead of "coin" throughout the codebase. The non-null assertion operator (!) is used here, so verify that state.selectedAsset.value is always non-null when this code path is executed.


🏁 Script executed:

#!/bin/bash
# Check if there are any null checks for selectedAsset before this code path

# Look for null checks or conditional rendering related to selectedAsset
rg -A 2 -B 2 "selectedAsset\s*[?]\s*[.]\s*value" --glob "*.dart"

# Look for other files that have been updated from selectedCoin to selectedAsset
rg -l "selectedCoin\s*[.]\s*value" --glob "*.dart"

Length of output: 119


Please verify that state.selectedAsset.value can never be null at runtime.

The renaming update from selectedCoin to selectedAsset is consistent with the refactoring effort. However, since our initial searches produced no evidence of explicit null checks or conditional validations for state.selectedAsset before its usage (i.e. using the non-null operator !), please manually confirm that the value is indeed always initialized (or safely guarded) by the time this code is reached.

  • Confirm that any parent widget or business logic guarantees state.selectedAsset is non-null.
  • Check for conditional rendering or initialization logic elsewhere in the codebase to avoid potential runtime exceptions.

To help with this verification, you might run:


🏁 Script executed:

#!/bin/bash
# Search for any conditional logic related to state.selectedAsset ensuring it is non-null
rg -n -C3 "if\s+\(.*state\.selectedAsset[^\)]*!=\s*null" --glob "*.dart"

# Locate assignments or initializations for state.selectedAsset in the repository
rg -n -C3 "state\.selectedAsset\s*=" --glob "*.dart"

Length of output: 251


Ensure non-null guarantee for state.selectedAsset before usage

The update to replace selectedCoin with selectedAsset in the snippet below fits the broader refactoring. However, automated searches did not reveal any explicit null checks or initialization patterns for state.selectedAsset in the surrounding code. Please manually verify that this property is always initialized (and never null) prior to its usage with the non-null assertion (!).

  • Verify that a parent widget or business logic initializes state.selectedAsset to a valid value.
  • Ensure that any fallback or conditional rendering logic properly prevents execution of this code when state.selectedAsset is null.
              state.selectedAsset.value!.symbol,
              state.selectedFiat.value!.symbol,
lib/bloc/analytics/analytics_repo.dart (1)

54-54: Code simplification for parameter sanitization.

The type check has been removed, and all values are now directly converted to strings using toString(). This is a good simplification since all objects in Dart have a toString() method, and the map parameters are already declared as Map<String, Object>.

lib/bloc/bridge_form/bridge_validator.dart (2)

2-3: Added imports for Get_it and Komodo SDK.

These new imports support the refactoring of the balance checks to use the SDK for retrieving coin balances.


375-377: Added SDK instance for balance retrieval.

The KomodoDefiSdk is now retrieved from the GetIt service locator to support balance checking.

lib/views/wallets_manager/widgets/wallet_creation.dart (1)

16-21: Updated constructor parameter syntax to use super.key.

This change utilizes Dart's newer and more concise constructor parameter syntax. The functionality remains the same, but the code is now more elegant and aligned with modern Flutter best practices.

lib/views/settings/widgets/security_settings/password_update_page.dart (2)

104-105: Added linting suppression for unused parameter.

The comment // ignore: unused_element_parameter was added to suppress warnings for the unused onSuccess parameter in the private _FormView constructor. This improves code quality by acknowledging that the parameter is intentionally passed but not used directly in the class implementation.


370-371: Added linting suppression for unused parameter.

Similar to the previous change, this comment suppresses warnings for the unused back parameter in the _SuccessView constructor. This is a good practice when parameters are required for API consistency but not directly used in the implementation.

lib/views/fiat/fiat_page.dart (4)

4-4: Added KomodoDefiSdk import for SDK integration.

The import for the KomodoDefiSdk package has been added, which is used later to retrieve the SDK instance from the repository provider.


54-54: Added SDK retrieval from repository provider.

Added a new variable to get the KomodoDefiSdk instance from context, which is part of the refactoring to use the SDK for fiat operations instead of directly using the coins repository.


56-59: Updated FiatFormBloc instantiation to use SDK.

This change replaces the coinsRepository parameter with the new sdk parameter in the FiatFormBloc constructor, and immediately triggers the FiatFormStarted() event. This is part of the migration to use the KomodoDefiSdk for fiat operations.


177-178: Improved linting suppression specificity.

Changed the comment from // ignore: unused_element to // ignore: unused_element_parameter to more precisely indicate that only the unused parameter should be ignored, not the entire element.

lib/bloc/taker_form/taker_validator.dart (2)

2-3: Added GetIt and KomodoDefiSdk imports.

Added imports for the GetIt service locator and the KomodoDefiSdk, which are used to retrieve the SDK instance and access coin balances.


253-255: Updated balance retrieval to use SDK.

Modified how coin balances are accessed by using a method call with the SDK instance (balance(sdk)) instead of directly accessing a property. This change ensures balance retrieval is done through the SDK, which may provide more up-to-date information.

-if (parentSell.balance == 0.00) return false;
+if (parentSell.balance(sdk) == 0.00) return false;

-if (parentBuy.balance == 0.00) return false;
+if (parentBuy.balance(sdk) == 0.00) return false;

The added comment also helps explain the purpose of the SDK variable.

Also applies to: 273-273, 286-286

lib/bloc/fiat/base_fiat_provider.dart (1)

19-19: Improved type specificity in currency list return types.

Changed the return types of getFiatList() and getCoinList() methods from generic Future<List<ICurrency>> to more specific Future<List<FiatCurrency>> and Future<List<CryptoCurrency>> respectively. This improves type safety and makes the API more explicit about what kind of currencies each method returns.

-Future<List<ICurrency>> getFiatList();
+Future<List<FiatCurrency>> getFiatList();

-Future<List<ICurrency>> getCoinList();
+Future<List<CryptoCurrency>> getCoinList();

Also applies to: 21-21

lib/bloc/fiat/ramp/ramp_fiat_provider.dart (3)

90-90: More specific return type improves type safety

The return type is now more specific (Future<List<FiatCurrency>> instead of Future<List<ICurrency>>), which improves type safety and eliminates the need for explicit casting by consumers of this API.


105-105: More specific return type improves type safety

The return type is now more specific (Future<List<CryptoCurrency>> instead of Future<List<ICurrency>>), which improves type safety and eliminates the need for explicit casting by consumers of this API.


121-121: Updated casting to match new return type

The cast has been properly updated to align with the more specific return type of the method.

lib/bloc/fiat/models/i_currency.dart (4)

1-3: Appropriate imports for SDK integration

The addition of these imports enables integration with the KomodoDefiSdk and support for assets conversion.


40-47: Added factory constructor for Asset conversion

This factory method enables converting SDK Assets to CryptoCurrency objects, providing a convenient bridge between the SDK and application models.


71-73: Added toAsset conversion method

This method complements the fromAsset factory and allows for bidirectional conversion between CryptoCurrency and SDK Asset types.


58-63:

✅ Verification successful

Simplified getAbbr method with potential implications

The method has been simplified to just return the symbol, with the previous implementation commented out.

Make sure that other parts of the codebase don't rely on the previous format (which included the chain type). Since there's a TODO comment, consider creating a tracking issue to determine if the previous implementation is still necessary anywhere in the codebase.


🏁 Script executed:

#!/bin/bash
# Search for uses of getAbbr() to check if any code relies on the previous format
echo "Searching for uses of getAbbr() in the codebase..."
rg "getAbbr\(\)" -A 3 -B 3

Length of output: 3089


Simplified getAbbr() Change – Verified No Downstream Dependency on Chain Type

  • The search across the codebase (in files like fiat_select_button.dart and fiat_repository.dart) shows that all callers of getAbbr() are using it solely to retrieve the currency symbol.
  • There’s no evidence that any part of the code expects the old, concatenated format (with the chain type appended).
  • It’s still recommended to create a tracking issue to revisit whether the extended format might be required in any future edge cases.
lib/views/wallet/coin_details/coin_details_info/coin_addresses.dart (4)

34-34: Added late-initialized bloc reference

Good practice to store the bloc as a class variable for proper lifecycle management.


37-41: Properly initialized bloc in didChangeDependencies

Using didChangeDependencies to initialize the bloc reference is the correct approach since it ensures the widget is properly attached to the widget tree before accessing the context.


44-48: Improved bloc disposal

Using the stored bloc reference in the dispose method ensures proper resource cleanup and avoids potential context-related issues during disposal.


54-133: Simplified widget structure

The widget structure has been improved by removing unnecessary nesting and directly using BlocBuilder, making the code more readable and maintainable.

lib/bloc/fiat/fiat_repository.dart (2)

78-88: Enhanced getFiatList with specific return type

The method now returns a more specific type (Future<List<FiatCurrency>> instead of Future<List<ICurrency>>) and includes improved sorting logic for the returned currencies.


106-113: Enhanced getCoinList with specific return type

The method now returns a more specific type (Future<List<CryptoCurrency>> instead of Future<List<ICurrency>>), aligning with similar changes in the provider classes.

lib/bloc/fiat/models/fiat_transaction_limit.dart (2)

2-2: Switching to Decimal for financial calculations looks solid.
This approach helps avoid floating-point inaccuracies when dealing with money.


30-32: Using Decimal for min, max, and weekly is appropriate.
Retaining these as Decimal fields aligns well with precise monetary calculations.

lib/bloc/fiat/banxa_fiat_provider.dart (2)

160-160: Refining return type to Future<List> is a good move.
This improves type safety and clarity when working with a list of fiat currencies.


174-178: Shift from generic ICurrency to CryptoCurrency is commendable.
Declaring List<CryptoCurrency> enforces correct usage of crypto-specific properties.

lib/bloc/fiat/fiat_onramp_form/fiat_form_state.dart (28)

5-8: Enhanced documentation for the form state is helpful.
These doc comments clearly describe the class’s responsibilities.


12-12: Introducing selectedAsset constructor parameter aligns with new asset handling.
This ensures the state can track the chosen crypto currency accurately.


23-24: New properties for asset address and pubkeys expand the form’s capabilities.
Capturing these fields in state is essential for onramp logic.


27-27: Adding an explicit doc comment for the initial state clarifies defaults.
This is beneficial for maintainers.


32-32: Defaulting selectedAsset to BTC is a practical baseline.
It provides a sensible starting point for the form.


36-36: Setting selectedAssetAddress to null in initial state is reasonable.
This ensures no address is assumed without user action.


45-46: Using FiatMode.onramp and null selectedCoinPubkeys by default is coherent with new features.
It keeps the state aligned with typical onramp usage.


48-48: Clarifying the purpose of selectedFiat.
The doc comment ties the fiat field to the selected crypto asset.


52-52: Declaring final CurrencyInput selectedAsset emphasizes immutability.
This ensures consistent usage and enforces correct updates via copyWith.


54-54: Annotation clarifies the fiatAmount usage relative to selectedAsset.
Keeping these doc comments updated fosters better readability.


57-57: Doc comment conveys the meaning of selectedPaymentMethod in the new flow.
This helps maintainers understand its role in final checkout.


60-64: Documenting selectedAssetAddress and selectedCoinPubkeys clarifies on-chain details.
Tracking addresses and pubkeys in state is crucial for automated post-checkout flows.


98-101: Switch to Decimal for minFiatAmount and maxFiatAmount ensures better financial precision.
It aligns with the updated FiatTransactionLimit usage.


102-103: No functional changes at lines 102 and 103.
Skipping further comment as they appear to be blank or spacing adjustments.


105-107: Adding isLoadingCurrencies and isLoading improves UI handling logic.
Explicit distinctions between loading states are beneficial for clarity.


109-112: Requiring selectedAssetAddress != null for canSubmit is a logical safeguard.
Users can’t proceed without specifying an address.


119-120: copyWith additions for selectedAsset allow dynamic updates while preserving immutability.
Consistent with the rest of the newly introduced fields.


122-122: Incorporating selectedAssetAddress into copyWith fosters robust address updates.
This is essential for multi-stage onramp flows.


127-128: Including fiatList and coinList in copyWith manages currency refresh scenarios.
Allows seamless updates when new lists are fetched.


131-131: selectedCoinPubkeys in copyWith covers advanced wallet integrations.
It ensures the state can reflect updated pubkeys.


135-135: Retaining fallback to this.selectedAsset in copyWith is a standard, safe approach.
Preserves existing data when no new asset is provided.


138-138: Same pattern for selectedAssetAddress ensures consistency.
Essential for partial updates without overwriting existing addresses unintentionally.


148-148: selectedCoinPubkeys property also follows the same fallback pattern.
This is aligned with the immutability and partial updates principle.


155-155: Adding selectedAsset to the list of Formz inputs clarifies validation.
This helps unify the form’s validation process.


159-159: Including coinList in props ensures re-rendering when coinList changes.
This is vital for state equality checks in Equatable.


162-162: Adding selectedAsset to props likewise ensures accurate state comparisons.
Prevents unintended stale data if asset changes.


164-164: selectedAssetAddress is now part of props, improving reactivity.
This ensures UI updates if the address changes.


174-174: Remember to include selectedCoinPubkeys in props to track pubkey changes.
Good addition for parity with other properties.

lib/views/fiat/fiat_form.dart (11)

37-44: Initializing the form state and refreshing on init is consistent.
This ensures the UI is up-to-date once the user arrives.


47-153: Overhauled build method with BlocListeners & BlocConsumers is well-structured.
These changes consolidate event handling and UI rendering neatly, though keep an eye on potential rebuild performance if the widget tree grows.


155-156: Refactored _completeOrder to dispatch FiatFormSubmitted clearly.
This follows the established pattern of letting the bloc handle logic.


158-168: Forcing refresh on fiat/coin/amount changes ensures real-time updates.
These calls to FiatFormRefreshed(forceRefresh: true) are consistent with dynamic form logic.


170-171: _setActiveTab triggers mode updates in the bloc.
Clean separation of concerns for UI tab selection and state transitions.


179-182: Dispatching FiatFormWalletAuthenticated/FiatFormAccountCleared on login state change is correct.
It aligns with the reactivity when user logs in or out.


193-193: _openCheckoutPage bridging web vs. mobile flows is well-structured.
Providing a consistent experience across platforms can reduce CORS and provider mismatch issues.


210-212: Capturing console messages from WebView is a helpful debugging approach.
Forwarding them to the bloc for status handling is neat.


227-228: Starting order status watch upon submission is a natural next step.
This sets the stage for listening to real-time updates.


237-237: Invoking _showPaymentStatusDialog for non-pending statuses clarifies the flow.
This ensures the user sees immediate feedback on success/failure states.


241-241: _showPaymentStatusDialog details each payment status thoroughly.
Offering distinct user messages based on order status is user-friendly.

lib/model/forms/fiat/fiat_amount_input.dart (4)

1-1: Consolidate numeric precision with Decimal
No major concerns with this import; it’s necessary for precise financial calculations.


26-27: Appropriate transition from double? to Decimal?
Using Decimal for currency amounts is more precise and avoids floating-point errors.


29-29: Value parsing improved
Switching from double parsing to Decimal helps avoid precision issues for monetary calculations.


21-23:

❓ Verification inconclusive

Verify usage with new constructor signature
Dropping the default minValue=0 might allow negative amounts if not explicitly set. Please confirm that no calling code relied on the old default.


🏁 Script executed:

#!/bin/bash
# Description: Searching for all calls to FiatAmountInput.pure or .dirty to see if code relies on default minValue=0
rg -A 3 "FiatAmountInput\.(pure|dirty)\("

Length of output: 1216


Action: Verify Constructor Call Sites and Default Value Handling

We've identified that the pure constructor is called without an explicit minValue in at least one location (in lib/bloc/fiat/fiat_onramp_form/fiat_form_state.dart via const FiatAmountInput.pure()). This change from a default minValue = 0 to potentially null might let negative amounts slip through unless handled further downstream.

  • Review all instances where FiatAmountInput.pure is used (especially in fiat_form_state.dart) to ensure that a missing minValue does not inadvertently allow negative amounts.
  • Confirm that either the consumer code or internal validations guard against negative input when minValue is not provided explicitly.

Please verify that no calling code relies on the previous default of minValue = 0.

lib/views/fiat/fiat_inputs.dart (5)

3-6: New imports for bridging with KomodoDefiSdk
No apparent issues. These references appear necessary for the updated logic.


19-34: Additional constructor parameters
Providing selectedAsset, selectedAssetAddress, selectedAssetPubkeys, and onSourceAddressChanged increases clarity. Please verify backward compatibility or confirm any required references are updated.


36-45: Decimals for amounts
Switching from doubles to decimals is beneficial for accurate financial calculations.


47-48: More robust typed callbacks
Changing callback signatures to accept FiatCurrency/CryptoCurrency promotes safer typing versus a generic ICurrency.


198-212: SourceAddressField integration
The new Row and SourceAddressField logic is clear and provides an intuitive way to manage addresses. Good addition.

lib/bloc/fiat/fiat_onramp_form/fiat_form_bloc.dart (28)

6-12: Imports for Decimal, SDK, and logging
These imports are appropriate for the new form logic.


29-31: Injecting KomodoDefiSdk
Using _sdk to delegate pubkey retrieval centralizes functionality.


33-50: Event registrations
All relevant events are set up, aligning with the bloc pattern for form management.

Also applies to: 55-55


62-62: Logger usage
Centralizing logs under _log is helpful for debugging.


64-69: _onStarted: Auto-trigger fetch
Automatically dispatching FiatFormCurrenciesFetched on start is convenient. Confirm it won’t trigger duplicate fetch cycles in repeated scenarios.


71-80: _onFiatSelected
Establishes the chosen fiat in state. Implementation is straightforward.


82-107: _onCoinSelected
Retrieves and sets pubkeys for the newly selected coin. Error handling is well done.


109-116: _onAmountUpdated
Debounced updates help reduce unnecessary triggers. Good approach.


139-140: _onSelectPaymentMethod
Updates the payment method retrieval to reflect user choice. No issues found.


156-157: _onSubmitForm
Integrates the form submission workflow correctly.


161-162: Form validation logging
Warns about invalid states. Straightforward usage.


171-178: Order creation
Properly passing decimal-based parameters to the repository. Implementation looks sound.


181-182: Order creation error
Logs warnings and handles fallback.


199-201: Setting final states
Assigns checkout URL and order ID upon success. No concerns.


204-204: Error logging
Using _log.shout for high-severity errors is reasonable.


222-223: Check for empty or invalid decimal
Falls back to default payment methods if user input is invalid. Good usability measure.


237-238: _updateAssetPubkeys
Refreshes coin addresses seamlessly when needed.


254-256: onError
Graceful fallback in case payment method retrieval fails.


299-299: Load currency list error
Error is clearly logged.


304-305: _onWalletAuthenticated
Pubkeys are reloaded post-authentication, ensuring updated state.


309-317: Fetching pubkeys
Implementation is consistent. Using firstOrNull avoids index errors.


320-321: Error logs
Sets address to null and logs the error if pubkeys retrieval fails.


325-330: _onClearAccountInformation
Resets and clears the form state.


332-346: _updateAssetPubkeys
Similar logic to _onCoinSelected; ensures consistency in updating addresses.


349-350: _onPaymentStatusMessage
Guarded JSON parsing for ramp messages. Implementation is sufficient.


405-432: _onWatchOrderStatus
Monitors Banxa order status stream. Implementation is aligned with the overall architecture.


461-462: Null address scenario
Correctly flags unsupported coins or absent wallet.


476-486: _onCoinAddressSelected
Updates selectedAssetAddress upon user selection. Straightforward.

lib/bloc/fiat/fiat_onramp_form/fiat_form_event.dart (19)

3-3: Good addition of comprehensive documentation.

Adding clear documentation for the base class helps with code understandability and maintainability.


11-14: Well-defined event for initializing the form.

The FiatFormStarted event is properly documented and follows the consistent naming convention. This is a good practice for handling the initialization of the form.


16-17: Improved naming consistency with the FiatForm prefix.

Renaming to FiatFormOnRampPaymentStatusMessageReceived aligns with the naming convention and provides better clarity on the event's purpose and scope.


26-28: Good renaming for clarity and consistency.

Changing from SelectedFiatCurrencyChanged to FiatFormFiatSelected follows the naming convention and makes the purpose clearer.


30-30: Type clarification improves code quality.

Using the more specific FiatCurrency type instead of a generic type improves type safety and documentation.


36-38: Consistent naming convention applied.

Renaming from SelectedCoinChanged to FiatFormCoinSelected maintains consistency with other events and clearly communicates its purpose.


40-40: Type improvement for better clarity.

Using the more specific CryptoCurrency type instead of a generic type enhances code clarity and type safety.


46-48: Clear naming and documentation for amount updates.

The renaming to FiatFormAmountUpdated and the added documentation clearly indicate the event's purpose.


56-58: Consistent naming for payment method selection.

The renaming to FiatFormPaymentMethodSelected follows the established pattern and improves readability.


69-72: Good documentation and naming for mode updates.

The FiatFormModeUpdated event is well-documented and follows the naming convention.


73-75: Helpful named constructor for mode updates.

The named constructor fromTabIndex is a good approach for converting UI-specific data to the domain model.


83-86: Clear purpose for payment status clearing.

The FiatFormPaymentStatusCleared event is well-documented and follows the naming convention.


88-91: Good authentication event for wallet operations.

The FiatFormWalletAuthenticated event provides a clear signal for authentication completion.


93-96: Well-defined event for clearing account data.

The FiatFormAccountCleared event follows the naming convention and has a clear purpose.


98-102: Good design for refresh functionality with force option.

The FiatFormRefreshed event includes a forceRefresh parameter with a default value, providing flexibility in refreshing behavior.


104-105: Helpful documentation for the forceRefresh parameter.

The documentation clarifies the purpose of the forceRefresh flag, which is good for maintainability.


111-114: Well-defined event for currency fetching.

The FiatFormCurrenciesFetched event is properly documented and follows the naming convention.


116-119: Good implementation for order status watching.

The FiatFormOrderStatusWatchStarted event provides a clear purpose for initiating order status monitoring.


121-129: Key implementation for HD wallet address selection support.

The FiatFormCoinAddressSelected event is critical for the HD wallet address selection feature mentioned in the PR objectives. The use of PubkeyInfo type provides strong typing for addresses.

Flutter compilation errors were hidden in the generate-assets action, which would cause the workflow to fail without printing error logs
- use Decimal.tryParse in payment provider min/max value parsing
- add locale-aware decimal parsing
- remove 'as Type' casting in UI layer
- add todo comment
@takenagain
Copy link
Collaborator Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 25, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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 (15)
.github/actions/generate-assets/action.yml (1)

65-67: Fix trailing whitespace

There are trailing spaces on lines 65, 66, and 80 that should be removed.

-# Run flutter build once to download coin icons and config files. 
-# This step is expected to "fail", since flutter build has to run again 
+# Run flutter build once to download coin icons and config files.
+# This step is expected to "fail", since flutter build has to run again
 # after the assets are downloaded to register them in AssetManifest.bin
 ...
-set -e  # Restore exit on error behavior
+set -e  # Restore exit on error behavior

Also applies to: 80-80

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 65-65: trailing spaces

(trailing-spaces)


[error] 66-66: trailing spaces

(trailing-spaces)

lib/shared/utils/formatters.dart (1)

311-313: Consider centralizing repetitive formatting logic.

The logic mirrors the approach at lines 183–185. If this pattern occurs frequently, factoring it out into a shared helper might reduce duplication and simplify changes.

lib/bloc/fiat/ramp/models/host_assets_config.dart (1)

1-42: Thorough model definition – consider JSON validation & doc comments.

  1. The constructor and factory method handle essential fields, but missing or malformed JSON values could cause parse exceptions. Consider adding graceful fallback or validation.
  2. If this class is public API, adding doc comments on each field and constructor parameter can improve clarity for consumers.

Would you like to incorporate default/fallback handling for missing JSON keys or values?

lib/bloc/fiat/ramp/models/ramp_asset_info.dart (1)

52-74: Comprehensive JSON parsing, but missing toJson method.

The fromJson method handles all fields properly, but there's no corresponding toJson method which would be needed for full serialization support.

Consider adding a toJson method for consistency with other model classes:

+  Map<String, dynamic> toJson() {
+    return {
+      'name': name,
+      'symbol': symbol,
+      'decimals': decimals,
+      'price': price,
+      'minPurchaseAmount': minPurchaseAmount?.toString(),
+      'maxPurchaseAmount': maxPurchaseAmount?.toString(),
+      'address': address,
+      'chain': chain,
+      'currencyCode': currencyCode,
+      'enabled': enabled,
+      'hidden': hidden,
+      'logoUrl': logoUrl,
+      'minPurchaseCryptoAmount': minPurchaseCryptoAmount,
+      'networkFee': networkFee.toString(),
+      'type': type,
+    };
+  }
lib/views/fiat/fiat_form.dart (5)

47-48: Follow through on the TODO for checkout URL reuse.
Caching the generated checkout URL in the FiatFormBloc could prevent generating unnecessary orders on repeated submissions when user inputs are unchanged.

Would you like help implementing a mechanism to store and reuse the checkout URL when the relevant form data is unchanged?


71-104: Reassess the listenWhen condition.
You’re only listening for changes to fiatOrderStatus. If you need to react to other state changes, consider adjusting or removing the listenWhen filter.


117-137: Prevent forced casts by validating the input types.
The statements such as state.selectedFiat.value! as FiatCurrency presume the type is guaranteed. An unexpected runtime type may cause runtime exceptions. Consider using safe type checks or a fallback.

- initialFiat: state.selectedFiat.value! as FiatCurrency,
+ initialFiat: state.selectedFiat.value is FiatCurrency 
+   ? state.selectedFiat.value as FiatCurrency 
+   : const FiatCurrency('USD', 'United States Dollar'),

158-168: Consider batching refresh triggers.
Calling FiatFormRefreshed(forceRefresh: true) on every single change can be expensive, especially if each triggers network calls. You might batch or debounce these calls for better performance.


193-213: Handle potential connectivity or error states for WebView.
Consider providing user feedback if checkoutUrl fails to load or if network issues occur.

lib/bloc/fiat/models/fiat_buy_order_info.dart (2)

73-73: Ensure robust error handling with Decimal.parse.
If data['fiat_amount'] is non-numeric (e.g., an unexpected string), this could throw a FormatException. Consider a fallback or try-catch.

- fiatAmount: Decimal.parse(data['fiat_amount']?.toString() ?? '0'),
+ fiatAmount: _parseDecimalOrZero(data['fiat_amount']),

129-129: Serializing Decimal consistently.
Using toString() is a common approach for JSON output, though consider formatting if specific decimal precision is required by the consumer.

lib/bloc/fiat/fiat_onramp_form/fiat_form_state.dart (1)

109-115: canSubmit gating ensures minimal checks.
Currently, it checks selectedAssetAddress != null. Consider adding validations for user’s coin selection and payment method if needed.

lib/model/forms/fiat/fiat_amount_input.dart (1)

55-89: Robust multi-locale parsing implementation
The parseLocaleAwareDecimal covers several distinct decimal formats (standard, US/UK, and European). While thorough, note that some locales might use other separators (e.g. spaces). If you expect further locale variations, consider extending or centralizing these parsing rules in a dedicated utility.

-// Third attempt: European format (1.234,56)
+// Third attempt: European format (1.234,56) or other edge cases
lib/bloc/fiat/fiat_onramp_form/fiat_form_bloc.dart (2)

82-103: Good error handling when retrieving pubkeys
Catching exceptions and logging a warning before setting selectedAssetAddress to null helps avoid crashes. Consider surfacing this error to the UI, so the user knows that pubkey retrieval failed.


405-432: Order status watch concurrency
Using restartable() within _onWatchOrderStatus helps prevent multiple overlapping watchers. Confirm that you intend to allow or disallow restarts if the user initiates additional watch events for the same order.

Would you like a shell script to verify concurrency usage across these event handlers in the entire codebase?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c148bb and bac8103.

📒 Files selected for processing (28)
  • .github/actions/generate-assets/action.yml (1 hunks)
  • lib/app_config/app_config.dart (1 hunks)
  • lib/bloc/coins_bloc/coins_bloc.dart (4 hunks)
  • lib/bloc/fiat/banxa_fiat_provider.dart (8 hunks)
  • lib/bloc/fiat/base_fiat_provider.dart (4 hunks)
  • lib/bloc/fiat/fiat_onramp_form/fiat_form_bloc.dart (14 hunks)
  • lib/bloc/fiat/fiat_onramp_form/fiat_form_event.dart (2 hunks)
  • lib/bloc/fiat/fiat_onramp_form/fiat_form_state.dart (5 hunks)
  • lib/bloc/fiat/fiat_repository.dart (7 hunks)
  • lib/bloc/fiat/models/fiat_buy_order_info.dart (7 hunks)
  • lib/bloc/fiat/models/fiat_payment_method.dart (7 hunks)
  • lib/bloc/fiat/models/fiat_price_info.dart (3 hunks)
  • lib/bloc/fiat/models/fiat_transaction_fee.dart (3 hunks)
  • lib/bloc/fiat/ramp/models/host_assets_config.dart (1 hunks)
  • lib/bloc/fiat/ramp/models/models.dart (1 hunks)
  • lib/bloc/fiat/ramp/models/onramp_purchase_quotation/onramp_purchase_quotation.dart (1 hunks)
  • lib/bloc/fiat/ramp/models/onramp_purchase_quotation/ramp_payment_method_name.dart (1 hunks)
  • lib/bloc/fiat/ramp/models/onramp_purchase_quotation/ramp_quote_result.dart (1 hunks)
  • lib/bloc/fiat/ramp/models/onramp_purchase_quotation/ramp_quote_result_for_payment_method.dart (1 hunks)
  • lib/bloc/fiat/ramp/models/ramp_asset_info.dart (1 hunks)
  • lib/bloc/fiat/ramp/ramp_fiat_provider.dart (8 hunks)
  • lib/model/forms/fiat/fiat_amount_input.dart (3 hunks)
  • lib/shared/utils/formatters.dart (3 hunks)
  • lib/shared/utils/utils.dart (2 hunks)
  • lib/views/fiat/fiat_form.dart (6 hunks)
  • lib/views/fiat/fiat_inputs.dart (6 hunks)
  • lib/views/fiat/fiat_payment_method_card.dart (3 hunks)
  • test_units/tests/helpers/total_24_change_test.dart (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • lib/bloc/fiat/ramp/models/models.dart
  • lib/bloc/fiat/ramp/models/onramp_purchase_quotation/onramp_purchase_quotation.dart
🚧 Files skipped from review as they are similar to previous changes (4)
  • test_units/tests/helpers/total_24_change_test.dart
  • lib/bloc/fiat/banxa_fiat_provider.dart
  • lib/bloc/fiat/ramp/ramp_fiat_provider.dart
  • lib/bloc/fiat/fiat_repository.dart
🧰 Additional context used
🪛 YAMLlint (1.35.1)
.github/actions/generate-assets/action.yml

[error] 65-65: trailing spaces

(trailing-spaces)


[error] 66-66: trailing spaces

(trailing-spaces)


[error] 80-80: trailing spaces

(trailing-spaces)

🪛 GitHub Actions: takenagain is running unit tests on PR 🚀
lib/views/fiat/fiat_inputs.dart

[error] 208-208: Error: No named parameter with the name 'showBalanceIndicator'.


[error] 208-208: Error: Compilation failed.

🪛 GitHub Actions: takenagain is validating code guidelines 🚀
lib/views/fiat/fiat_inputs.dart

[error] 208-208: Error: No named parameter with the name 'showBalanceIndicator'.

🪛 GitHub Actions: takenagain is deploying a preview build to Firebase Hosting 🚀
lib/views/fiat/fiat_inputs.dart

[error] 208-208: No named parameter with the name 'showBalanceIndicator'.


[error] 1-1: Compilation failed. Flutter build exited with status 1.

🪛 GitHub Actions: takenagain is running UI tests on PR 🚀
lib/views/fiat/fiat_inputs.dart

[error] 208-208: Error: No named parameter with the name 'showBalanceIndicator'.


[error] 208-208: Error: Compilation failed.

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build Desktop (windows)
  • GitHub Check: Build Mobile (iOS)
🔇 Additional comments (80)
.github/actions/generate-assets/action.yml (2)

53-63: Improved Trello parameter handling logic

The new conditional logic ensures that Trello parameters are only added to the build command when all required inputs are available. This is a more robust approach that prevents partial configuration issues.


68-80: Enhanced build process with better output handling and error reporting

The changes improve the build process by:

  1. Capturing and displaying output from flutter pub get
  2. Making the build command output visible (rather than redirecting to /dev/null)
  3. Properly capturing and handling the exit status

These changes will make debugging failures much easier.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 80-80: trailing spaces

(trailing-spaces)

lib/app_config/app_config.dart (1)

11-11: LGTM: Added scaling constant for high-precision calculations

The new constant scaleOnInfinitePrecision with a value of 20 is appropriate for handling cryptocurrencies like ETH that have high decimal precision (18 decimal places). This will help improve accuracy in financial calculations throughout the app.

lib/bloc/fiat/models/fiat_transaction_fee.dart (1)

1-1: Improved precision by replacing double with Decimal for monetary values

Converting from double to Decimal for the amount field is an excellent change for financial calculations. Floating-point types like double can introduce precision errors that are unacceptable when dealing with currency amounts.

The implementation includes proper JSON serialization and deserialization for the Decimal type.

Also applies to: 31-33, 35-35, 39-39

lib/bloc/fiat/ramp/models/onramp_purchase_quotation/ramp_payment_method_name.dart (1)

1-19: LGTM: Well-structured payment method enum with proper string conversion

The new RampPaymentMethodName enum is well-designed with:

  1. Clear value definitions for various payment methods
  2. A proper string value association for each method
  3. A robust fromString method with appropriate error handling for unknown values

This approach provides type safety when working with payment methods throughout the application.

lib/bloc/fiat/ramp/models/onramp_purchase_quotation/ramp_quote_result.dart (1)

1-32: Well-structured model implementation

This class is well-designed with:

  • Proper immutability through final fields
  • Clear factory method for JSON parsing
  • Helper method for accessing payment methods
  • Strong typing for financial data

The code follows good Dart practices and the structure aligns well with the apparent domain model.

lib/shared/utils/utils.dart (3)

12-12: Good addition of app_config import

Adding the app configuration import allows for referencing global configuration values rather than hardcoded constants, improving maintainability.


70-72: Improved precision handling with configurable scale

Replacing the hardcoded value 24 with the configurable scaleOnInfinitePrecision variable enhances flexibility and consistency across the application.


74-76: Consistent use of configurable scale

This change ensures that the same precision scale is used consistently throughout the function, improving reliability in financial calculations.

lib/bloc/fiat/ramp/models/onramp_purchase_quotation/ramp_quote_result_for_payment_method.dart (1)

1-32: Well-designed financial model with appropriate precision

This class makes good use of the Decimal type for financial values, which is crucial for accuracy in monetary calculations. The implementation includes:

  • Appropriate immutability with final fields
  • Clear factory method for JSON parsing
  • Proper null handling for optional fields

Using Decimal instead of double for monetary values prevents floating-point precision issues that could lead to incorrect financial calculations.

lib/views/fiat/fiat_payment_method_card.dart (2)

31-32: Improved type safety with Decimal

The change from nullable double to Decimal improves type safety and precision. The comparison with Decimal.zero is more explicit and safer than checking for null.


88-88: Enhanced numeric precision for percentage display

Using Decimal.fromInt(100) for multiplication ensures the calculation remains within the Decimal type system, maintaining precision throughout the entire calculation chain before converting to string.

lib/shared/utils/formatters.dart (2)

8-8: Import for config usage – looks good.

No issues found with this import statement for app_config.dart.


183-183: Check numeric edge cases when formatting amounts.

Using toDecimal(scaleOnInfinitePrecision: scaleOnInfinitePrecision) plus toStringAsFixed(8) can cause rounding or truncation. Ensure large or very small Rational values behave as expected.

Do you want to run tests with boundary values to confirm the correct behavior?

lib/bloc/fiat/base_fiat_provider.dart (7)

5-5: Logger import – no immediate concerns.

This import is appropriate to facilitate structured logging.


47-47: Static logger initialization – good addition.

No immediate issues. This allows structured error and warning messages for the class.


51-51: @protected usage is suitable here.

This annotation cleanly indicates internal usage. No concerns.


100-101: Potential risk of logging sensitive data.

Returning Future.error(json.decode(response.body)) after logging a warning might leak sensitive info if the response payload includes user data. Confirm no PII is present in the response.


103-104: Verbose logging of error & stack trace.

Double-check that logging stack traces never reveals sensitive details. Otherwise, this approach is standard for diagnosing network issues.


20-20:

✅ Verification successful

Changed return type to more specialized list.

Replacing Future<List<ICurrency>> with Future<List<FiatCurrency>> clarifies the expected data. Verify all callers have been updated accordingly.


🏁 Script executed:

#!/bin/bash
# Description: Search for references to getFiatList to ensure correct usage updates
rg -A 3 'getFiatList'

Length of output: 1715


Verified return type update for getFiatList across all consumers.

  • The change from Future<List<ICurrency>> to Future<List<FiatCurrency>> in lib/bloc/fiat/base_fiat_provider.dart has been consistently applied.
  • References in lib/bloc/fiat/fiat_repository.dart, lib/bloc/fiat/ramp/ramp_fiat_provider.dart, and lib/bloc/fiat/banxa_fiat_provider.dart now correctly reflect the specialized return type.
  • All callers, including those in lib/bloc/fiat/fiat_onramp_form/fiat_form_bloc.dart, have been updated accordingly.

22-22:

✅ Verification successful

Changed return type to more specialized list.

Similar to getFiatList, confirm that references to getCoinList handle the new CryptoCurrency type properly.


🏁 Script executed:

#!/bin/bash
# Description: Search for references to getCoinList to ensure correct usage updates
rg -A 3 'getCoinList'

Length of output: 5876


Changed return type to a more specialized list.

After verifying across the codebase, all found references to getCoinList—including those in test cases and provider implementations—appear to correctly handle the new CryptoCurrency type (similar to how getFiatList is used). No further issues were detected, so please ensure that dependent modules maintain this behavior during ongoing development.

lib/bloc/fiat/models/fiat_price_info.dart (5)

1-1: Good move importing Decimal for financial calculations.

Adding the Decimal package is a significant improvement for handling financial values with the precision they require.


13-19: Great use of a static zero constant.

Using a static zero constant with proper Decimal.zero initialization provides a reusable empty state instance, which improves code consistency and reduces object creation.


23-28: Proper defensive parsing of JSON values.

The conversions from JSON now properly handle potential null values and use Decimal.parse for accurate financial representation instead of floating-point values.


32-36: Improved type safety for financial fields.

The transition from double to Decimal for monetary values will prevent floating-point precision issues that are especially problematic in financial applications.


57-61: Proper serialization of Decimal values.

Converting Decimal values to strings before adding them to JSON is the correct approach. This ensures precise values are preserved during serialization.

lib/bloc/fiat/models/fiat_payment_method.dart (6)

2-2: Appropriate import for financial calculations.

Adding the Decimal package is consistent with the pattern established in other financial classes.


20-29: Good refactoring to use a static field instead of constructor.

Replacing the .none() constructor with a static field improves code clarity and performance by avoiding repeated object instantiation.


54-55: Proper parsing of relative percent as Decimal.

Using Decimal.parse for the relative percent ensures consistency with the precision improvements throughout the codebase.


66-66: Improved type safety for relative percent.

Changing from double to Decimal is consistent with the application's approach to handling financial values.


102-102: Correct serialization of Decimal values.

The toString() method ensures proper representation of the Decimal value in JSON format.


122-153: Well-structured default payment methods with Decimal values.

The default payment methods now properly use FiatPriceInfo.zero and explicit Decimal values, maintaining the improved precision throughout the codebase.

lib/bloc/fiat/ramp/models/ramp_asset_info.dart (2)

3-19: Well-defined model class with appropriate fields.

The RampAssetInfo class has a comprehensive set of fields to represent an asset, with proper typing including Decimal for financial values.


38-50: Good validation methods for purchase amounts.

The hasValidMinPurchaseAmount and hasValidMaxPurchaseAmount methods provide clear validation logic with proper handling of the special case where -1 indicates no limit.

lib/bloc/coins_bloc/coins_bloc.dart (5)

7-10: Appropriate imports for additional utilities.

The added imports provide access to necessary utility functions and extensions that support the modified implementation.


151-157: Good addition of coin state synchronization.

This additional block ensures that coin states are properly synchronized after balance updates, improving the reliability of the displayed coin information.


541-541: More efficient asset retrieval directly from SDK.

Retrieving activated assets directly from the SDK with getActivatedAssets() is more efficient than going through the repository.


544-546: Improved coin lookup using firstWhereOrNull.

The use of firstWhereOrNull with a direct predicate is cleaner and more efficient than previous approaches.


563-567: Good handling of API-enabled but GUI-disabled coins.

This loop ensures that any coins enabled on the API side but not on the GUI side are properly enabled, maintaining synchronization between the two.

lib/views/fiat/fiat_form.dart (7)

37-44: Ensure clean-up or subscription management if needed.
Although you removed dispose(), confirm that there are no ongoing streams or listeners that need unsubscribing to prevent any potential memory leaks.

Are there any active listeners or streams that might remain subscribed after this widget is disposed?


61-70: Check for potential race conditions with coin bootstrap.
You correctly handle the isLoginCoinBootstrapFinished flag. However, confirm there aren’t edge cases where slow fetching of walletCoins might conflict with subsequent events.


155-156: Method rename aligns well with private usage.
Renaming completeOrder to _completeOrder clarifies scoping. The dispatch to FiatFormSubmitted appears correct.


170-171: Tab index update logic looks solid.
Using FiatFormModeUpdated.fromTabIndex is a clear pattern, ensuring the correct form mode is derived from the selected tab.


179-181: Double-check handling for in-progress orders on logout.
When the user logs out mid-transaction, confirm that partial orders are canceled or saved appropriately.

Could you verify if partial orders remain open or if they’re cleaned up automatically on the server?


224-238: Ensure only one dialog or snackbar at a time.
Multiple state updates (e.g., from submitted to failed) might trigger repeated dialogs or snackbars. Confirm that transitions happen in sequence without stacking feedback.


241-278: Dialog-based status feedback is straightforward.
Your approach to using an AlertDialog is user-friendly. If you need more customization or concurrent flows later, consider a more dynamic overlay or dedicated status screen.

lib/bloc/fiat/models/fiat_buy_order_info.dart (4)

24-32: Good transition to Decimal.zero for precision.
This helps avoid floating-point inaccuracies and ensures consistent monetary calculations.


42-50: Constructors handle default values consistently.
Initializing fiatAmount with Decimal.zero in fromCheckoutUrl is a sensible default.


92-92: Accurate representation of fiatAmount with Decimal.
Switching from double to Decimal ensures higher precision in financial operations.


149-149: Copy method signature aligns with Decimal usage.
This ensures consistency across the entire class.

lib/bloc/fiat/fiat_onramp_form/fiat_form_state.dart (8)

5-8: Informative doc comments.
The improved documentation clarifies the purpose of FiatFormState.


27-46: Initial state defaults are well-chosen.
Setting BTC as a default asset and USD as the default fiat currency is fine. Confirm that these defaults align with UX expectations.


79-84: Typed fiatList and coinList enhance clarity.
Switching from Iterable<ICurrency> to Iterable<FiatCurrency> / Iterable<CryptoCurrency> eliminates ambiguity in the codebase.


97-101: Decimal-based min/max amounts.
Using Decimal for boundary limits mitigates rounding errors. Consider verifying string conversions for large amounts.


103-108: isLoading logic might be too simplistic.
Relying on fiatList.length < 2 || coinList.length < 2 could incorrectly label states with fewer supported networks as “loading.” Evaluate if a single currency scenario is valid.


117-132: copyWith respects new properties.
All newly introduced state fields are included in copyWith, preserving consistency.


155-157: Expanded validation inputs.
Including selectedAsset in inputs clarifies form validation. Confirm you are testing these validations thoroughly.


162-175: Props array updated to match new fields.
Ensures Equatable tracks the updated properties in equality checks.

lib/model/forms/fiat/fiat_amount_input.dart (2)

21-29: Refactor ensures precise currency handling
Switching from double to Decimal in the constructors and introducing valueAsDecimal improves numeric precision for currency amounts. This is a solid approach given floating-point inaccuracies.


33-37: Consider clarifying negative or zero-edge cases
The validator checks for empty input and invalid format but does not explicitly handle negative or zero amounts. If negative amounts are disallowed, consider adding an explicit check to ensure clarity.

Do you want me to verify whether negative or zero amounts are permissible elsewhere in the codebase, or add a check here?

lib/views/fiat/fiat_inputs.dart (2)

19-34: Constructor and new parameters
The updated parameters (selectedAsset, selectedAssetAddress, and selectedAssetPubkeys) align with the project’s shift toward typed asset handling. Verify that future usage consistently references these new fields to avoid confusion with any legacy naming.


218-239: Generified asset selection
Splitting the selection dialog into "fiat" vs. "coin" is clear. The generic parameter <C extends ICurrency> fosters reusability. Ensure that UI labels and placeholders reflect the correct asset type (“Select Fiat” vs. “Select Coin”).

lib/bloc/fiat/fiat_onramp_form/fiat_form_bloc.dart (2)

156-205: Ensure address presence before submit
Form submission references state.selectedAssetAddress!.address directly. While there's a prior check, consider an early return or assertion if selectedAssetAddress is null. This guards against unforeseen races or uninitialized states.


304-322: Reloading pubkeys post-authentication
Refreshing selectedAssetAddress inside _onWalletAuthenticated is a clean approach. Confirm if any concurrent event calls _onCoinSelected again during the same timeframe, which might override or conflict with updated pubkeys.

lib/bloc/fiat/fiat_onramp_form/fiat_form_event.dart (16)

3-3: Good addition of class documentation.

The newly added documentation clearly describes the purpose of the base class, improving code readability and maintainability.


11-14: LGTM: Well-designed new event for form initialization.

The addition of FiatFormStarted event with appropriate documentation follows the BLoC pattern best practices and provides a clear entry point for form initialization.


16-17: Consistent naming convention applied.

The renaming to FiatFormOnRampPaymentStatusMessageReceived aligns with the new naming pattern and improves code consistency.


26-30: Improved type safety with specialized types.

The class was renamed from SelectedFiatCurrencyChanged to FiatFormFiatSelected for consistency, and now uses a specific FiatCurrency type instead of a more generic one, enhancing type safety.


36-40: Good renaming and type specification.

Similar to the fiat currency selection, this event has been renamed from SelectedCoinChanged to follow the consistent naming pattern, and uses a specific CryptoCurrency type.


46-48: Clear naming improvement.

Renaming from FiatAmountChanged to FiatFormAmountUpdated follows the established pattern and better describes the action.


56-58: Consistent event naming implemented.

Renamed from PaymentMethodSelected to follow the FiatForm[Action] pattern, improving code consistency.


66-69: Streamlined form submission event.

Renamed from FormSubmissionRequested to FiatFormSubmitted, which is more concise while maintaining clarity.


71-76: Well-structured mode update event with helpful factory constructor.

The named constructor fromTabIndex is a nice addition that encapsulates the conversion logic from UI tab index to domain model.


85-88: Good addition for state management.

The new FiatFormPaymentStatusCleared event provides a clear way to reset payment status, which helps manage the UI state properly.


90-93: Important new event for authentication flow.

Adding FiatFormWalletAuthenticated helps track the authentication state, which is crucial for secure transactions.


95-98: Useful event for resetting account state.

The FiatFormAccountCleared event enables proper cleanup of account data when needed.


100-111: Well-designed refresh mechanism.

The new FiatFormRefreshed event with the forceRefresh flag provides flexibility in how data is refreshed, allowing for cache optimization.


113-116: Good addition for currency data fetching.

The FiatFormCurrenciesFetched event clearly separates the concern of fetching available currencies from other form actions.


118-121: Important addition for transaction monitoring.

The FiatFormOrderStatusWatchStarted event enables tracking of transaction status, which is essential for providing feedback to users.


123-131: Key enhancement supporting HD wallet address selection.

The FiatFormCoinAddressSelected event using the PubkeyInfo type enables selection of specific addresses from HD wallets, directly addressing the PR objective of supporting HD wallet address selection.

@takenagain
Copy link
Collaborator Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 25, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@github-actions
Copy link

github-actions bot commented Mar 25, 2025

Visit the preview URL for this PR (updated for commit 46edfb3):

https://walletrc--pull-2570-merge-8h6nd0n7.web.app

(expires Mon, 05 May 2025 06:37:52 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: f66a4ff03faa546f12f0ae5a841bd9eff2714dcc

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

♻️ Duplicate comments (1)
lib/views/fiat/fiat_inputs.dart (1)

199-213: ⚠️ Potential issue

The showBalanceIndicator parameter issue remains.

The showBalanceIndicator parameter at line 209 was previously flagged as causing build errors. Although you mentioned it will be added in a future SDK update, it's still present in the code which could continue to cause build failures.

-                  showBalanceIndicator: false,
+                  // showBalanceIndicator: false, // Will be added in future SDK update
🧹 Nitpick comments (3)
lib/bloc/fiat/ramp/models/onramp_purchase_quotation/ramp_quote_result_for_payment_method.dart (1)

59-68: Consider unifying decimal parsing approach for consistency

While the implementation is generally good, there's an inconsistency in how decimal values are parsed. cryptoAmount uses direct parsing from a string (line 61), while other decimal fields use .toString() first (lines 62-67). This could cause issues if the API changes its response format.

  return RampQuoteResultForPaymentMethod(
    fiatCurrency: json['fiatCurrency'] as String,
-   cryptoAmount: Decimal.parse(json['cryptoAmount'] as String),
+   cryptoAmount: Decimal.parse(json['cryptoAmount'].toString()),
    fiatValue: Decimal.parse(json['fiatValue'].toString()),
    baseRampFee: Decimal.parse(json['baseRampFee'].toString()),
    appliedFee: Decimal.parse(json['appliedFee'].toString()),
    hostFeeCut: json['hostFeeCut'] != null
        ? Decimal.parse(json['hostFeeCut'].toString())
        : null,
  );
lib/model/forms/fiat/fiat_amount_input.dart (1)

57-58: TODO for further refactoring

Consider moving the parseLocaleAwareDecimal function into the SDK or as an extension method on the Decimal class as suggested by the TODO comment. This would make the functionality more reusable across the application.

lib/bloc/fiat/fiat_onramp_form/fiat_form_bloc.dart (1)

214-270: Enhanced refresh form logic with better error handling.

The updated refresh form logic properly handles state transitions and has improved error handling with structured logging.

However, there might be an opportunity to optimize the state emissions:

Consider potentially combining the state updates at lines 225-228 and line 240 to reduce UI rebuilds during the refresh operation.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bac8103 and be26875.

⛔ Files ignored due to path filters (2)
  • packages/komodo_ui_kit/pubspec.lock is excluded by !**/*.lock
  • pubspec.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • .github/actions/generate-assets/action.yml (1 hunks)
  • lib/bloc/fiat/fiat_onramp_form/fiat_form_bloc.dart (15 hunks)
  • lib/bloc/fiat/fiat_onramp_form/fiat_form_state.dart (5 hunks)
  • lib/bloc/fiat/ramp/models/host_assets_config.dart (1 hunks)
  • lib/bloc/fiat/ramp/models/onramp_purchase_quotation/ramp_quote_result.dart (1 hunks)
  • lib/bloc/fiat/ramp/models/onramp_purchase_quotation/ramp_quote_result_for_payment_method.dart (1 hunks)
  • lib/bloc/fiat/ramp/models/ramp_asset_info.dart (1 hunks)
  • lib/model/forms/fiat/currency_input.dart (2 hunks)
  • lib/model/forms/fiat/fiat_amount_input.dart (3 hunks)
  • lib/views/fiat/fiat_form.dart (7 hunks)
  • lib/views/fiat/fiat_inputs.dart (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .github/actions/generate-assets/action.yml
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build Desktop (windows)
  • GitHub Check: Build Mobile (Android)
  • GitHub Check: Build Mobile (iOS)
🔇 Additional comments (48)
lib/bloc/fiat/ramp/models/onramp_purchase_quotation/ramp_quote_result.dart (1)

1-65: Well-structured model class with proper validation and error handling

The implementation of RampQuoteResult follows good practices for JSON parsing and validation. The class appropriately checks for required fields, validates types, and provides clear error messages when validation fails.

lib/bloc/fiat/ramp/models/ramp_asset_info.dart (2)

76-86: LGTM: Clear validation methods for purchase amounts

The methods for validating minimum and maximum purchase amounts are well-implemented and handle the special value of -1 correctly to indicate no limit.


94-149: Robust JSON parsing with good validation

The fromJson factory method properly validates required fields and handles type checking appropriately. The use of Decimal.tryParse for optional fields is a good approach to gracefully handle parsing errors.

lib/bloc/fiat/ramp/models/host_assets_config.dart (2)

48-80: Well-structured JSON parsing with good validation

The fromJson factory method makes good use of helper methods to validate required fields and parse decimal values. The code properly validates that the 'assets' field is a list and that each asset is a valid JSON object.


82-103: Effective helper methods for validation and parsing

The private helper methods _validateRequiredField and _parseDecimal are well-implemented and provide clear error messages. The consistent use of these methods throughout the class reduces code duplication and improves maintainability.

lib/model/forms/fiat/currency_input.dart (3)

14-15: Good use of generics for type safety improvements

Converting the class to use a generic type parameter (T extends ICurrency) is a solid improvement that enhances type safety. This allows for more specific typing in consumer code, reducing the risk of runtime type errors when working with different currency types.


20-21: Type parameter correctly applied to validator method

The validator method now correctly uses the generic type parameter, maintaining type safety throughout the validation process.


33-33: Consistent generic type usage

The isCurrencySupported method correctly adopts the generic type parameter, completing the class's conversion to a proper generic implementation.

lib/bloc/fiat/fiat_onramp_form/fiat_form_state.dart (10)

12-13: Renamed property improves semantic clarity

Changing from selectedCoin to selectedAsset is a good semantic improvement that better represents the concept being modeled, especially when working with multiple types of assets.


23-24: Good addition of asset-specific properties

Adding selectedAssetAddress and selectedCoinPubkeys properties provides better structure for managing HD wallet addresses, which appears to be the main focus of this PR.


36-37: Initial state properly handles new fields

The initial state constructor correctly initializes the new properties to null, maintaining the expected initial state behavior.


48-50: Improved type safety with generic currency inputs

The code now uses the generic CurrencyInput<FiatCurrency> and CurrencyInput<CryptoCurrency> types instead of the less specific CurrencyInput. This leverages the generic improvements made in currency_input.dart and improves type safety throughout the app.

Also applies to: 51-52


61-62: HD wallet address selection support added

These properties add the necessary state to support HD wallet address selection, which is essential for the feature described in the PR title.

Also applies to: 64-65


80-81: Type specificity improves compiler checks

Using specific currency types (FiatCurrency and CryptoCurrency) instead of the generic ICurrency improves type safety and provides better IDE support for developers.

Also applies to: 83-84


98-99: Using Decimal type for currency amounts

Changing from double? to Decimal? for currency-related values is a good practice that avoids floating-point precision issues common in financial applications.

Also applies to: 101-102


112-113: Improved validation logic

The updated canSubmit logic now checks for the presence of selectedAssetAddress instead of a previously removed property, ensuring proper validation of the user's selection.


118-120: Updated copyWith method maintains immutability pattern

The copyWith method has been properly updated to include all new properties, maintaining the immutability pattern that's important for state management in Flutter.

Also applies to: 127-129, 131-132


148-149: Proper inclusion in props list ensures equality comparisons work

The new properties have been correctly added to the props list, ensuring that equality comparisons (used by the Bloc library) work correctly.

lib/views/fiat/fiat_form.dart (10)

37-46: Simplified initialization with event-driven approach

The initialization logic has been streamlined to dispatch a refresh event rather than setting up multiple listeners. This is a cleaner approach that centralizes state management in the Bloc.


63-75: Improved state management with BlocListener and BlocConsumer

Using BlocListener for the CoinsBloc and BlocConsumer for the FiatFormBloc creates a cleaner separation of concerns and more predictable state updates.


99-107: Proper handling of currency and asset selection

The implementation now correctly passes the selected asset address and pubkeys to the FiatInputs widget, addressing the issue mentioned in the PR description about failure to update the address field when changing the coin.


130-131: Renamed method with proper underscore prefix

Renaming completeOrder to _completeOrder follows the convention of marking private methods with an underscore, improving code readability and organization.


158-169: Improved event handling for field changes

The implementation now properly dispatches both the specific field update event and a forced refresh event when values change, ensuring consistent form state.


179-182: Simplified account status handling

The account status change handler now simply dispatches appropriate events to the bloc rather than implementing complex logic, following a cleaner separation of concerns.


233-235: Fixed QR code visibility issue

This implementation addresses the pop-up issue mentioned in the PR description, where the Ramp fiat onramp process was covering the QR code.


247-298: Improved payment status dialog handling

Converting the dialog method to asynchronous and simplifying the implementation provides better user experience by ensuring proper dialog flow and potential animation completion.


50-61: TODO comment provides context for future development

The comprehensive TODO comment provides valuable context for future development related to checkout URL reuse, which is a good practice for maintaining code knowledge.


210-218: Enhanced console message handling

The improved console message handling dispatches events directly to the bloc, maintaining proper separation of concerns and event-driven architecture.

lib/model/forms/fiat/fiat_amount_input.dart (4)

21-27: Improved precision with Decimal type

Changing from double? to Decimal? for currency-related values is an excellent improvement for financial calculations, avoiding the floating-point precision issues that can occur with doubles.


28-29: Better currency value parsing

Replacing valueAsDouble with valueAsDecimal and using the new parseLocaleAwareDecimal function provides more accurate and locale-aware parsing.


37-38: Updated validator with improved parsing

The validator now uses the locale-aware parsing function, ensuring consistent validation regardless of the user's number format preferences.


55-92: Excellent locale-aware decimal parsing implementation

The parseLocaleAwareDecimal function is a comprehensive solution for handling different number formats. It tries multiple parse strategies to accommodate various locale conventions:

  1. Standard format with period as decimal separator
  2. US/UK format with comma thousand separators
  3. European format with periods as thousand separators and commas as decimal separators

This is exactly what was needed to address the previous review comment about potential issues with locale-based comma usage, and the implementation goes beyond the basic suggestion to create a robust solution.

lib/views/fiat/fiat_inputs.dart (7)

3-6: Good use of structured imports.

The addition of Komodo SDK and types modules along with flutter_bloc imports sets the foundation for the upcoming changes and properly organizes the dependency imports.


17-34: Improved parameter types for better type safety.

The refactoring from generic ICurrency to specific FiatCurrency and CryptoCurrency types is a great improvement that enhances type safety and makes the code more maintainable. The new parameters like selectedAssetPubkeys and onSourceAddressChanged properly support the feature to handle HD wallet addresses.

Also applies to: 36-52


75-93: Good migration to Decimal for financial calculations.

Converting from double to Decimal for financial calculations is a best practice as it avoids floating-point precision issues. The updated comparison logic properly handles this type change.


95-105: Type-safe callback implementations.

The methods now correctly accept specific currency types, which matches the function signatures in the class properties and improves type safety throughout the codebase.


134-187: Properly updated widget references.

The UI elements now use the updated property names and types, maintaining consistency with the refactored model.


223-239: Improved type-specific dialog handling.

Good job using separate type-specific method calls for fiat and coin selection dialogs. This improves type safety and makes the code more maintainable.


242-282: Well-implemented generic selection dialog.

The generic implementation using type parameter C extends ICurrency makes the code more flexible while maintaining type safety. This is a good pattern for reusable UI components that need to handle different but related types.

lib/bloc/fiat/fiat_onramp_form/fiat_form_bloc.dart (9)

6-12: Proper imports for enhanced functionality.

The addition of decimal, SDK, types, and logging imports sets up the foundation for the code improvements throughout the file.


27-58: Well-structured event handling setup.

The constructor now correctly uses KomodoDefiSdk instead of CoinsRepo, and event handlers follow a consistent naming convention. The use of appropriate transformer strategies (debounce vs restartable) for different events helps prevent UI jank.


82-107: SDK integration for pubkey management.

Good implementation of the SDK calls to fetch pubkeys for the selected asset. There's proper error handling with structured logging which improves debuggability.


109-136: Improved financial calculations with Decimal.

The migration to use Decimal instead of double for financial calculations is a best practice that avoids floating-point precision issues. The _getAmountInputWithBounds method correctly handles this transition.


305-324: Good wallet authentication handling.

The new method provides proper handling for wallet authentication events and retrieves pubkeys as needed. The error handling and logging are implemented well.


333-347: Well-implemented asset pubkeys update method.

This new helper method properly encapsulates the logic for updating asset pubkeys, making the code more maintainable. The try-catch block with structured logging enhances error handling.


404-432: Improved order status monitoring with structured error handling.

The order status monitoring implementation now has better error handling with proper logging. The use of emit.forEach with onError handler ensures the bloc properly manages failures during streaming operations.


442-452: TODO comment should be addressed.

There's a TODO comment about handling Banxa error responses that hasn't been addressed. This might be an opportunity to improve the user experience by providing more specific error messages.

Is this TODO still relevant? If so, consider creating a task to address it in a future update or implement a solution now.


476-485: Well-implemented address selection handler.

The new method for handling coin address selection properly updates the state with the selected address. This is essential for the HD wallet address selection feature.

remove debouncing on input events, and change refresh form from debounce to restartable to avoid unexpected UI changes to to delayed state changes
@smk762
Copy link
Collaborator

smk762 commented Apr 4, 2025

Can't seem to progress beyond this screen regardless of the address input:
image

I did notice tho that in the "source address" dropdown, only non-segwit BTC addresses are listed - we should list both.

CharlVS

This comment was marked as outdated.

@CharlVS CharlVS self-requested a review April 10, 2025 17:54
@takenagain
Copy link
Collaborator Author

Can't seem to progress beyond this screen regardless of the address input:

@smk762 were you using a local debug build at the time? I could reproduce the issue with BTC when using a debug build, but profile and release builds worked for me. It might be restrictions in the Ramp testing environment specific to BTC.

MATIC and ETH work for testing with "Manual Bank Transfer" in debug builds, although the transactions do not reach completion because they are not the Ramp test network coins. The Ramp test coins are currently being filtered out, so we could look into making them visible in debug/profile modes to simplify testing.

I've added segwit coins to the dropdown in the meantime.

@smk762
Copy link
Collaborator

smk762 commented Apr 11, 2025

Yep, local as per first post in PR ...test/demo/sandbox environments only work for debug builds, so testing needs to be done with a local build rather than preview links, unless testing with real fiat transfers is desired.

Confirmed seeing btc segwit in the list, thanks. Can we please make it the default instead of BTC?

CharlVS and others added 2 commits April 11, 2025 18:37
@smk762
Copy link
Collaborator

smk762 commented Apr 14, 2025

Confirmed BTC-segwit is now the default 🙏

Banxa purchase via credit card successfully submitted 🎉
image
Can we update something to make the bottom button on completion say "Return to Komodo Wallet"? Either way, clicking on this button did nothing. I had to use the X in the modal corner to close it.

I got a payment failed pop up, though after checking email, wallet and bank account, it was actually successful.
image

Unable to complete a "real world" purchase with RAMP, as using AUD for fiat only supports Banxa.

@CharlVS CharlVS added P0 Blocker / critical defect blocked and removed QA Ready for QA Testing labels Apr 16, 2025
Copy link
Collaborator

@CharlVS CharlVS left a comment

Choose a reason for hiding this comment

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

Thank you for your contributions, @takenagain. Please review the Banxa bug as soon as possible, when you are available. There has been a change to the structure of their order status payload in their latest API version, but that shouldn't affect us since the URL should be pegged to a specific version. Please verify that we are using a pegged URL

@CharlVS CharlVS closed this Apr 25, 2025
@CharlVS CharlVS force-pushed the feat/fiat-form-hd-support branch from bc50a96 to 04696c9 Compare April 25, 2025 11:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocked bug Something isn't working P0 Blocker / critical defect

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants