-
Notifications
You must be signed in to change notification settings - Fork 6
fix: disable button when user has insufficient native balance #80
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
Conversation
## Walkthrough
The changes involve updates to the `TokenAndAmount` and `Balance` components, enhancing the logic for fetching and calculating balances. The `TokenAndAmount` component now distinguishes between native and token balances, utilizing `useBalance` and `useReadContract` for retrieval. A new variable, `isNativeTransaction`, has been introduced to streamline the balance fetching process. Additionally, utility functions in `format.ts` and `getFormattedBalance.ts` have been refactored for improved type safety and clarity.
## Changes
| Files | Change Summary |
|--------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx`, `web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx` | Enhanced balance fetching logic using `useReadContract` and `useBalance`, introduced `isNativeTransaction`, and updated rendering logic for accurate balance display. |
| `web/src/utils/format.ts` | Improved type annotations and clarity in `formatValue`, `formatPNK`, and `formatETH` functions, with explicit return statements added. |
| `web/src/utils/getFormattedBalance.ts` | Enhanced type safety by changing `balanceData` from `any` to `bigint`, and updated internal logic for balance formatting. |
| `web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx` | Introduced `ErrorButtonMessage` for displaying insufficient balance messages, streamlined recipient address logic, and improved loading/error state handling for transactions. |
## Possibly related PRs
- #78: The changes in the `TokenAndAmount` component regarding balance retrieval and the introduction of `isNativeTransaction` are related to the modifications in the `Balance` component, which also incorporates `isNativeTransaction` and updates balance retrieval logic using `useReadContract`.
## Suggested reviewers
- kemuru
## Poem
> 🐰 In the meadow of tokens, where balances gleam,
> We fetch with precision, fulfilling the dream.
> With native and tokens, our logic is clear,
> Hopping through changes, we dance without fear.
> So raise up your carrots, let joy be our guide,
> In the world of transactions, together we stride! 🎉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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for kleros-escrow-v2 ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
There was a problem hiding this 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
Outside diff range and nitpick comments (10)
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/AcceptSettlementButton.tsx (1)
19-19: LGTM: Button disabled state updated correctly.The changes effectively implement the PR objective. The button is now disabled when the user has insufficient native balance, in addition to the existing condition of an ongoing transaction.
A minor suggestion for improved readability:
Consider extracting the disabled condition into a separate variable for better clarity:
+ const isButtonDisabled = isSending || !hasSufficientNativeBalance; return ( <Button isLoading={isSending} - disabled={isSending || !hasSufficientNativeBalance} + disabled={isButtonDisabled} text="Accept" onClick={handleAcceptSettlement} /> );This change would make the component's logic more explicit and easier to understand at a glance.
Also applies to: 44-51
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/ExecuteTransactionButton.tsx (3)
19-19: LGTM: New context used correctly. Consider adding a type annotation.The
useNewTransactionContexthook is used correctly to extract thehasSufficientNativeBalancevalue. For consistency with other variables in this component (likeisSending), consider adding a type annotation:const { hasSufficientNativeBalance }: { hasSufficientNativeBalance: boolean } = useNewTransactionContext();This change would make the type explicit and consistent with the component's style.
46-51: LGTM: Button disabled state updated correctly. Consider extracting the disabled condition.The
disabledprop of the Button component has been correctly updated to include the!hasSufficientNativeBalancecondition, which aligns with the PR objective. To improve readability, consider extracting the disabled condition into a separate variable:const isButtonDisabled = isSending || !hasSufficientNativeBalance; return ( <Button isLoading={isSending} disabled={isButtonDisabled} text="Execute Transaction" onClick={handleExecuteTransaction} /> );This change would make the component more readable and easier to maintain.
Implement feedback for insufficient balance
The "Execute Transaction" button correctly disables when the user has insufficient native balance. However, there is no feedback mechanism informing the user why the button is disabled.
Please implement a feedback mechanism, such as a tooltip or helper text, to guide users when the button is disabled due to insufficient balance.
Analysis chain
Line range hint
1-55: Summary: PR objective achieved. Consider verifying UX impact.The changes successfully implement the PR objective of disabling the "Execute Transaction" button when the user has insufficient native balance. The code is well-structured and follows React best practices.
To ensure a smooth user experience:
- Verify that users receive clear feedback about why the button is disabled when they have insufficient balance.
- Consider adding a tooltip or helper text to guide users on how to proceed when the button is disabled due to insufficient balance.
To check for existing feedback mechanisms, run the following script:
This will help identify if there are already feedback mechanisms in place for insufficient balance scenarios.
[/run_scripts]
[/run_scripts]
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Search for feedback mechanisms related to insufficient balance # Test: Look for components or strings related to insufficient balance feedback rg --type typescript --type javascript -i "(insufficient|not enough) (balance|funds)"Length of output: 122
Script:
#!/bin/bash # Description: Search for feedback mechanisms related to insufficient balance # Test: Look for components or strings related to insufficient balance feedback rg -e ts -e tsx -e js -e jsx -i "(insufficient|not enough) (balance|funds)"Length of output: 159
Script:
#!/bin/bash # Description: Search for feedback mechanisms related to insufficient balance # Test: Look for components or strings related to insufficient balance feedback rg -i "(insufficient|not enough) (balance|funds)" --glob "*.{ts,tsx,js,jsx}"Length of output: 205
web/src/pages/MyTransactions/TransactionDetails/WasItFulfilled/Buttons/ClaimFullPaymentButton.tsx (2)
52-52: Approved: Button disabled state updated, consider adding user feedback.The button's disabled state has been correctly updated to include the check for sufficient native balance, which aligns with the PR objective. This change prevents users from attempting to claim full payment when they lack the necessary balance.
Consider adding a tooltip or some visual indication to inform the user why the button might be disabled due to insufficient balance. This would improve the user experience by providing clear feedback. For example:
<Button isLoading={isSending} disabled={isSending || !hasSufficientNativeBalance} text={"No. Claim full payment"} onClick={handleExecuteTransaction} tooltip={!hasSufficientNativeBalance ? "Insufficient balance to claim payment" : undefined} />Note: Ensure that the
Buttoncomponent from@kleros/ui-components-librarysupports atooltipprop. If it doesn't, you might need to wrap theButtonin a container that provides the tooltip functionality.
Line range hint
1-60: Overall assessment: Changes successfully implement the PR objective.The modifications to
ClaimFullPaymentButton.tsxeffectively address the PR objective of disabling the button when the user has insufficient native balance. The code is well-structured, and the new functionality is integrated seamlessly with the existing component.Key points:
- The new context hook is properly imported and used.
- The button's disabled state is correctly updated to include the balance check.
- The changes follow React best practices and maintain code readability.
To further enhance this implementation, consider the following:
- Add error handling for the
hasSufficientNativeBalancefunction, in case it fails to retrieve the balance information.- Implement a re-check mechanism for the native balance, especially if the component remains mounted for extended periods.
- Consider adding a loading state while checking the balance to prevent a flash of enabled state before the balance check completes.
These enhancements would make the component more robust and provide a smoother user experience.
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/TimeOutButton.tsx (2)
23-23: LGTM: New context used correctly.The
hasSufficientNativeBalancevalue is properly destructured from theuseNewTransactionContexthook. This aligns with the PR objective of considering the native balance for button state.Consider adding a comment explaining the purpose of
hasSufficientNativeBalancefor improved code readability:+ // Check if the user has enough native balance to perform the transaction const { hasSufficientNativeBalance } = useNewTransactionContext();
66-73: LGTM: Button disabled state updated correctly.The button's disabled state now correctly considers both the
isSendingstatus and thehasSufficientNativeBalancecondition, which aligns with the PR objective.Consider making the button text more generic or dynamic based on the transaction state. For example:
- text="Claim full payment back" + text={isBuyer ? "Claim full payment back" : "Time out transaction"}This change would make the button text more accurate for both buyer and seller scenarios.
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (1)
81-88: LGTM: Button disabled state updated correctly.The
disabledprop of the Button component has been properly updated to include the check for sufficient native balance, which aligns with the PR objective.Consider adding a tooltip to provide feedback to the user when the button is disabled due to insufficient balance. This would improve the user experience by clearly communicating why the action can't be performed. Here's a suggestion:
<Button isLoading={isSending} disabled={isSending || !hasSufficientNativeBalance} text={buttonText} onClick={handleRaiseDispute} + tooltip={!hasSufficientNativeBalance ? "Insufficient balance to raise dispute" : undefined} />Note: Ensure that the Button component from @kleros/ui-components-library supports a
tooltipprop. If it doesn't, you might need to wrap the Button in a tooltip component or implement a custom solution.web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (1)
156-156: LGTM: Button disabled state updated correctly, but consider improving user feedback.The button's disabled state now correctly includes the check for sufficient native balance, which aligns with the PR objective. However, consider adding a tooltip or some visual indication to inform the user why the button is disabled when there's insufficient balance. This would improve the user experience by providing clear feedback.
Consider adding a tooltip to the button:
<StyledButton isLoading={isSending} disabled={isSending || !hasSufficientNativeBalance} text={isNativeTransaction || isApproved ? "Deposit the Payment" : "Approve Token"} onClick={isNativeTransaction || isApproved ? handleCreateTransaction : handleApproveToken} tooltip={!hasSufficientNativeBalance ? "Insufficient balance for this transaction" : undefined} />Note: Ensure that the
StyledButtoncomponent supports atooltipprop. If it doesn't, you may need to wrap it in a tooltip component from your UI library.
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (8)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/AcceptSettlementButton.tsx (3 hunks)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/ExecuteTransactionButton.tsx (3 hunks)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/ProposeSettlementButton.tsx (3 hunks)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (3 hunks)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/TimeOutButton.tsx (3 hunks)
- web/src/pages/MyTransactions/TransactionDetails/WasItFulfilled/Buttons/ClaimFullPaymentButton.tsx (3 hunks)
- web/src/pages/MyTransactions/TransactionDetails/WasItFulfilled/Buttons/ReleasePaymentButton.tsx (3 hunks)
- web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (3 hunks)
Additional context used
Learnings (1)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (1)
Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:180-180 Timestamp: 2024-06-11T17:11:32.906Z Learning: The `refetchAllowance` function call is necessary in the `DepositPaymentButton` component to ensure the frontend updates correctly after an approval action.
Additional comments not posted (20)
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/AcceptSettlementButton.tsx (1)
7-7: LGTM: New context hook import added.The import of
useNewTransactionContextis correctly added and aligns with the existing import style.web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/ExecuteTransactionButton.tsx (1)
7-7: LGTM: New context import added correctly.The import statement for
useNewTransactionContextis properly placed and follows the correct naming convention for React hooks.web/src/pages/MyTransactions/TransactionDetails/WasItFulfilled/Buttons/ClaimFullPaymentButton.tsx (2)
5-5: LGTM: New context hook import.The new import for
useNewTransactionContextis correctly placed and follows proper naming conventions for React hooks.
20-20: LGTM: Proper usage of the new context hook.The
hasSufficientNativeBalancefunction is correctly extracted from theuseNewTransactionContexthook. The naming is clear and descriptive, enhancing code readability.web/src/pages/MyTransactions/TransactionDetails/WasItFulfilled/Buttons/ReleasePaymentButton.tsx (4)
5-5: LGTM: New context hook import added.The import of
useNewTransactionContextis correctly added and aligns with the PR objective to check the user's native balance.
19-19: LGTM: New context hook used correctly.The
useNewTransactionContexthook is properly utilized to extract thehasSufficientNativeBalancevalue. This implementation aligns well with the PR objective and follows React best practices.
Line range hint
1-58: Summary: Changes successfully implement the PR objective.The modifications in this file effectively disable the "Release full payment" button when the user has insufficient native balance. This is achieved by:
- Importing and using the
useNewTransactionContexthook to access thehasSufficientNativeBalancevalue.- Updating the button's
disabledprop to include the!hasSufficientNativeBalancecondition.These changes align perfectly with the PR objective and maintain the existing functionality of disabling the button during transaction processing.
50-50: LGTM: Button disabled state updated correctly.The modification to the button's
disabledprop successfully implements the PR objective. The button will now be disabled when the user has insufficient native balance or when a transaction is in progress.To ensure this change doesn't affect other parts of the codebase, let's verify the usage of
ReleasePaymentButton:Verification successful
Verification Complete: No Additional Usages Found
The changes to the
ReleasePaymentButton'sdisabledprop are confined to its current implementation withinweb/src/pages/MyTransactions/TransactionDetails/WasItFulfilled/Buttons/. No other usages ofReleasePaymentButtonwere detected in the codebase.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for any other usage of ReleasePaymentButton that might be affected by this change. # Test: Search for ReleasePaymentButton usage rg --type typescript --type tsx "ReleasePaymentButton"Length of output: 89
Script:
#!/bin/bash # Description: Check for any other usage of ReleasePaymentButton that might be affected by this change. # Test: Search for ReleasePaymentButton usage in TypeScript and TSX files rg --type typescript --type typescriptreact "ReleasePaymentButton"Length of output: 101
Script:
#!/bin/bash # Description: Check for any other usage of ReleasePaymentButton that might be affected by this change. # Test: Search for ReleasePaymentButton usage in .ts and .tsx files using glob patterns rg "ReleasePaymentButton" --glob "*.ts" --glob "*.tsx"Length of output: 627
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/ProposeSettlementButton.tsx (4)
8-8: LGTM: New context import added correctly.The new import for
useNewTransactionContextis appropriately placed and follows the correct naming convention for React hooks.
32-32: LGTM: New context variable correctly implemented.The
hasSufficientNativeBalancevariable is appropriately destructured from the new context. Its name clearly indicates its purpose, which aligns with the PR objective.
Line range hint
1-68: Summary: PR objective successfully implemented.The changes in this file successfully implement the PR objective of disabling the button when the user has insufficient native balance. The implementation includes:
- Importing a new context (
useNewTransactionContext).- Using the
hasSufficientNativeBalancevariable from this context.- Incorporating this variable into the button's
disabledprop logic.These changes are well-integrated into the existing code structure and follow React best practices.
62-62: LGTM: Button disabled state correctly updated.The
disabledprop of the Button component has been appropriately updated to include the new condition!hasSufficientNativeBalance. This change directly implements the PR objective of disabling the button when the user has insufficient native balance.To ensure the correctness of this implementation, let's verify that
hasSufficientNativeBalanceis being set correctly in theNewTransactionContext:Verification successful
LGTM: Button disabled state correctly updated.
The
disabledprop of the Button component has been appropriately updated to include the new condition!hasSufficientNativeBalance. This change ensures that the button is disabled when the user has insufficient native balance, aligning with the PR's objective.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the implementation of hasSufficientNativeBalance in NewTransactionContext # Test: Search for the definition and usage of hasSufficientNativeBalance rg --type typescript -e "hasSufficientNativeBalance" -e "NewTransactionContext"Length of output: 112
Script:
#!/bin/bash # Description: Verify the implementation of hasSufficientNativeBalance in NewTransactionContext # Test: Search for the definition and usage of hasSufficientNativeBalance in TypeScript files rg --glob "*.ts" --glob "*.tsx" "hasSufficientNativeBalance" | rg "NewTransactionContext"Length of output: 1861
Script:
#!/bin/bash # Description: Locate all instances where setHasSufficientNativeBalance is called to verify proper balance updates rg --glob "*.ts" --glob "*.tsx" "setHasSufficientNativeBalance"Length of output: 1285
Script:
#!/bin/bash # Description: Verify how hasSufficientNativeBalance is set based on user balance # Search for balance-related logic that affects setHasSufficientNativeBalance rg --glob "*.ts" --glob "*.tsx" "balance" | rg "setHasSufficientNativeBalance"Length of output: 225
Script:
#!/bin/bash # Description: Extract the logic in TokenAndAmount/index.tsx that sets hasSufficientNativeBalance based on balanceData and quantity # Display lines around setHasSufficientNativeBalance to understand the context rg --glob "web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx" -C 5 "setHasSufficientNativeBalance"Length of output: 3865
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/TimeOutButton.tsx (2)
4-4: LGTM: New context import added correctly.The new import for
useNewTransactionContextis properly placed and follows the correct naming convention for React hooks.
Line range hint
1-73: Summary: PR objective successfully implemented.The changes in this file successfully implement the PR objective of disabling the button when the user has insufficient native balance. The new context is properly imported and used, and the button's disabled state is correctly updated to consider both the sending status and the native balance.
These changes improve the user experience by preventing attempts to perform transactions when the user lacks sufficient funds, potentially reducing failed transactions and user frustration.
To ensure that the
useNewTransactionContextis properly implemented and exported, run the following script:This script will help confirm that the new context is properly set up and available for use in the
TimeOutButtoncomponent.Verification successful
Verified:
useNewTransactionContextis correctly implemented and exported.The
useNewTransactionContexthook is properly exported fromweb/src/context/NewTransactionContext.tsxand correctly implemented usinguseContext(NewTransactionContext). This ensures that theTimeOutButtoncomponent can reliably access the transaction context without issues.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the implementation and export of useNewTransactionContext # Test: Check if useNewTransactionContext is exported from the expected file rg --type typescript -e "export.*useNewTransactionContext" -g "NewTransactionContext.ts*" # Test: Verify the implementation of useNewTransactionContext rg --type typescript -A 10 -e "const useNewTransactionContext" -g "NewTransactionContext.ts*"Length of output: 257
Script:
#!/bin/bash # Description: Verify the implementation and export of useNewTransactionContext # Test: Check if useNewTransactionContext is exported from the expected file rg --type tsx -e "export.*useNewTransactionContext" -g "NewTransactionContext.tsx" # Test: Verify the implementation of useNewTransactionContext rg --type tsx -A 10 -e "const useNewTransactionContext" -g "NewTransactionContext.tsx"Length of output: 225
Script:
#!/bin/bash # Description: Verify the implementation and export of useNewTransactionContext # Test: Check if useNewTransactionContext is exported from the expected files rg -e "export.*useNewTransactionContext" -g "*.ts" -g "*.tsx" # Test: Verify the implementation of useNewTransactionContext rg -A 10 -e "const useNewTransactionContext" -g "*.ts" -g "*.tsx"Length of output: 1537
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (3)
4-4: LGTM: New context hook import added correctly.The import statement for
useNewTransactionContextis properly placed and follows the correct naming convention for React hooks.
29-29: LGTM: New context hook used correctly.The
useNewTransactionContexthook is properly utilized, and thehasSufficientNativeBalancemethod is correctly destructured from it.
Line range hint
1-88: Summary: Changes successfully implement the PR objective.The modifications effectively disable the "Raise Dispute" button when the user has insufficient native balance, as intended. The new context hook is properly imported and utilized, and the Button component's disabled state is correctly updated. The changes are well-integrated into the existing code structure.
A suggestion was made to add a tooltip for improved user feedback, which you may want to consider implementing.
Overall, the changes look good and achieve the desired functionality.
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (3)
4-4: LGTM: New context import added correctly.The import statement for
useNewTransactionContextis correctly placed and necessary for the new functionality.
58-58: LGTM: New state variable correctly introduced.The
hasSufficientNativeBalancevariable is properly destructured from theuseNewTransactionContext. This aligns with the PR objective of checking for sufficient native balance.
Line range hint
1-163: Overall, the changes successfully implement the PR objective.The modifications to the
DepositPaymentButtoncomponent correctly integrate the newhasSufficientNativeBalancecheck from theuseNewTransactionContext. This successfully implements the PR objective of disabling the button when the user has insufficient native balance.Key points:
- The new context is correctly imported and used.
- The button's disabled state logic is updated appropriately.
- The changes are clean and consistent with the existing code style.
Consider the suggested improvement for user feedback to enhance the user experience. Otherwise, the implementation looks good and ready for merging.
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/AcceptSettlementButton.tsx
Show resolved
Hide resolved
There was a problem hiding this 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 (8)
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (4)
29-36: Approve changes with a minor suggestion for clarity.The addition of the
queryobject with theenabledproperty and the newisLoadingstate (renamed toisPreparingBuyerConfig) are good improvements. These changes align well with the PR objectives by enhancing the button's functionality based on the user's role.Consider renaming
isPreparingBuyerConfigtoisPreparingBuyerArbitrationConfigfor increased clarity about what is being prepared. This would make the variable name more descriptive and consistent with the context of arbitration fees.- const { data: payArbitrationFeeByBuyerConfig, isLoading: isPreparingBuyerConfig } = + const { data: payArbitrationFeeByBuyerConfig, isLoading: isPreparingBuyerArbitrationConfig } =
38-45: Approve changes with a minor suggestion for consistency.The modifications to the
useSimulateEscrowUniversalPayArbitrationFeeBySellerhook, including the addition of thequeryobject with theenabledproperty and the newisLoadingstate (renamed toisPreparingSellerConfig), are appropriate and consistent with the changes made for the buyer.For consistency with the previous suggestion, consider renaming
isPreparingSellerConfigtoisPreparingSellerArbitrationConfig. This would make the variable names more descriptive and uniform throughout the component.- const { data: payArbitrationFeeBySellerConfig, isLoading: isPreparingSellerConfig } = + const { data: payArbitrationFeeBySellerConfig, isLoading: isPreparingSellerArbitrationConfig } =
86-93: Approve changes with a suggestion for improved readability.The updates to the
Buttoncomponent'sisLoadinganddisabledprops correctly incorporate the new loading states for preparing arbitration fee configurations. This enhancement prevents premature user interactions, aligning well with the PR's objective of improving user experience.To improve code readability, consider extracting the condition for the
isLoadinganddisabledprops into a separate variable:+ const isProcessing = isSending || isPreparingBuyerConfig || isPreparingSellerConfig; + return ( <Button - isLoading={isSending || isPreparingBuyerConfig || isPreparingSellerConfig} - disabled={isSending || isPreparingBuyerConfig || isPreparingSellerConfig} + isLoading={isProcessing} + disabled={isProcessing} text={buttonText} onClick={handleRaiseDispute} /> );This refactoring would make the component's JSX cleaner and easier to read while maintaining the same functionality.
Missing
hasSufficientNativeBalanceCheck inRaiseDisputeButton.tsxThe
RaiseDisputeButtoncomponent does not include a check forhasSufficientNativeBalance, which is required as per the PR objectives. Please implement this validation to ensure users have sufficient native balance before raising a dispute.🔗 Analysis chain
Line range hint
1-93: Overall implementation effectively addresses PR objectives.The changes made to the
RaiseDisputeButtoncomponent successfully implement the newuseNewTransactionContextby incorporating loading states for arbitration fee configurations. This aligns well with the PR's objective of enhancing button functionality based on the user's native balance and role.However, there's one aspect of the PR objectives that isn't directly addressed in this file:
The PR summary mentions checking for
hasSufficientNativeBalance, but this check is not visible in the current implementation. Let's verify if this check is implemented elsewhere or if it needs to be added here:If the
hasSufficientNativeBalancecheck is not found or not properly implemented, consider adding it to this component to fully meet the PR objectives.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for hasSufficientNativeBalance usage in the codebase rg --type typescript 'hasSufficientNativeBalance'Length of output: 84
Script:
#!/bin/bash # Search for hasSufficientNativeBalance usage in TypeScript files rg --glob "*.ts" --glob "*.tsx" 'hasSufficientNativeBalance'Length of output: 833
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (4)
60-65: LGTM: Balance data retrieval and error state.The implementation of the
useBalancehook and the introduction of theerrorstate are appropriate for managing balance checks and error messages.Consider using a more descriptive name for the error state, such as
balanceError, to differentiate it from other potential error states in the component.
71-85: LGTM: Balance check effect implementation.The new effect for balance checking is well-implemented. It correctly compares the balance with the sending quantity, sets appropriate error messages, and updates the context.
Consider extracting the balance check logic into a separate function to improve readability and testability. For example:
const checkBalance = (balance: number, quantity: number) => { if (quantity > balance) { return "Insufficient balance"; } else if (quantity === 0) { return "Amount cannot be zero"; } return null; }; useEffect(() => { const balance = parseFloat(balanceData?.formatted || "0"); const quantity = parseFloat(sendingQuantity); const errorMessage = checkBalance(balance, quantity); setError(errorMessage); setHasSufficientNativeBalance(!errorMessage); }, [balanceData, sendingQuantity, setHasSufficientNativeBalance]);
177-185: LGTM: Button rendering and error display.The changes to the button's disabled state and the addition of the error message display are appropriate for improving user feedback.
To improve accessibility, consider wrapping the error message in an ARIA live region to ensure screen readers announce changes. For example:
<p aria-live="polite" role="status">{error}</p>This ensures that users relying on assistive technologies are informed of balance-related issues.
Line range hint
1-191: LGTM: Overall implementation of balance check feature.The changes successfully implement the balance check feature as described in the PR objectives. The use of the
useBalancehook, context updates, and error handling enhance the user experience by preventing actions with insufficient balance.To improve code organization and readability, consider extracting the balance check logic and error handling into a custom hook. For example:
const useBalanceCheck = (sendingQuantity: string, isNativeTransaction: boolean, tokenAddress?: string) => { const { address } = useAccount(); const { data: balanceData } = useBalance({ address: address as `0x${string}` | undefined, token: isNativeTransaction ? undefined : tokenAddress as `0x${string}` | undefined, }); const [error, setError] = useState<string | null>(null); const { setHasSufficientNativeBalance } = useNewTransactionContext(); useEffect(() => { // ... balance check logic ... }, [balanceData, sendingQuantity, setHasSufficientNativeBalance]); return { error, balanceData }; };This would simplify the main component and make the balance check logic more reusable.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (5)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/AcceptSettlementButton.tsx (1 hunks)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/ExecuteTransactionButton.tsx (1 hunks)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (2 hunks)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/TimeOutButton.tsx (1 hunks)
- web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/AcceptSettlementButton.tsx
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/ExecuteTransactionButton.tsx
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/TimeOutButton.tsx
🧰 Additional context used
📓 Learnings (1)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:63-64 Timestamp: 2024-06-11T17:14:13.327Z Learning: Errors in the `useContractRead` hook for ERC20 token allowance checks in the `DepositPaymentButton` component are managed by the `wrapWithToast()` function, which logs errors in a notification popup. Additionally, the quantity for the approval is pre-validated and stored in the context of the NewTransactionContext.Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:180-180 Timestamp: 2024-06-11T17:11:32.906Z Learning: The `refetchAllowance` function call is necessary in the `DepositPaymentButton` component to ensure the frontend updates correctly after an approval action.
🔇 Additional comments (2)
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (1)
49-50: LGTM: Consistent use of prepared configuration.The update to use
payArbitrationFeeBySellerConfigwith theuseWriteEscrowUniversalPayArbitrationFeeBySellerhook is consistent with the changes made to the simulation hooks. This ensures that the write operation uses the correctly prepared configuration.web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (1)
20-20: LGTM: New imports and context usage.The addition of the
useBalancehook and the extraction ofsetHasSufficientNativeBalancefrom the context are appropriate for implementing the new balance check feature.Also applies to: 42-42
There was a problem hiding this 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 (3)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (3)
52-52: LGTM: Balance checking and error handling improvements.The addition of
setHasSufficientNativeBalance,useBalancehook, and theerrorstate variable are well-aligned with the PR objectives. These changes enable balance checking and error management for both native and ERC20 tokens.Consider initializing the
errorstate with a more specific type:const [error, setError] = useState<string | null>(null);This will provide better type safety and make the code more self-documenting.
Also applies to: 70-75
81-95: LGTM: Effective balance checking implementation.The new useEffect hook successfully implements balance checking, error message setting, and context updating. This aligns perfectly with the PR objectives of disabling the button when the user has insufficient balance and providing clear feedback.
To improve readability, consider extracting the balance check logic into a separate function:
const checkBalance = (balance: number, quantity: number) => { if (quantity > balance) { setError("Insufficient balance"); setHasSufficientNativeBalance(false); } else if (quantity === 0) { setError("Amount cannot be zero"); setHasSufficientNativeBalance(false); } else { setError(null); setHasSufficientNativeBalance(true); } }; useEffect(() => { const balance = parseFloat(balanceData?.formatted || "0"); const quantity = parseFloat(sendingQuantity); checkBalance(balance, quantity); }, [balanceData, sendingQuantity, setHasSufficientNativeBalance]);This separation of concerns would make the code more maintainable and easier to test.
195-195: LGTM: Clear error message display.The conditional rendering of the ErrorMessage component effectively displays error messages to users, providing clear visual feedback about balance issues or other errors. This aligns well with the PR objectives of improving user experience and preventing actions that cannot be completed due to insufficient funds.
To improve accessibility, consider adding an
aria-liveattribute to the ErrorMessage component:{error ? <ErrorMessage aria-live="polite"><ClosedCircleIcon /> {error}</ErrorMessage> : null}This will ensure that screen readers announce the error message when it appears, enhancing the experience for users with visual impairments.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
- web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (4 hunks)
🧰 Additional context used
📓 Learnings (1)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:63-64 Timestamp: 2024-06-11T17:14:13.327Z Learning: Errors in the `useContractRead` hook for ERC20 token allowance checks in the `DepositPaymentButton` component are managed by the `wrapWithToast()` function, which logs errors in a notification popup. Additionally, the quantity for the approval is pre-validated and stored in the context of the NewTransactionContext.Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:180-180 Timestamp: 2024-06-11T17:11:32.906Z Learning: The `refetchAllowance` function call is necessary in the `DepositPaymentButton` component to ensure the frontend updates correctly after an approval action.
🔇 Additional comments (3)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (3)
20-20: LGTM: New imports and styled component.The addition of the
useBalancehook and theErrorMessagestyled component aligns well with the PR objectives. These changes will help in implementing balance checks and displaying error messages to users.Also applies to: 32-39
187-194: LGTM: Button enhancements for better user feedback.The changes to the StyledButton component, including the addition of the
disabledandtooltipprops, effectively implement the PR objectives. The button is now disabled when there's an error (including insufficient balance), and error messages are displayed as tooltips, providing clear feedback to users.
Line range hint
1-201: Great job implementing balance checks and improving user feedback!The changes in this file effectively address the PR objectives:
- Balance checking is implemented using the
useBalancehook.- The button is disabled when the user has insufficient balance or when the amount is zero.
- Clear error messages are displayed to inform users of balance issues.
- The code is well-structured and follows best practices.
These improvements will significantly enhance the user experience by preventing actions that cannot be completed due to insufficient funds and providing clear feedback.
There was a problem hiding this 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)
web/src/pages/MyTransactions/Modal/RaiseDisputeModal/FeeRequired.tsx (1)
40-40: Approve the conditional rendering with a minor suggestion.The introduction of conditional rendering for the arbitration cost is a good improvement. It prevents displaying potentially misleading values when
arbitrationCostis falsy (e.g., 0, undefined, or null).Consider adding a placeholder message when
arbitrationCostis falsy to maintain consistent layout and provide clarity to the user. For example:{arbitrationCost ? ( <StyledQuantity>{formatEther(arbitrationCost)} ETH</StyledQuantity> ) : ( <StyledQuantity>Not available</StyledQuantity> )}This ensures that the component always displays some information, improving the user experience.
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/TokenIcon.tsx (1)
Line range hint
46-57: Consider adding error logging for unexpected undefined symbols.The change in
getTokenLogoimproves error handling, but it might silently handle cases wheresymbolis unexpectedly undefined. To maintain visibility into such scenarios:
- Consider adding error logging when
symbolis undefined:const TokenIcon = ({ symbol, logo }) => { + if (symbol === undefined) { + console.error('Unexpected undefined symbol in TokenIcon'); + } const TokenLogoComponent = getTokenLogo(symbol); if (TokenLogoComponent) { return <TokenLogoComponent width={24} height={24} />; } else if (logo) { return <TokenLogoImg src={logo} alt={`${symbol} logo`} />; } else { return <StyledUnknownTokenIcon width={24} height={24} />; } };This addition will help identify unexpected undefined symbols during development or in production logs, allowing for quicker debugging and resolution of potential issues.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- web/src/pages/MyTransactions/Modal/RaiseDisputeModal/FeeRequired.tsx (1 hunks)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/TokenIcon.tsx (1 hunks)
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (2)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
32-40: LGTM: New ErrorButtonMessage component for displaying errors.The
ErrorButtonMessagestyled component is well-designed for displaying error messages, using flex layout and theme-consistent styling. This addition enhances the user feedback mechanism, which is crucial for the new balance checking feature.Consider adding an
aria-live="polite"attribute to improve accessibility for screen readers, ensuring they announce the error message when it appears:-export const ErrorButtonMessage = styled.div` +export const ErrorButtonMessage = styled.div.attrs({ 'aria-live': 'polite' })` display: flex; align-items: center; gap: 4px; justify-content: center; margin: 12px; color: ${({ theme }) => theme.error}; font-size: 14px; `;
69-76: LGTM: Balance checking and simplified address assignment.The addition of the
useBalancehook and theinsufficientBalancecalculation effectively implements the balance checking feature. The simplifiedfinalRecipientAddressassignment is a good refactor, reducing complexity.Consider adding error handling for the case where
balanceDatais undefined:const insufficientBalance = parseFloat(sendingQuantity) > parseFloat(balanceData?.value.toString() || "0"); +const balanceError = !balanceData && 'Unable to fetch balance';This will help distinguish between an insufficient balance and a failure to fetch the balance.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (4 hunks)
- web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx
🧰 Additional context used
📓 Learnings (1)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:63-64 Timestamp: 2024-06-11T17:14:13.327Z Learning: Errors in the `useContractRead` hook for ERC20 token allowance checks in the `DepositPaymentButton` component are managed by the `wrapWithToast()` function, which logs errors in a notification popup. Additionally, the quantity for the approval is pre-validated and stored in the context of the NewTransactionContext.Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:180-180 Timestamp: 2024-06-11T17:11:32.906Z Learning: The `refetchAllowance` function call is necessary in the `DepositPaymentButton` component to ensure the frontend updates correctly after an approval action.
🔇 Additional comments (2)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
20-20: LGTM: New imports for balance checking and error UI.The added imports for
useBalanceandClosedCircleIconare consistent with the new features implemented in this component. These additions enhance the functionality by enabling balance checks and improving the error message UI.Also applies to: 28-28
Line range hint
1-184: Overall assessment: Well-implemented balance checking feature.The changes in this file effectively implement the PR objective of disabling the button when the user has insufficient native balance. The new balance checking feature is well-integrated into the existing component structure, and the error handling remains consistent with previous learnings (using
wrapWithToast()). TherefetchAllowancefunctionality is maintained, aligning with the learning about its necessity for frontend updates after approval actions.The added
useBalancehook,insufficientBalancecalculation, and error message display enhance the user experience by providing clear feedback about balance issues. The simplifiedfinalRecipientAddressassignment is a good refactor that reduces complexity.These changes improve the overall robustness and user-friendliness of the transaction process, aligning well with the PR objectives.
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/AcceptSettlementButton.tsx
Outdated
Show resolved
Hide resolved
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/AcceptSettlementButton.tsx
Outdated
Show resolved
Hide resolved
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx
Outdated
Show resolved
Hide resolved
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx
Outdated
Show resolved
Hide resolved
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx
Outdated
Show resolved
Hide resolved
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx
Outdated
Show resolved
Hide resolved
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx
Outdated
Show resolved
Hide resolved
22dec65
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (2)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
61-70: LGTM: Improved ENS handling and address assignment.The changes to ENS resolution and
finalRecipientAddressassignment are good improvements:
- Using
normalizewith theuseEnsAddresshook ensures proper ENS name handling.- Direct assignment of
finalRecipientAddresssimplifies the code by removing the need for auseEffect.These changes enhance the efficiency and readability of the component.
Consider using
useMemoforfinalRecipientAddressto optimize performance:const finalRecipientAddress = useMemo( () => ensResult.data || sellerAddress, [ensResult.data, sellerAddress] );This ensures the value is only recalculated when
ensResult.dataorsellerAddresschanges.
175-187: LGTM with suggestion: UI updates for insufficient balance.The changes to the UI components effectively implement the PR objective:
- The button is correctly disabled when there's insufficient balance.
- The error message is displayed using the new
ErrorButtonMessagecomponent when the balance is insufficient.These updates provide clear visual feedback to the user, preventing actions that cannot be completed due to lack of funds.
Consider adding a tooltip to the disabled button to provide immediate feedback:
<StyledButton isLoading={isSending} disabled={isSending || insufficientBalance} title={insufficientBalance ? "Insufficient balance to complete this transaction" : ""} text={isNativeTransaction || isApproved ? "Deposit the Payment" : "Approve Token"} onClick={isNativeTransaction || isApproved ? handleCreateTransaction : handleApproveToken} />This will give users context on why the button is disabled, even before they see the error message.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/AcceptSettlementButton.tsx (2 hunks)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (4 hunks)
- web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/AcceptSettlementButton.tsx
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx
🧰 Additional context used
📓 Learnings (1)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:63-64 Timestamp: 2024-06-11T17:14:13.327Z Learning: Errors in the `useContractRead` hook for ERC20 token allowance checks in the `DepositPaymentButton` component are managed by the `wrapWithToast()` function, which logs errors in a notification popup. Additionally, the quantity for the approval is pre-validated and stored in the context of the NewTransactionContext.Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:180-180 Timestamp: 2024-06-11T17:11:32.906Z Learning: The `refetchAllowance` function call is necessary in the `DepositPaymentButton` component to ensure the frontend updates correctly after an approval action.
🔇 Additional comments (4)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (4)
22-22: LGTM: Import ofnormalizefunction.The addition of the
normalizefunction from 'viem/ens' is appropriate for handling ENS name normalization. This import supports the proper processing of ENS names in the component.
28-28: LGTM: Import ofClosedCircleIconcomponent.The addition of the
ClosedCircleIconimport is appropriate for enhancing the visual feedback in error messages. This aligns well with the PR objective of improving UI components for clarity.
32-41: LGTM: NewErrorButtonMessagestyled component.The addition of the
ErrorButtonMessagestyled component is well-implemented. It provides a consistent and visually appealing way to display error messages, particularly for insufficient balance scenarios. This aligns with the PR objective of improving UI components and providing clearer feedback to users.
85-85: LGTM: Addition ofinsufficientBalancechecks.The addition of
insufficientBalancechecks in various conditions is a great improvement:
- It prevents unnecessary contract calls when the user doesn't have sufficient balance.
- It aligns with the PR objective of enhancing error handling during the transaction process.
- It helps in providing early feedback to the user, improving the overall user experience.
These changes effectively implement the core objective of the PR by disabling actions that cannot be executed due to insufficient funds.
Also applies to: 100-100, 112-113, 125-125
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
-
the
isLoading&&isErrorfeedback has to be implemented ALL buttons. -
there are more instances in the repo of tokens balances being fetched with the "useBalance" hook by wagmi. we need to refactor ALL of those too.
-
the condition
!isBuyer || !insufficientBalanceis incorrect, it has to be&&AND operation.
|
Another thing, the insufficientBalance useMemo returns true when the data is loading which is not pretty UX wise Screen.Recording.2024-10-01.at.15.03.46.mov |
There was a problem hiding this 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)
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (2)
27-31: Improved balance fetching withuseReadContractThe switch to
useReadContractprovides more precise control over the balance fetching process and adheres to the ERC20 standard. The type assertions for Ethereum addresses enhance type safety.Consider adding a safety check for
token.addressto handle cases where it might be undefined (e.g., for native ETH):const { data: balanceData } = useReadContract( token?.address ? { address: token.address as `0x${string}`, abi: erc20Abi, functionName: 'balanceOf', args: [address as `0x${string}`], } : undefined );
Line range hint
33-43: Consider explicit handling of loading stateThe overall component structure and logic remain consistent, which is good for maintainability. The use of
useMemoforformattedBalanceis appropriate for performance.To improve user experience, consider explicitly handling the loading state from
useReadContract:const { data: balanceData, isLoading } = useReadContract({...}); // In the return statement return ( <Container> {isLoading || isUndefined(formattedBalance) ? <StyledAmountSkeleton /> : null} {!isLoading && !isUndefined(formattedBalance) && formattedBalance !== "0" ? formattedBalance : null} </Container> );This change will ensure that the skeleton loader is displayed during the initial loading phase, providing a smoother user experience.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (4 hunks)
- web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (6 hunks)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx
- web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx
🔇 Additional comments (2)
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (2)
4-4: Improved token balance fetching approachThe changes in the import statements reflect a shift from using
useBalancetouseReadContract, along with the addition oferc20Abi. This approach allows for more flexible and standardized interaction with ERC20 tokens.These changes should provide better consistency across different ERC20 tokens and potentially improve the reliability of balance fetching.
Also applies to: 8-8
Line range hint
1-43: Summary: Improved balance fetching aligns with PR objectivesThe changes in this file contribute positively to the PR's objectives of enhancing error handling and improving UI components. The new implementation of balance fetching using
useReadContractprovides more precise control and adheres to ERC20 standards, which can lead to better error handling and more accurate balance displays.To further align with the PR objectives:
- Implement the suggested safety check for
token.addressto handle potential undefined cases.- Add explicit handling of the loading state to improve user feedback and prevent potential UI flickering.
These improvements will enhance the overall user experience and error handling, fully meeting the PR's goals.
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (2)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
61-61: LGTM: Simplified ENS resolution and recipient address handling.The ENS resolution logic has been streamlined, and the
finalRecipientAddressassignment is now more straightforward. This change improves code readability and efficiency.Consider adding a comment to explain the fallback logic:
// Use ENS resolution result if available, otherwise use the original sellerAddress const finalRecipientAddress = ensResult.data || sellerAddress;This comment would help future developers understand the purpose of this assignment at a glance.
Also applies to: 69-69
181-200: LGTM: Enhanced button state and error message display.The updates to the button's disabled state and the addition of the error message for insufficient balance significantly improve the user experience. These changes effectively implement the PR objective of disabling the button when the user has insufficient balance and displaying an error message.
Consider adding a tooltip to the disabled button to provide more context:
<StyledButton isLoading={isSending || isLoadingNativeConfig || isLoadingERC20Config} disabled={ isSending || insufficientBalance || isLoadingNativeConfig || isLoadingERC20Config || isErrorNativeConfig || isErrorERC20Config } + title={insufficientBalance ? "Insufficient balance to complete this transaction" : ""} text={isNativeTransaction || isApproved ? "Deposit the Payment" : "Approve Token"} onClick={isNativeTransaction || isApproved ? handleCreateTransaction : handleApproveToken} />This will give users immediate feedback on why the button is disabled, even before they see the error message.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (7)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/ExecuteTransactionButton.tsx (2 hunks)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/ProposeSettlementButton.tsx (2 hunks)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (4 hunks)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/TimeOutButton.tsx (2 hunks)
- web/src/pages/MyTransactions/TransactionDetails/WasItFulfilled/Buttons/ClaimFullPaymentButton.tsx (2 hunks)
- web/src/pages/MyTransactions/TransactionDetails/WasItFulfilled/Buttons/ReleasePaymentButton.tsx (2 hunks)
- web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/ExecuteTransactionButton.tsx
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/ProposeSettlementButton.tsx
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/TimeOutButton.tsx
- web/src/pages/MyTransactions/TransactionDetails/WasItFulfilled/Buttons/ClaimFullPaymentButton.tsx
- web/src/pages/MyTransactions/TransactionDetails/WasItFulfilled/Buttons/ReleasePaymentButton.tsx
🧰 Additional context used
📓 Learnings (1)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:63-64 Timestamp: 2024-06-11T17:14:13.327Z Learning: Errors in the `useContractRead` hook for ERC20 token allowance checks in the `DepositPaymentButton` component are managed by the `wrapWithToast()` function, which logs errors in a notification popup. Additionally, the quantity for the approval is pre-validated and stored in the context of the NewTransactionContext.Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:180-180 Timestamp: 2024-06-11T17:11:32.906Z Learning: The `refetchAllowance` function call is necessary in the `DepositPaymentButton` component to ensure the frontend updates correctly after an approval action.
🔇 Additional comments (9)
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (6)
3-3: LGTM: New imports support balance checking and error display.The added imports for
useBalance,ClosedCircleIcon, andErrorButtonMessageare appropriate for implementing the new balance checking functionality and improving error display, aligning with the PR objectives.Also applies to: 14-15
31-33: LGTM: Balance retrieval implemented correctly.The
useBalancehook is correctly implemented to fetch the user's balance using their address. This change is essential for the new balance checking functionality.
39-42: LGTM: Simulation hooks optimized with balance check.The addition of the
insufficientBalancecheck in theenabledproperty of the simulation hooks is a good optimization. This change will help save RPC bandwidth by preventing unnecessary simulations when the user has insufficient balance, as suggested in the previous review.Also applies to: 47-50
95-109: LGTM: Button state handling improved.The changes to the Button component's
disabledprop andisLoadingstate are well-implemented. The inclusion of theinsufficientBalancecondition and consideration of loading/error states from both buyer and seller config hooks improve error handling and user feedback, aligning with the PR objectives.
110-114: LGTM: Clear error message for insufficient balance.The addition of the error message for insufficient balance using the
ErrorButtonMessagecomponent andClosedCircleIconis a good improvement. This change enhances user feedback and clarity, aligning well with the PR objectives.
Line range hint
1-116: Overall, good improvements to error handling and user feedback.The changes in this file significantly enhance the
RaiseDisputeButtoncomponent by implementing balance checks, improving error handling, and providing clearer user feedback. These improvements align well with the PR objectives and address most of the concerns raised in previous reviews.The main point for improvement is in the
insufficientBalancecalculation. Addressing this will make the component more robust and improve the user experience, especially during loading states.Great work on enhancing the overall functionality and user experience of this component!
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (3)
22-22: LGTM: New imports and error message component.The addition of
normalizefrom 'viem/ens' andClosedCircleIconimproves ENS handling and UI feedback. The newErrorButtonMessagestyled component enhances error display, aligning with the PR objective of improving user feedback during the transaction process.Also applies to: 28-28, 32-40
96-102: LGTM: Improved transaction simulation and error handling.The updates to the enabled conditions for transaction simulations and the addition of loading and error states significantly improve the component's robustness. These changes prevent unnecessary simulations when the balance is insufficient and provide better feedback to the user, aligning with the PR objectives.
The separation of loading and error states for native and ERC20 transactions allows for more granular control over the UI, enhancing the overall user experience.
Also applies to: 108-119
Line range hint
1-204: Overall assessment: Significant improvements in error handling and user experience.This PR successfully implements balance checks, enhances error handling, and improves UI components for clarity and responsiveness. The changes align well with the stated objectives and significantly enhance the user experience during the transaction process.
Key improvements include:
- Simplified ENS resolution and recipient address handling.
- Implementation of balance checks (with a suggestion for improvement for native tokens).
- Enhanced transaction simulation with better error handling.
- Improved button state management and error message display.
With the suggested minor improvements, this PR represents a substantial step forward in the functionality and user-friendliness of the DepositPaymentButton component.
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx
Outdated
Show resolved
Hide resolved
|
im seeing some crashes in payment step and failed to load the amounts specially when you open the token modal. probably related to the useReadContract and useBalance hook modifications. |
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (2)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
107-138: LGTM with suggestion: Improved transaction simulation handling.The addition of loading and error states for transaction simulations, along with the
insufficientBalancecheck in theenabledconditions, significantly improves error handling and user feedback. This aligns well with the PR objectives.Consider adding a loading indicator or message when the simulation is in progress to provide even clearer feedback to the user:
{isLoadingNativeConfig || isLoadingERC20Config ? ( <LoadingMessage>Simulating transaction...</LoadingMessage> ) : null}This would further enhance the user experience during the transaction process.
198-217: LGTM with suggestion: Improved button state and error handling.The updates to the button state, including loading and error conditions, along with the
insufficientBalancecheck and error message display, significantly improve the user interface. These changes provide clearer feedback about the transaction state and prevent actions when the balance is insufficient, aligning well with the PR objectives.Consider adding a tooltip to the button to provide more context when it's disabled:
<StyledButton // ... existing props title={insufficientBalance ? "Insufficient balance to complete this transaction" : ""} />This would provide immediate feedback to users about why the button is disabled, even before they see the error message.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (4 hunks)
- web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (5 hunks)
🧰 Additional context used
📓 Learnings (1)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:63-64 Timestamp: 2024-06-11T17:14:13.327Z Learning: Errors in the `useContractRead` hook for ERC20 token allowance checks in the `DepositPaymentButton` component are managed by the `wrapWithToast()` function, which logs errors in a notification popup. Additionally, the quantity for the approval is pre-validated and stored in the context of the NewTransactionContext.Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:180-180 Timestamp: 2024-06-11T17:11:32.906Z Learning: The `refetchAllowance` function call is necessary in the `DepositPaymentButton` component to ensure the frontend updates correctly after an approval action.
🔇 Additional comments (9)
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx (5)
3-3: LGTM: New imports added correctly.The new imports for
useBalance,ClosedCircleIcon, andErrorButtonMessageare correctly added and necessary for the implemented balance checking and error display functionality.Also applies to: 14-15
39-58: LGTM: Well-implemented arbitration fee simulation hooks.The implementation of separate hooks for buyer and seller arbitration fee simulation is well done. The tracking of loading and error states for each simulation is a good practice. The conditional enabling of hooks based on user role and balance sufficiency is an excellent optimization to save RPC bandwidth.
103-117: LGTM: Comprehensive button state handling.The button rendering logic effectively considers multiple factors to determine its state, including balance insufficiency, loading states, and error conditions. This implementation aligns well with the PR objectives of improving UI components for clarity and responsiveness.
118-122: LGTM: Clear error message for insufficient balance.The implementation of the error message for insufficient balance is well done. It provides clear feedback to the user and enhances visibility with the use of an icon. This aligns perfectly with the PR objectives of enhancing error handling and user feedback.
Line range hint
1-124: LGTM: Excellent implementation of balance checking and error handling.The overall structure of the
RaiseDisputeButtoncomponent has been effectively adjusted to accommodate the new balance checking and error handling functionality. The changes consistently apply error handling and loading states throughout the component, resulting in a more robust and user-friendly interface. These improvements align well with the PR objectives of enhancing error handling, user feedback, and UI responsiveness during the transaction process.Great job on implementing these enhancements!
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (4)
20-23: LGTM: New imports for enhanced functionality.The added imports (
useBalance,normalize, andClosedCircleIcon) are appropriate for the new features implemented in this component. They support native token balance checking, ENS normalization, and improved error message UI respectively.Also applies to: 29-29
33-41: LGTM: Well-structured error message component.The new
ErrorButtonMessagestyled component is a good addition for displaying the insufficient balance error. It's well-structured, uses theme colors for consistency, and aligns with the PR objective of improving UI components for clarity.
94-95: LGTM: Improved query efficiency and error handling.The addition of the
insufficientBalancecheck in theenabledcondition for the allowance query is a good optimization. It prevents unnecessary allowance checks when the balance is insufficient. The use of optional chaining forescrowUniversalAddressis also a good defensive programming practice.Also applies to: 98-98
148-148: LGTM: Optimized approve simulation.The addition of the
insufficientBalancecheck in theenabledcondition for the approve simulation is a good optimization. It prevents unnecessary simulations when the balance is insufficient, potentially saving computational resources and improving the overall performance of the component.
web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx
Show resolved
Hide resolved
There was a problem hiding this 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 (3)
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (3)
26-26: LGTM: Good addition for transaction type differentiation.The
isNativeTransactionconstant provides a clear way to distinguish between native and token transactions. However, consider using a more robust check:const isNativeTransaction = token?.address === 'native' || token?.address === '0x0000000000000000000000000000000000000000';This change would cover cases where the native token might be represented by the zero address as well.
32-37: LGTM: Effective implementation of contract reading for token balances.The use of
useReadContractfor fetching token balances is a good approach. However, consider adding error handling:const { data: tokenBalance, error } = useReadContract({ address: !isNativeTransaction ? token?.address as `0x${string}` : undefined, abi: erc20Abi, functionName: 'balanceOf', args: [address as `0x${string}`], }); if (error) { console.error('Error fetching token balance:', error); }This addition would help in debugging and potentially improving user feedback in case of errors.
39-42: LGTM: Improved balance calculation and rendering.The updated
formattedBalancecalculation correctly handles both native and token balances. The simplified rendering logic is more concise. However, consider separating the rendering logic for better readability:const renderBalance = () => { if (isUndefined(formattedBalance)) { return <StyledAmountSkeleton />; } return formattedBalance !== "0" ? formattedBalance : null; }; return ( <Container> {renderBalance()} </Container> );This separation would make the component's render method easier to understand at a glance.
Also applies to: 46-46
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (2 hunks)
🔇 Additional comments (3)
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (3)
4-4: LGTM: New imports align with updated functionality.The addition of
useReadContractanderc20Abiimports is consistent with the shift towards using contract reads for balance fetching, which is a more flexible approach for handling both native and token balances.Also applies to: 8-8
28-30: LGTM: Efficient use ofuseBalancehook.The modification to only fetch native balance when necessary is a good optimization. The conditional address setting and type assertion enhance type safety.
Line range hint
1-51: Overall, the changes improve balance handling and component flexibility.The modifications to the
Balancecomponent effectively address the need to handle both native and token transactions. The use ofuseReadContractfor token balances and the conditional use ofuseBalancefor native transactions is a good approach.Some suggestions for further improvement:
- Enhance error handling, especially for the
useReadContracthook.- Consider refactoring the rendering logic for better readability.
- Ensure robust checking for native transactions.
These changes align well with the PR objectives of improving error handling and enhancing UI components for clarity and responsiveness.
There was a problem hiding this 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 (7)
web/src/utils/getFormattedBalance.ts (3)
3-3: Approve type improvement forbalanceData, suggest further enhancements.The change from
anytobigint | undefinedforbalanceDatais a good improvement in type safety. However, there are a couple of additional enhancements that could be made:
- Consider defining a more specific type for the
tokenparameter instead of usingany. This could improve type safety and make the function's requirements clearer.- Add an explicit return type to the function for better clarity and type checking.
Here's a suggested improvement:
type Token = { symbol: string; // Add other relevant properties }; export const getFormattedBalance = (balanceData: bigint | undefined, token: Token): string | undefined => { // Function body };
4-6: Approve changes, suggest error handling improvements.The updates to the function body are good:
- Using strict equality (
===) for the undefined check is a best practice.- Directly passing
balanceDatato the formatting functions is consistent with the new parameter type.However, there's room for improvement in error handling:
- Consider adding a check for negative
balanceDatavalues, which shouldn't occur in balance scenarios.- It might be helpful to handle cases where
tokenis undefined or doesn't have asymbolproperty.Here's a suggested improvement with additional error handling:
export const getFormattedBalance = (balanceData: bigint | undefined, token: Token): string | undefined => { if (balanceData === undefined) return undefined; if (balanceData < 0n) throw new Error("Balance cannot be negative"); if (!token || typeof token.symbol !== 'string') throw new Error("Invalid token"); if (token.symbol === "PNK") return formatPNK(balanceData); return formatETH(balanceData); };
1-6: Summary: Positive changes with room for further improvementsThe modifications to
getFormattedBalancefunction align well with the PR's objectives of enhancing error handling and improving type safety. The changes to parameter types and internal logic contribute to a more robust implementation.However, there's still room for improvement:
- Further type refinement for the
tokenparameter.- Additional error handling for edge cases.
- Explicit return type declaration.
These enhancements would further contribute to the PR's goals of improving error handling and user feedback during transactions.
Consider creating a comprehensive set of utility functions for balance and token operations. This could include type definitions, validation functions, and formatting utilities, promoting code reuse and consistency across the application.
web/src/utils/format.ts (2)
17-20: Approve with suggestion: Improve type handling informatPNK.The addition of the undefined check improves the function's robustness. However, since the
valueparameter is typed asbigint, it cannot beundefinedin TypeScript. Consider updating the type tobigint | undefinedfor more accurate typing:export const formatPNK = (value: bigint | undefined, fractionDigits = 0, roundDown = true) => { if (value === undefined) return "0"; return formatValue(formatUnitsWei(value), fractionDigits, roundDown); };This change will align the function signature with its implementation and improve type safety.
22-25: Approve with suggestion: Improve type handling informatETH.The addition of the undefined check enhances the function's robustness. However, as with
formatPNK, thevalueparameter is typed asbigint, which cannot beundefinedin TypeScript. Consider updating the type tobigint | undefinedfor more accurate typing:export const formatETH = (value: bigint | undefined, fractionDigits = 4, roundDown = true) => { if (value === undefined) return "0"; return formatValue(formatEther(value), fractionDigits, roundDown); };This change will align the function signature with its implementation and improve type safety.
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (2)
32-37: LGTM with suggestion: Add error handling foruseReadContract.The addition of
useReadContractfor fetching token balances is a good improvement. It correctly uses the token's contract address, ERC20 ABI, and the 'balanceOf' function.However, consider adding error handling for potential contract read failures to improve robustness.
Consider adding error handling:
const { data: tokenBalance, error } = useReadContract({ // ... existing configuration ... }); // Then use `error` to handle and display any issues
39-42: LGTM with suggestion: Improve zero balance handling.The updated
formattedBalancecalculation and rendering logic are good improvements. They correctly handle both native and token balances and provide better error handling for undefined values.However, the condition
formattedBalance !== "0"might not catch all cases of zero balance, especially for tokens with different decimal places.Consider using a more robust check for zero balance:
import { parseUnits } from 'ethers/lib/utils'; // In the component const isZeroBalance = useMemo(() => { if (!formattedBalance) return true; const parsedBalance = parseUnits(formattedBalance, token.decimals); return parsedBalance.isZero(); }, [formattedBalance, token.decimals]); // In the render {isUndefined(formattedBalance) ? <StyledAmountSkeleton /> : !isZeroBalance ? formattedBalance : null}This approach ensures accurate zero balance detection regardless of the token's decimal places.
Also applies to: 46-46
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (4)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (2 hunks)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx (4 hunks)
- web/src/utils/format.ts (1 hunks)
- web/src/utils/getFormattedBalance.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx
🔇 Additional comments (6)
web/src/utils/format.ts (2)
11-11: LGTM: Improved type safety forformatValue.The addition of type annotations for
fractionDigitsandroundDownparameters enhances type safety and improves code readability. This change is beneficial for maintaining code quality and reducing potential type-related errors.
Line range hint
1-25: Summary: Improved error handling, but consider addressing loading states.The changes in this file enhance error handling and type safety, which aligns with the PR objectives. The addition of undefined checks in
formatPNKandformatETHimproves robustness and prevents potential errors.However, these changes don't directly address the concerns raised in the PR comments about loading states and crashes. Consider the following suggestions:
- Implement a separate loading state in components using these functions to differentiate between "loading" and "insufficient balance" scenarios.
- Review the usage of
useReadContractanduseBalancehooks in components to ensure they're not causing the reported crashes.- Consider adding more comprehensive error handling or logging in these utility functions to help diagnose issues in the payment step and token modal.
To verify the usage of these functions and identify potential issues, you can run the following script:
This script will help identify where these functions are used and if proper error handling is in place when the result is "0" (which could indicate an undefined input).
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (4)
4-4: LGTM: Import statements updated correctly.The addition of
useReadContractanderc20Abiimports aligns with the PR objectives for improving balance fetching logic. These changes enable interaction with ERC20 tokens and reading contract data.Also applies to: 8-8
26-26: LGTM: Correctly implemented native transaction check.The
isNativeTransactionconstant is a good addition that allows for differentiation between native and token transactions. This aligns with the PR objectives of improving balance fetching logic.
28-30: LGTM: Efficient use ofuseBalancehook.The
useBalancehook is now conditionally used only for native transactions. This optimization prevents unnecessary native balance fetches for token transactions, improving efficiency.
Line range hint
1-51: Overall assessment: Good improvements with minor suggestions.The changes in this file significantly improve balance fetching and display, aligning well with the PR objectives. The implementation now correctly handles both native and token transactions, enhancing error handling and user feedback.
Key improvements:
- Efficient balance fetching using
useBalanceanduseReadContracthooks.- Clear distinction between native and token transactions.
- Improved rendering logic for balance display.
Suggestions for further improvement:
- Add error handling for
useReadContractto manage potential contract read failures.- Implement a more robust check for zero balances to account for tokens with different decimal places.
These changes, along with the suggested improvements, will greatly enhance the user experience and reliability of the balance display functionality.
...nsaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx
Outdated
Show resolved
Hide resolved
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (5)
web/src/utils/getFormattedBalance.ts (2)
3-3: Improved type safety forbalanceData, consider enhancingtokentype as well.The change from
anytobigintforbalanceDatais a good improvement in type safety. However, thetokenparameter is still typed asany.Consider defining a more specific type for the
tokenparameter to further enhance type safety. For example:type Token = { symbol: string; // Add other relevant properties }; export const getFormattedBalance = (balanceData: bigint, token: Token) => { // ... };
5-6: Approve changes, but consider more robust token handling.The updates to
formatPNKandformatETHcalls align well with the newbiginttype. The null-safe access ontoken?.symbolis a good practice.However, the current implementation assumes any non-PNK token should be formatted as ETH, which might not always be correct. Consider adding a more robust token check or a default case:
if (token?.symbol === "PNK") return formatPNK(balanceData); if (token?.symbol === "ETH") return formatETH(balanceData); // Add more token checks if needed return formatETH(balanceData); // Default case, or consider throwing an errorweb/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (3)
26-26: LGTM: Good addition ofisNativeTransaction.The new constant improves code readability and maintainability by clearly distinguishing between native and token transactions.
Consider adding a comment explaining what 'native' represents in this context for better clarity:
// 'native' represents the blockchain's native currency (e.g., ETH for Ethereum) const isNativeTransaction = token?.address === 'native';
28-37: LGTM: Improved balance fetching logic.The separation of native and token balance fetching improves the component's flexibility and accuracy. The implementation correctly uses the appropriate hooks and parameters.
Consider adding error handling for the
useReadContracthook:const { data: tokenBalance, error } = useReadContract({ // ... existing configuration ... }); // Then, in the component body: if (error) { console.error('Error fetching token balance:', error); // Optionally, set an error state or display an error message }This will help catch and handle any potential issues with contract interactions.
Line range hint
44-48: Consider simplifying the return statement.While the current implementation is functionally correct, it still uses nested ternary operators, which can be hard to maintain. As suggested in the past review comments, consider refactoring to improve readability:
return ( <Container> {isUndefined(formattedBalance) ? ( <StyledAmountSkeleton /> ) : formattedBalance !== "0" ? ( formattedBalance ) : null} </Container> );This version eliminates the nested ternary operators while maintaining the same logic, making it easier to read and maintain.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (4)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (2 hunks)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx (4 hunks)
- web/src/utils/format.ts (1 hunks)
- web/src/utils/getFormattedBalance.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- web/src/utils/format.ts
🧰 Additional context used
🔇 Additional comments (10)
web/src/utils/getFormattedBalance.ts (2)
3-6: Overall improvements in type safety and clarity.The changes to
getFormattedBalancefunction have significantly improved its type safety and clarity. The use ofbigintforbalanceDataand the explicit undefined check are positive changes.To further enhance this function:
- Consider improving the type definition for the
tokenparameter.- Use the
isUndefined()utility function for consistency.- Implement more robust token type checking.
These improvements will make the function more type-safe, consistent with the rest of the codebase, and less prone to errors when handling different token types.
4-4: 🛠️ Refactor suggestionConsider using
isUndefined()utility function.The explicit check
balanceData === undefinedis good, but for consistency with the rest of the codebase, consider using theisUndefined()utility function.Import and use the
isUndefined()function from the "utils/index" folder:import { isUndefined } from "../utils"; // ... if (isUndefined(balanceData)) return undefined;web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (3)
4-4: LGTM: Import statement updated correctly.The addition of
useReadContractto the import statement is consistent with the new functionality implemented in the component.
39-42: LGTM: ImprovedformattedBalancecalculation.The updated
useMemohook correctly handles both native and token balances, using the appropriate utility function for formatting. The dependencies array is properly updated to include all relevant variables, ensuring the memoized value is recalculated when necessary.
Line range hint
1-54: Overall, good improvements to balance handling and display.The changes in this file significantly improve the
Balancecomponent's ability to handle both native and token transactions. The separation of balance fetching logic and the use of appropriate hooks enhance the component's flexibility and accuracy.Key improvements:
- Addition of
isNativeTransactionfor clear distinction between transaction types.- Separate handling of native and token balances using appropriate hooks.
- Updated
formattedBalancecalculation to accommodate both balance types.Minor suggestions have been made for further improvement:
- Adding a comment to clarify the 'native' concept.
- Implementing error handling for the
useReadContracthook.- Simplifying the return statement to avoid nested ternary operators.
These suggestions are minor and don't impact the core functionality, but they could further enhance the code's readability and robustness.
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx (5)
4-4: LGTM: Import statements updated correctlyThe new import statements for
useReadContract,useBalance,erc20Abi, andformatUnitsare correctly added and necessary for the implemented changes in balance fetching and calculation logic.Also applies to: 7-8
80-80: LGTM: Dependency array updated correctlyAdding
balanceAmountto the dependency array of theuseEffecthook is correct. This ensures that the effect runs whenever the balance changes, keeping the error state and native balance sufficiency check up-to-date.
82-85: LGTM: Formatted balance calculation improvedThe new
formattedBalancecalculation usinguseMemois well-implemented. It correctly handles both native and token balances, and properly uses theisUndefinedutility function. This approach ensures efficient recalculation of the formatted balance only when necessary.
94-94: LGTM: MaxBalance component prop updated correctlyUpdating the
rawBalanceprop to usebalanceAmountis correct and consistent with the new balance calculation logic. This change provides a more accurate raw balance value to the MaxBalance component.
101-101: LGTM: Minor formatting improvementAdding an empty line before the export statement improves code readability. This is a good practice for maintaining clean and well-structured code.
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (2)
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx (2)
82-85: LGTM with minor optimization suggestionThe
formattedBalancecalculation usinguseMemois well-implemented. It correctly handles both native and token balances and properly checks for undefined values.A minor optimization could be to memoize the
balancevalue:const formattedBalance = useMemo(() => { const balance = useMemo(() => isNativeTransaction ? nativeBalance?.value : tokenBalance, [isNativeTransaction, nativeBalance, tokenBalance] ); return !isUndefined(balance) ? getFormattedBalance(balance, sendingToken) : undefined; }, [sendingToken, balance]);This change would prevent unnecessary recalculations of the
balancevalue when onlysendingTokenchanges. However, this is a minor optimization and the current implementation is already good.
Line range hint
1-101: Summary of reviewThe changes to the
TokenAndAmountcomponent significantly improve its functionality, particularly in terms of balance fetching and calculation. The separation of native and token balance handling is a good step forward. However, there are a few areas where further improvements could be made:
- Error handling: Implement more robust error handling in the balance fetching logic and balance amount calculation.
- Loading states: Address the concern about showing incorrect balance information during loading by implementing a tri-state approach (loading, error, success) in the balance amount calculation.
- Type safety: Enhance type assertions and null checks to prevent potential runtime errors.
- Performance: Consider the suggested minor optimization in the
formattedBalancecalculation.These improvements will enhance the component's reliability and user experience. Overall, the changes are moving in the right direction, and with these additional enhancements, the component will be more robust and user-friendly.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx (4 hunks)
🧰 Additional context used
🔇 Additional comments (4)
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx (4)
4-4: LGTM: Import statements updated correctlyThe new import statements for
useReadContract,useBalance,erc20Abi, andformatUnitsare correctly added and necessary for the implemented balance fetching and calculation logic.Also applies to: 7-8
80-80: LGTM: Dependency array updated correctlyAdding
balanceAmountto the dependency array of theuseEffecthook is correct. This ensures that the effect runs when the balance changes, which is crucial for accurate error handling and balance sufficiency checks.
94-94: LGTM: MaxBalance prop updated correctlyUpdating the
rawBalanceprop of theMaxBalancecomponent to usebalanceAmountis correct and consistent with the new balance calculation logic. This change provides more accurate raw balance data to theMaxBalancecomponent, which is crucial for correct functionality.
101-101: LGTM: Empty line added at end of fileAdding an empty line at the end of the file is a good practice. It ensures that the file ends with a newline character, which can prevent issues with certain tools and improve git diff readability.
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lgtm
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Outside diff range and nitpick comments (3)
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (1)
33-39: LGTM: Efficient token balance fetching implementedThe addition of the
useReadContracthook for fetching token balances is well-implemented. It's correctly configured and only enabled for non-native transactions, which is efficient.Consider adding a check for
token?.addressbefore using it in theaddressprop to prevent potential runtime errors:address: !isNativeTransaction && token?.address ? (token.address as `0x${string}`) : undefined,web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx (2)
37-58: Improved balance fetching, but error handling could be enhancedThe separation of native and token balance fetching is a good improvement. The use of
isNativeTransactionand theenabledoption inuseReadContracthelps prevent unnecessary API calls.However, to further enhance robustness, consider implementing error handling as suggested in the previous review:
- Capture error states from
useBalanceanduseReadContract.- Handle these errors in the component to provide feedback to the user.
Example:
const { data: nativeBalance, isError: isNativeBalanceError } = useBalance({ // ... existing code ... }); // Similar changes for tokenBalance and tokenDecimal useEffect(() => { if (isNativeBalanceError || isTokenBalanceError || isTokenDecimalError) { // Set an error state or show an error message to the user console.error("Error fetching balance information"); } }, [isNativeBalanceError, isTokenBalanceError, isTokenDecimalError]);This will improve the overall error handling and user experience.
Line range hint
1-101: Overall assessment: Improved balance handling with room for further enhancementsThe changes in this file significantly improve the balance fetching and calculation logic, aligning well with the PR objectives. Key improvements include:
- Separation of native and token balance fetching.
- Improved balance calculation using
formatUnits.- Better handling of different token types (native vs. ERC20).
However, there are opportunities for further enhancement:
- Implement more robust error handling for balance fetching operations.
- Enhance the
balanceAmountcalculation to handle loading and error states explicitly.These additional improvements would address the loading state issue mentioned in the PR comments and further enhance the user experience. Overall, the changes represent a significant step forward in improving the component's functionality and reliability.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (5 hunks)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (2 hunks)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx (3 hunks)
🧰 Additional context used
📓 Learnings (1)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:63-64 Timestamp: 2024-06-11T17:14:13.327Z Learning: Errors in the `useContractRead` hook for ERC20 token allowance checks in the `DepositPaymentButton` component are managed by the `wrapWithToast()` function, which logs errors in a notification popup. Additionally, the quantity for the approval is pre-validated and stored in the context of the NewTransactionContext.Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:180-180 Timestamp: 2024-06-11T17:11:32.906Z Learning: The `refetchAllowance` function call is necessary in the `DepositPaymentButton` component to ensure the frontend updates correctly after an approval action.
🔇 Additional comments (13)
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (6)
4-4: LGTM: New imports for enhanced functionalityThe addition of
useReadContractanderc20Abiimports aligns with the implementation of token balance fetching from ERC20 contracts. These changes are consistent with the PR objectives and enhance the component's capabilities.Also applies to: 8-8
26-26: LGTM: Clear distinction for native transactionsThe addition of
isNativeTransactionprovides a clear way to distinguish between native and token transactions. This variable is crucial for the conditional logic in balance fetching and improves the overall readability of the component.
28-30: LGTM: Optimized native balance fetchingThe
useBalancehook has been optimized to only fetch balances for native transactions. This change improves performance by preventing unnecessary API calls for non-native tokens. The conditional address setting is also a good practice.
Line range hint
46-51: LGTM: Clear rendering logic maintainedThe rendering logic remains unchanged and follows the suggestion from the past review comment to avoid nested ternary operators. This implementation is clear and easy to maintain.
Line range hint
1-55: Overall: Well-implemented balance fetching and display logicThe changes in this file effectively address the PR objectives by improving balance fetching for both native and token transactions. The implementation:
- Correctly distinguishes between native and token transactions.
- Efficiently fetches balances using appropriate hooks.
- Handles loading states and potential errors gracefully.
- Maintains clear and maintainable rendering logic.
These improvements enhance the user experience by providing more accurate balance information and preventing actions when funds are insufficient.
41-44: LGTM: Improved balance calculation and formattingThe updated
formattedBalancecalculation is well-implemented. It correctly handles both native and token balances using theisNativeTransactionflag. The use ofuseMemois appropriate for performance optimization.Regarding the concern raised in the PR comments about
insufficientBalancereturning true when data is still loading, this implementation addresses that issue. TheformattedBalancewill beundefinedwhen the data is loading, which is then handled in the rendering logic.To verify this behavior, we can check if there are any other occurrences of
insufficientBalancecalculations in the codebase:✅ Verification successful
LGTM: Verified balance handling for loading states
The
insufficientBalancelogic in bothRaiseDisputeButton.tsxandDepositPaymentButton.tsxcorrectly handles loading states. UI elements appropriately reflect the loading status by disabling actions and showing loading indicators when balance data is not yet available.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for insufficientBalance calculations rg --type typescript 'const\s+insufficientBalance'Length of output: 87
Script:
#!/bin/bash # Search for insufficientBalance calculations in TypeScript files rg 'const\s+insufficientBalance' --glob '*.ts' --glob '*.tsx'Length of output: 317
Script:
#!/bin/bash # Extract context around 'const insufficientBalance' declarations in TypeScript files rg 'const\s+insufficientBalance' -A 5 -B 5 --glob '*.ts' --glob '*.tsx'Length of output: 2540
Script:
#!/bin/bash # Extract usage context of 'insufficientBalance' in the identified TypeScript files rg 'insufficientBalance' -A 10 -B 10 -- 'web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx' 'web/src/pages/MyTransactions/TransactionDetails/PreviewCardButtons/RaiseDisputeButton.tsx'Length of output: 21617
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx (4)
4-4: LGTM: New imports for enhanced balance handlingThe new imports (
useReadContract,useBalance,erc20Abi, andformatUnits) are appropriate for the updated balance fetching and calculation logic. These changes align well with the PR objectives of improving balance checks and error handling.Also applies to: 7-8
83-83: LGTM: Correct update to useEffect dependency arrayAdding
balanceAmountto the dependency array of useEffect is correct. This ensures that the effect re-runs when the balance changes, maintaining consistency between the entered amount and the available balance.
85-88: LGTM: Improved formattedBalance calculationThe new
formattedBalancecalculation is well-implemented. It correctly handles both native and token balances, and the use ofisUndefinedhelps prevent potential errors. This change aligns well with the PR objectives of improving balance checks and formatting.
95-95: LGTM: Correct update to MaxBalance component propsUpdating the
rawBalanceprop to usebalanceAmountis consistent with the new balance calculation logic. This change ensures that the MaxBalance component receives the correctly calculated balance value.web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (3)
20-20: LGTM: New imports for enhanced functionality.The addition of
useBalance,normalize, andClosedCircleIconimports are appropriate for the new features implemented in this component. These imports enable native token balance checking, ENS name normalization, and improved error message display, respectively.Also applies to: 23-23, 29-29
33-41: LGTM: Well-designed error message component.The new
ErrorButtonMessagestyled component is a good addition. It's properly styled for consistent error message display, using theme colors and appropriate spacing. This enhances the user interface for showing balance-related errors.
Line range hint
1-224: LGTM: Significant improvements to deposit payment functionality.Overall, the changes in this file greatly enhance the deposit payment process:
- Improved handling of both native and ERC20 token transactions.
- Implementation of balance checks for better user feedback.
- Clear error messaging for insufficient balance scenarios.
- Enhanced button state management based on transaction type and balance.
These improvements will provide users with a more informative and smoother experience when making deposits. The suggested refinements in previous comments, if implemented, will further optimize the user experience and accessibility.
Great work on these enhancements!
a911019
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Outside diff range and nitpick comments (5)
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (2)
33-39: LGTM: Added token balance fetching from smart contract.The addition of
useReadContractfor fetching token balances is well-implemented. It correctly uses the ERC20 ABI andbalanceOffunction, and is conditionally enabled for non-native transactions.Consider adding a check for
token?.addressbefore enabling the query to prevent potential errors:query: { enabled: !isNativeTransaction && !!token?.address },
Line range hint
1-56: Overall assessment: Well-implemented balance fetching and display logic.The changes in this file significantly improve the
Balancecomponent by:
- Distinguishing between native and token transactions.
- Optimizing balance fetching for both native and token balances.
- Improving the calculation and display of formatted balances.
These improvements align well with the PR objectives of enhancing error handling and user feedback during the transaction process.
Consider extracting the balance fetching logic into a custom hook (e.g.,
useTokenBalance) to improve reusability and separation of concerns. This could simplify theBalancecomponent and make the balance fetching logic more testable and maintainable.web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (3)
62-62: LGTM: Improved ENS resolution and balance fetching.The simplified ENS resolution and the addition of balance fetching for both native and ERC20 tokens are well-implemented. These changes enhance the component's ability to handle different address formats and token types.
Consider adding error handling for the balance fetching:
const { data: tokenBalance, error: tokenBalanceError } = useReadContract({ // ... existing configuration ... }); // Then use tokenBalanceError in your UI to display any errors that occurred during balance fetchingThis addition would provide more robust error handling and improve the user experience in case of balance fetching failures.
Also applies to: 70-83
109-140: LGTM: Enhanced transaction simulation logic.The updated transaction simulation logic, which now includes the
insufficientBalancecheck and separates configurations for native and ERC20 transactions, is well-implemented. These changes prevent unnecessary simulations and improve the overall efficiency of the component.Consider adding a loading state for the simulation:
const [isSimulating, setIsSimulating] = useState(false); // Before each simulation setIsSimulating(true); // After simulation completes or errors setIsSimulating(false);This addition would allow you to show a loading indicator during simulation, enhancing the user experience.
200-219: LGTM: Improved UI feedback for insufficient balance.The UI changes, including the button state considering
insufficientBalanceand the new error message display, significantly improve user feedback. These changes align well with the PR objective of enhancing error handling and user feedback during the transaction process.Consider adding an aria-label to the button for better accessibility:
<StyledButton // ... existing props ... aria-label={insufficientBalance ? "Cannot deposit payment due to insufficient balance" : undefined} />This addition would provide more context to screen reader users about why the button might be disabled.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (5 hunks)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (2 hunks)
- web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx (3 hunks)
🧰 Additional context used
📓 Learnings (1)
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (2)
Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:63-64 Timestamp: 2024-06-11T17:14:13.327Z Learning: Errors in the `useContractRead` hook for ERC20 token allowance checks in the `DepositPaymentButton` component are managed by the `wrapWithToast()` function, which logs errors in a notification popup. Additionally, the quantity for the approval is pre-validated and stored in the context of the NewTransactionContext.Learnt from: kemuru PR: kleros/escrow-v2#60 File: web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx:180-180 Timestamp: 2024-06-11T17:11:32.906Z Learning: The `refetchAllowance` function call is necessary in the `DepositPaymentButton` component to ensure the frontend updates correctly after an approval action.
🔇 Additional comments (11)
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/TokenSelector/TokenItem/Balance.tsx (4)
4-4: LGTM: New imports added for contract interaction.The addition of
useReadContractanderc20Abiimports is appropriate for the new functionality to read token balances from smart contracts.Also applies to: 8-8
26-26: LGTM: Improved transaction type detection.The addition of
isNativeTransactionenhances code clarity by providing a clear distinction between native and token transactions.
28-30: LGTM: Optimized native balance fetching.The conditional enabling of
useBalancebased onisNativeTransactionis an excellent optimization. It prevents unnecessary API calls for token transactions, potentially improving performance.
41-44: LGTM: Improved balance calculation and display logic.The updated
formattedBalancecalculation correctly handles both native and token balances. TheuseMemodependencies are properly updated, ensuring the value is recalculated when necessary.Regarding the past comment about nested ternary operators, the current implementation already follows the suggested structure, avoiding nested ternaries. This improves readability and maintainability as requested.
Also applies to: 47-50
web/src/pages/NewTransaction/Terms/Payment/GeneralTransaction/TokenAndAmount/index.tsx (4)
4-4: LGTM: Import statements updated correctlyThe new imports (
useReadContract,useBalance,erc20Abi, andformatUnits) are appropriate for the updated balance fetching and formatting logic implemented in this component.Also applies to: 7-8
83-83: LGTM: Dependency array updated correctlyAdding
balanceAmountto the dependency array of theuseEffecthook is correct. This ensures that the effect runs when the balance changes, which is crucial for accurate error handling and balance sufficiency checks.
85-88: LGTM: Formatted balance calculation improvedThe new
formattedBalancecalculation usinguseMemois well-implemented. It correctly handles both native and token balances, and the use ofisUndefinedfor type checking is appropriate. This change improves the accuracy and efficiency of balance formatting.
100-100: LGTM: Empty line added at end of fileAdding an empty line at the end of the file is a common best practice for file formatting. This change improves consistency and adheres to standard coding conventions.
web/src/pages/NewTransaction/NavigationButtons/DepositPaymentButton.tsx (3)
20-20: LGTM: New imports and styled component for error handling.The addition of
useBalance,normalize, andClosedCircleIconimports, along with the newErrorButtonMessagestyled component, aligns well with the PR objective of improving error handling and user feedback. These changes provide the necessary tools to implement balance checks and display error messages effectively.Also applies to: 23-23, 29-29, 33-41
96-97: LGTM: Improved allowance checking efficiency.The modification to the allowance checking logic, which now considers the
insufficientBalancestate, is a good optimization. This ensures that allowance checks are only performed when necessary, improving the overall efficiency of the component.Also applies to: 100-100
150-151: LGTM: Optimized approve configuration.The modification to the approve configuration, which now considers the
insufficientBalancestate, is a good optimization. This ensures that approval checks are only performed when necessary, improving the overall efficiency of the component.
|
|
||
| const isNativeTransaction = sendingToken?.address === "native"; | ||
|
|
||
| const { data: nativeBalance } = useBalance({ | ||
| query: { enabled: isNativeTransaction }, | ||
| address: address as `0x${string}`, | ||
| }); | ||
|
|
||
| const { data: tokenBalance } = useReadContract({ | ||
| query: { enabled: !isNativeTransaction }, | ||
| address: sendingToken?.address as `0x${string}`, | ||
| abi: erc20Abi, | ||
| functionName: "balanceOf", | ||
| args: [address as `0x${string}`], | ||
| }); | ||
|
|
||
| const { data: tokenDecimal } = useReadContract({ | ||
| query: { enabled: !isNativeTransaction }, | ||
| address: sendingToken?.address as `0x${string}`, | ||
| abi: erc20Abi, | ||
| functionName: "decimals", | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Enhance balance fetching logic with consistent error handling
The separation of native and token balance fetching is a good improvement. However, consider the following enhancements:
- Use the
enabledoption consistently across all hooks to prevent unnecessary API calls. - Implement error handling for both native and token balance fetching.
Here's a suggested implementation:
const isNativeTransaction = sendingToken?.address === "native";
const { data: nativeBalance, isError: isNativeBalanceError } = useBalance({
address: isNativeTransaction ? address as `0x${string}` : undefined,
enabled: isNativeTransaction && Boolean(address),
});
const { data: tokenBalance, isError: isTokenBalanceError } = useReadContract({
address: !isNativeTransaction ? sendingToken?.address as `0x${string}` : undefined,
abi: erc20Abi,
functionName: "balanceOf",
args: [address as `0x${string}`],
enabled: !isNativeTransaction && Boolean(sendingToken?.address) && Boolean(address),
});
const { data: tokenDecimal, isError: isTokenDecimalError } = useReadContract({
address: !isNativeTransaction ? sendingToken?.address as `0x${string}` : undefined,
abi: erc20Abi,
functionName: "decimals",
enabled: !isNativeTransaction && Boolean(sendingToken?.address),
});
// Handle errors
useEffect(() => {
if (isNativeBalanceError || isTokenBalanceError || isTokenDecimalError) {
// Set an error state or show an error message to the user
console.error("Error fetching balance information");
}
}, [isNativeBalanceError, isTokenBalanceError, isTokenDecimalError]);This approach will improve error handling and prevent unnecessary API calls when required data is missing.
| const balanceAmount = useMemo(() => { | ||
| if (isNativeTransaction) { | ||
| return nativeBalance ? parseFloat(formatUnits(nativeBalance.value, nativeBalance.decimals)) : 0; | ||
| } else { | ||
| return tokenBalance && tokenDecimal ? parseFloat(formatUnits(tokenBalance, tokenDecimal)) : 0; | ||
| } | ||
| }, [isNativeTransaction, nativeBalance, tokenBalance, tokenDecimal]); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Enhance balance calculation to handle loading and error states
The balanceAmount calculation is improved, but it doesn't fully address the loading state issue mentioned in the PR comments. To enhance user experience and error handling, consider implementing a tri-state approach:
const balanceAmount = useMemo(() => {
if (isNativeBalanceError || isTokenBalanceError || isTokenDecimalError) {
return { state: 'error', value: null };
}
if (isNativeTransaction) {
return nativeBalance === undefined
? { state: 'loading', value: null }
: { state: 'success', value: parseFloat(formatUnits(nativeBalance.value, nativeBalance.decimals)) };
} else {
return tokenBalance === undefined || tokenDecimal === undefined
? { state: 'loading', value: null }
: { state: 'success', value: parseFloat(formatUnits(tokenBalance, tokenDecimal)) };
}
}, [isNativeTransaction, nativeBalance, tokenBalance, tokenDecimal, isNativeBalanceError, isTokenBalanceError, isTokenDecimalError]);This approach allows you to handle loading, error, and success states explicitly in your UI, providing a better user experience and addressing the concern about showing incorrect balance information during loading.
| rawBalance={parseFloat(balanceData?.formatted)} | ||
| setQuantity={setQuantity} | ||
| /> | ||
| <MaxBalance rawBalance={balanceAmount} {...{ setQuantity, formattedBalance }} /> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Update MaxBalance component to handle new balance states
After implementing the tri-state balance calculation suggested earlier, update this line to handle the new balance structure:
<MaxBalance
rawBalance={balanceAmount.state === 'success' ? balanceAmount.value : null}
isLoading={balanceAmount.state === 'loading'}
isError={balanceAmount.state === 'error'}
{...{ setQuantity, formattedBalance }}
/>This change will ensure that the MaxBalance component can properly handle loading and error states, improving the user experience.
PR-Codex overview
This PR focuses on enhancing error handling, improving balance checks, and refining the user interface for transaction buttons in a payment system. It introduces better state management for loading and error conditions across various components.
Detailed summary
getTokenLogoto handle potentialundefinedvalues.StyledQuantitybased onarbitrationCost.getFormattedBalance.Balancecomponent to differentiate between native and token balances.insufficientBalancechecks inRaiseDisputeButtonandDepositPaymentButton.TokenAndAmountand related components.Summary by CodeRabbit
New Features
Bug Fixes