Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix(trading): trading account #16719

Merged
merged 1 commit into from
Feb 4, 2025
Merged

fix(trading): trading account #16719

merged 1 commit into from
Feb 4, 2025

Conversation

adderpositive
Copy link
Contributor

@adderpositive adderpositive commented Jan 30, 2025

Description

Fixed a bad selected (cachec) account in the trading section (Swap, Sell)

Related Issue

Resolve #16701
Waiting for merging - #16681

@adderpositive adderpositive added bug Something isn't working as expected +Invity Related to Invity project labels Jan 30, 2025
@adderpositive adderpositive self-assigned this Jan 30, 2025
@adderpositive adderpositive linked an issue Jan 30, 2025 that may be closed by this pull request
@FreeWall
Copy link
Member

It will work, but I don't think it's the right approach. What if I go from ETH swap form directly to the POL swap form (shouldn't be possible at this time but might be in the future)? This new code won't be called so the account won't reset.

@adderpositive adderpositive force-pushed the refactor/trading-account-state branch from 3ee8821 to 754a984 Compare January 30, 2025 17:32
Copy link

coderabbitai bot commented Jan 30, 2025

Walkthrough

This pull request refactors the tradingMiddleware in packages/suite/src/middlewares/wallet/tradingMiddleware.ts. The changes introduce an import for ACCOUNTS_MODULE_PREFIX and update the destructuring of state properties by including account keys, which are then renamed for clarity. New boolean flags (isRouteChange and isSuiteAccountChanged) are added to streamline the control flow, replacing direct action type checks. The middleware logic now clears the trading account keys for both Sell and Swap sections when an account change is detected and updates the invityAPIKey in response to specific trading account key actions. These modifications aim to reset stale state information when transitioning between accounts or routes, ensuring consistent behavior during trading operations.

Assessment against linked issues

Objective Addressed Explanation
Ensure correct network selection during trading swaps (#16701)
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@adderpositive adderpositive force-pushed the refactor/trading-account-state branch from 754a984 to fd8a7ce Compare January 31, 2025 10:39
@adderpositive
Copy link
Contributor Author

It will work, but I don't think it's the right approach. What if I go from ETH swap form directly to the POL swap form (shouldn't be possible at this time but might be in the future)? This new code won't be called so the account won't reset.

Thanks for the feedback. I have updated the code to make it more resilient. I used ${ACCOUNTS_MODULE_PREFIX}/updateSelectedAccount to check whether selectedAccount (Trezor) is changed.

Copy link
Member

@FreeWall FreeWall left a comment

Choose a reason for hiding this comment

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

still feels a little weird to me, but I have no better fix now

FreeWall

This comment was marked as duplicate.

@adderpositive adderpositive force-pushed the refactor/trading-account-state branch from fd8a7ce to c742054 Compare February 3, 2025 10:14
Base automatically changed from refactor/trading-account-state to develop February 3, 2025 13:42
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
packages/suite/src/middlewares/wallet/tradingMiddleware.ts (1)

192-202: Explicit Logging for Missing Account in Trading Middleware

Our review confirms that the getAccountAccordingToRoute function can return undefined when no matching account is found (e.g., if no account matches the trading account keys). In the current middleware, since invityAPI.createInvityAPIKey is called only when account exists, the absence of explicit logging makes it harder to diagnose missing account scenarios. Adding an explicit warning—as shown in the diff—is a valuable improvement to aid debugging and ensure robustness.

  • The function may return undefined if the account isn’t found in either the sell or exchange case.
  • The middleware silently skips the API key creation when account is falsy.
  • Adding error handling (with a warning and early return) clarifies the flow and eases troubleshooting.
🔗 Analysis chain

Add error handling for undefined account.

The code should handle the case where getAccountAccordingToRoute returns undefined to prevent potential issues.

         if (
             action.type === TRADING_EXCHANGE.SET_TRADING_ACCOUNT_KEY ||
             action.type === TRADING_SELL.SET_TRADING_ACCOUNT_KEY
         ) {
             const account = getAccountAccordingToRoute(newState);
 
-            if (account) {
+            if (!account) {
+                console.warn('No account found when updating invityAPIKey');
+                return action;
+            }
-            }
             invityAPI.createInvityAPIKey(account.descriptor);
         }

Let's verify if this edge case can occur:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if getAccountAccordingToRoute can return undefined

# Search for calls to getAccountAccordingToRoute and check error handling
rg -A 5 "getAccountAccordingToRoute" --type ts

# Search for potential undefined account handling in tests
rg -A 5 "getAccountAccordingToRoute.*undefined" --type ts

Length of output: 1926


Script:

#!/bin/bash
# Display the full implementation of getAccountAccordingToRoute to inspect potential undefined returns.
sed -n '/export const getAccountAccordingToRoute/,/};/p' packages/suite/src/middlewares/wallet/tradingMiddleware.ts

Length of output: 821

🧹 Nitpick comments (1)
packages/suite/src/middlewares/wallet/tradingMiddleware.ts (1)

149-153: Add a comment explaining the clearing of both account keys.

While the logic to clear both sell and exchange account keys is correct, it would be helpful to add a comment explaining why both keys need to be cleared when the suite account changes. This helps future maintainers understand the reasoning.

-        // clear the account key in the Sell and Swap section when the route is not trading
+        // Clear both sell and exchange account keys when the suite account changes to prevent
+        // stale account selections from being used in either trading section
         if (isSuiteAccountChanged && (tradingExchangeAccountKey || tradingSellAccountKey)) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b9dbbed and 4b393d7.

📒 Files selected for processing (1)
  • packages/suite/src/middlewares/wallet/tradingMiddleware.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: run-desktop-tests (@group=wallet, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=settings, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=device-management, trezor-user-env-unix)
  • GitHub Check: Setup and Cache Dependencies
  • GitHub Check: run-desktop-tests (@group=suite, trezor-user-env-unix)
  • GitHub Check: build-web
  • GitHub Check: build-web
  • GitHub Check: Analyze with CodeQL (javascript)
🔇 Additional comments (4)
packages/suite/src/middlewares/wallet/tradingMiddleware.ts (4)

4-4: LGTM!

The import of ACCOUNTS_MODULE_PREFIX is appropriate for detecting account changes.


47-49: LGTM! Clear and descriptive variable naming.

The renamed variables tradingExchangeAccountKey and tradingSellAccountKey improve code readability by clearly indicating their purpose.


51-53: LGTM! Improved action type detection.

The boolean flags improve code readability and make the account change detection more reliable by using ACCOUNTS_MODULE_PREFIX.


160-160: LGTM! Simplified route change condition.

Using the isRouteChange flag improves code readability without changing the underlying logic.

@tomasklim tomasklim merged commit 71166c6 into develop Feb 4, 2025
30 checks passed
@tomasklim tomasklim deleted the fix/trading-account branch February 4, 2025 08:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working as expected +Invity Related to Invity project
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Trading - incorrect network selected when swapping
3 participants