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

Routes error on request pay #413

Merged
merged 6 commits into from
Oct 4, 2024
Merged

Routes error on request pay #413

merged 6 commits into from
Oct 4, 2024

Conversation

jjramirezn
Copy link
Contributor

This PR addresses two issues

  1. The route error was shown alongside with an enabled pay button. Now we properly clean the error message when we "recover" from an error
  2. The routes error we were experiencing in the first place were due to calling squid with bad params (specifically we used the decimals from the previous token to calculate the amount of the current token). This was due to a race condition between the token selector and the effect that calls squid, they both depending on the selected token changing so they executed alongside. Now the effect depends on "selectedTokenData" and not the selected address, selectedTokenData is modified by the selector after fetching the price and decimal data

From the request pay init, we need to now the token address, chain and
decimals in order to calculate the squid router fee. Previously we
depended on those three data points separately. This caused that when
the user seleted a token, we tried to calculate the route for that token
but with the decimals from the previous one (the effect tasked with
cleaning this also depends on the change of selected token, so they both
executed at the same time).

In reality, from the pay we depend on the whole token data and only care
when it updates completely. This refactor reflects that and avoid
calling squid with bad data.

Refs:  #102
Copy link

vercel bot commented Oct 4, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
peanut-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 4, 2024 2:21pm

Copy link
Contributor

coderabbitai bot commented Oct 4, 2024

Warning

Rate limit exceeded

@jjramirezn has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 1 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between 5487afc and ad2ef43.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces significant changes to the InitialView component and the tokenSelectorContext. The InitialView component now utilizes a single selectedTokenData object to manage token address and chain ID, simplifying the logic for transaction fee estimation and user balance checks. The tokenSelectorContext has been updated to include a new ITokenData type and to streamline state management by removing unnecessary variables. These modifications enhance the clarity and efficiency of token-related operations within the application.

Changes

File Path Change Summary
src/components/Request/Pay/Views/Initial.view.tsx Replaced selectedChainID and selectedTokenAddress with selectedTokenData. Updated transaction fee estimation logic and handleOnNext function to utilize selectedTokenData. Simplified useEffect dependencies. Removed selectedTokenDecimals and isTokenPriceFetchingComplete.
src/context/tokenSelector.context.tsx Introduced ITokenData type. Updated context initial state to include selectedTokenData. Removed isTokenPriceFetchingComplete. Adjusted fetchAndSetTokenPrice logic to populate selectedTokenData based on fetched data.

Possibly related PRs

Suggested labels

Being worked on

Suggested reviewers

  • Hugo0

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

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: 5

🧹 Outside diff range and nitpick comments (3)
src/context/tokenSelector.context.tsx (1)

Line range hint 61-126: Update effect dependency array to selectedTokenData to prevent race conditions

As per the PR objectives, to resolve the race condition between the token selector and the effect that calls squid, the useEffect hook should depend on selectedTokenData instead of selectedTokenAddress and selectedChainID. This ensures the effect runs only after selectedTokenData is fully updated, preventing calls with incomplete or incorrect parameters.

Apply this diff to update the dependency array:

 useEffect(() => {
     let isCurrent = true

     async function fetchAndSetTokenPrice(tokenAddress: string, chainId: string) {
         // Function implementation
     }

- }, [selectedTokenAddress, selectedChainID, isConnected])
+ }, [selectedTokenData, isConnected])
src/components/Request/Pay/Views/Initial.view.tsx (2)

34-34: Consider consolidating 'setSelectedChainID' and 'setSelectedTokenAddress' into 'setSelectedTokenData'.

Since selectedTokenData now encapsulates both the chain ID and token address, you might simplify state management by using a single setSelectedTokenData function instead of separate setSelectedChainID and setSelectedTokenAddress functions. This change would enhance consistency and reduce potential state mismatches.


Line range hint 146-185: Refactor 'handleOnNext' to reduce code duplication.

In the handleOnNext function, the code within the if and else branches (lines 146-185) is largely similar, with only a few differences in variables and function calls. This duplication can make the code harder to maintain and increase the risk of bugs. Consider abstracting the common logic into a separate function or adjusting your code structure to eliminate duplication.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2dc9a21 and 29e02ca.

📒 Files selected for processing (2)
  • src/components/Request/Pay/Views/Initial.view.tsx (7 hunks)
  • src/context/tokenSelector.context.tsx (6 hunks)
🧰 Additional context used
📓 Learnings (1)
src/context/tokenSelector.context.tsx (1)
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#404
File: src/context/tokenSelector.context.tsx:121-121
Timestamp: 2024-10-03T09:57:43.885Z
Learning: In `TokenContextProvider` within `tokenSelector.context.tsx`, when token data is loaded from preferences, it's acceptable to set `isTokenPriceFetchingComplete` to `true` because the token data is already available.
🔇 Additional comments (7)
src/context/tokenSelector.context.tsx (7)

26-26: Addition of selectedTokenData to context

Including selectedTokenData in the context aligns with the PR objectives to prevent race conditions and is implemented correctly.


29-34: Definition of ITokenData type

The ITokenData type is properly defined with all the necessary fields: tokenAddress, chainId, decimals, and price.


48-48: Initialization of selectedTokenData state variable

The state variable selectedTokenData is correctly initialized using useState with an initial value of undefined.


76-79: Resetting token data for unsupported chains

Properly resetting selectedTokenData and related variables when the chain is unsupported ensures consistency in the application state.


89-94: Setting selectedTokenData after successful token price fetch

selectedTokenData is correctly populated with the fetched token information, which helps in preventing race conditions by ensuring all necessary token data is available together.


101-104: Resetting token data on token price fetch failure

Appropriate resetting of selectedTokenData and related variables when the token price fetch fails maintains the integrity of the application state.


113-116: Resetting token data when user disconnects

Properly resets selectedTokenData and other related state variables when the user is not connected, ensuring that stale data is not used.

src/context/tokenSelector.context.tsx Show resolved Hide resolved
src/components/Request/Pay/Views/Initial.view.tsx Outdated Show resolved Hide resolved
src/components/Request/Pay/Views/Initial.view.tsx Outdated Show resolved Hide resolved
src/components/Request/Pay/Views/Initial.view.tsx Outdated Show resolved Hide resolved
src/components/Request/Pay/Views/Initial.view.tsx Outdated Show resolved Hide resolved
src/components/Request/Pay/Views/Initial.view.tsx Outdated Show resolved Hide resolved
src/components/Request/Pay/Views/Initial.view.tsx Outdated Show resolved Hide resolved
src/components/Request/Pay/Views/Initial.view.tsx Outdated Show resolved Hide resolved
src/context/tokenSelector.context.tsx Show resolved Hide resolved
src/components/Request/Pay/Views/Initial.view.tsx Outdated Show resolved Hide resolved
Copy link
Contributor

@Hugo0 Hugo0 left a comment

Choose a reason for hiding this comment

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

TODO: pls make sure to run prettier with the settings in prettier.config.js - you can set it up in vscode/cursor to auto run on every save

e.g. here the formatting should be 4 spaces, not 2
image

just so we all use the same formatting

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
src/components/Request/Pay/Views/Initial.view.tsx (2)

49-64: Improved error handling and consistency in createXChainUnsignedTx

The addition of the selectedTokenData check improves error handling, and the use of selectedTokenData properties is consistent with the earlier state management changes. However, there's a minor improvement opportunity:

Consider removing the non-null assertion (!) on line 56 and subsequent lines, as it's redundant given the check on line 51:

- fromToken: selectedTokenData!.tokenAddress,
+ fromToken: selectedTokenData.tokenAddress,

Apply this change to all occurrences of selectedTokenData! in this function.


Line range hint 73-116: Improved cross-chain handling in useEffect

The changes in the useEffect hook enhance the handling of cross-chain scenarios and align well with the new state management approach. The dependency update on line 113 is correct and consistent.

Consider removing the redundant condition on line 85:

- if (Number(feeEstimation) > 0) {
-     setErrorState({ showError: false, errorMessage: '' })
      setIsFeeEstimationError(false)
      setTxFee(Number(feeEstimation).toFixed(2))
      setLinkState(RequestStatus.CLAIM)
- } else {
-     setErrorState({ showError: true, errorMessage: ERR_NO_ROUTE })
-     setIsFeeEstimationError(true)
-     setTxFee('0')
-     setLinkState(RequestStatus.NOT_FOUND)
- }

This condition is always true at this point because of the check on line 84, so the else block is never reached.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7f1d42b and 5487afc.

📒 Files selected for processing (1)
  • src/components/Request/Pay/Views/Initial.view.tsx (7 hunks)
🧰 Additional context used
📓 Learnings (2)
📓 Common learnings
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#413
File: src/context/tokenSelector.context.tsx:118-123
Timestamp: 2024-10-04T13:40:16.067Z
Learning: In the `TokenContextProvider` component within `src/context/tokenSelector.context.tsx`, in the TypeScript React application, when data changes and before calling `fetchAndSetTokenPrice`, it is necessary to reset `selectedTokenData`, `selectedTokenPrice`, `selectedTokenDecimals`, and `inputDenomination` to discard stale data.
src/components/Request/Pay/Views/Initial.view.tsx (1)
Learnt from: Hugo0
PR: peanutprotocol/peanut-ui#413
File: src/components/Request/Pay/Views/Initial.view.tsx:71-72
Timestamp: 2024-10-04T13:10:49.199Z
Learning: In `src/components/Request/Pay/Views/Initial.view.tsx`, it's acceptable to use the `!` operator in TypeScript to assert that `selectedTokenData` is not `null` or `undefined`, and potential runtime errors from accessing its properties without checks can be disregarded.
🔇 Additional comments (2)
src/components/Request/Pay/Views/Initial.view.tsx (2)

34-37: Great simplification of state management!

The use of selectedTokenData instead of separate selectedChainID and selectedTokenAddress variables is a good improvement. This consolidation reduces the chances of state inconsistency and simplifies the component's logic.


145-148: Improved scenario handling in handleOnNext and consistent UI updates

The changes in the handleOnNext function enhance the handling of different scenarios (cross-chain and non-cross-chain) and align well with the new state management approach. The updated network switching logic is correct and consistent.

The JSX changes for displaying network costs accurately reflect the updated logic, providing a better user experience by showing the appropriate cost based on whether it's a cross-chain transaction or not.

These improvements contribute to a more robust and user-friendly component.

Also applies to: 181-182, 326-329

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants