Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix: base max fee + hw wallet shaded area #565

Merged
merged 3 commits into from
Dec 4, 2024
Merged

Conversation

kvhnuke
Copy link
Contributor

@kvhnuke kvhnuke commented Nov 21, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced handling of Ethereum transactions with improved fee calculation methods.
    • Streamlined transaction finalization process, supporting both legacy and fee market transactions.
    • Updated Solana token info retrieval with a new source and extended cache duration for improved data freshness.
  • Bug Fixes

    • Improved accuracy in gas cost estimations by utilizing finalized transaction data.
  • Style

    • Updated the layout of swap error and loading components for better responsiveness.
    • Simplified markup in the swap best offer component by removing unnecessary inline styles.

Copy link

coderabbitai bot commented Nov 21, 2024

Walkthrough

The changes made in the Transaction class of the Ethereum transaction handling library enhance the management of Ethereum transactions, particularly in fee calculations. The getOPfees method has been updated to directly accept a finalized transaction object, improving fee estimation. The finalizeTransaction method now returns an additional property, finalizedTransaction, which simplifies the handling of different transaction types. Additionally, the getGasCosts method has been adjusted to utilize this finalized transaction for accurate fee calculations. Overall, the modifications improve clarity and efficiency in transaction processing.

Changes

File Path Change Summary
packages/extension/src/providers/ethereum/libs/transaction/index.ts - Updated getOPfees method to accept `LegacyTransaction
packages/extension/src/ui/action/views/swap/components/swap-error/index.vue - Altered height of .swap-looking__container from 600px to 100% for flexible layout.
- Retained conditional rendering for error messages and animations.
packages/extension/src/ui/action/views/swap/components/swap-loading/index.vue - Changed height of .swap-looking__container from 600px to 100% for responsive design.
- Maintained structure and functionality of the component.
packages/extension/src/ui/action/views/swap/views/swap-best-offer/index.vue - Removed inline style for width from <hardware-wallet-msg> component, simplifying markup while retaining conditional rendering based on account.
packages/extension/src/providers/ethereum/libs/transaction/gas-utils.ts - Modified getMinPriorityFee to return a higher minimum priority fee, changing it from 0.1 gwei to 1 gwei.
packages/extension/src/providers/solana/libs/api.ts - Updated URL in getTokenInfo method for fetching Solana token list.
- Changed cache duration for token list fetch from 1 hour to 6 hours.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Transaction
    participant FeeCalculator

    User->>Transaction: Request to finalize transaction
    Transaction->>Transaction: Process transaction
    Transaction->>Transaction: Determine transaction type
    Transaction->>Transaction: Return finalizedTransaction
    User->>FeeCalculator: Request operational fees
    FeeCalculator->>Transaction: Get OP fees with finalizedTransaction
    Transaction->>FeeCalculator: Return calculated fees
Loading

Possibly related PRs


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

Documentation and Community

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

Copy link

github-actions bot commented Nov 21, 2024

💼 Build Files
chrome: enkrypt-chrome-d1b8c83f.zip
firefox: enkrypt-firefox-d1b8c83f.zip

💉 Virus total analysis
chrome: d1b8c83f
firefox: d1b8c83f

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between abf56be and 4e7071a.

📒 Files selected for processing (1)
  • packages/extension/src/providers/ethereum/libs/transaction/index.ts (7 hunks)
🔇 Additional comments (3)
packages/extension/src/providers/ethereum/libs/transaction/index.ts (3)

175-178: Set defaultHardfork dynamically based on network conditions

Hardcoding defaultHardfork to Hardfork.London may not be suitable for all networks, especially those that have progressed beyond the London hardfork. This could lead to incompatibilities when broadcasting transactions on networks with different hardforks.

Consider retrieving the latest supported hardfork dynamically:

 const common = Common.custom({
   chainId: BigInt(this.tx.chainId),
-  defaultHardfork: Hardfork.London,
+  defaultHardfork: await this.getNetworkHardfork(),
 });

And implement the getNetworkHardfork method to fetch the appropriate hardfork based on the network:

async getNetworkHardfork(): Promise<Hardfork> {
  const networkId = await this.web3.net.getId();
  // Map network IDs to their respective hardforks.
  // Implement the logic based on the network specifications.
  // For example:
  // if (networkId === 1) return Hardfork.Merge;
  // Add mappings for other networks as needed.
}

126-134: Ensure consistent handling of BigInt conversion for chainId

Converting this.tx.chainId to BigInt is necessary for the Common configuration. Verify that this.tx.chainId is always a number or a value compatible with BigInt to prevent potential runtime errors.

Run the following script to check all occurrences of chainId assignments and ensure they are compatible with BigInt:

✅ Verification successful

Based on the search results, I can now provide a final response:

chainId conversion to BigInt is safe in this context

The codebase consistently handles chainId as string values in hexadecimal format (e.g., '0x1', '0x5') through the Ethereum provider interfaces and transaction types. The conversion to BigInt at the specific location is safe because:

  • The EthereumTransaction interface explicitly types chainId as `0x${string}`, ensuring it's always a hex string
  • All chainId assignments in the codebase use either numeric strings or hex strings, which are valid BigInt inputs
  • The conversion is only used for the Common.custom() configuration, which requires a BigInt type as per the ethereum library requirements
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all assignments to `chainId` and check their types.

# Search for assignments to `chainId` in the codebase.
rg --type-add 'typescript' --files | xargs grep -E "chainId\s*[:=]"

# Check for any non-numeric assignments.
rg --type-add 'typescript' --files | xargs grep -E "chainId\s*[:=]\s*['\"]"

Length of output: 265


Script:

#!/bin/bash
# Search for chainId assignments and usage in typescript files
rg "chainId\s*[:=]" --type ts -A 2

# Search for chainId type definitions
ast-grep --pattern 'interface $_ {
  $$$
  chainId: $_
  $$$
}'

# Search for chainId parameter in function signatures
ast-grep --pattern 'function $_($$$ chainId: $_ $$$) {
  $$$
}'

Length of output: 27583


235-266: Verify that finalizedTransaction is correctly obtained in getGasCosts

In the getGasCosts method, ensure that finalizedTransaction is properly returned from finalizeTransaction. Any issues in obtaining finalizedTransaction could affect fee calculations, especially for networks like Optimism where opFee is added.

Run the following script to check for any inconsistencies in the use of finalizedTransaction:

✅ Verification successful

Let me gather more information about the finalizeTransaction implementation and its usage.


Let me check the actual implementation of finalizeTransaction and its return type definitions.


Let me check the usage of finalizedTransaction in the getOPfees method since it's used in the error case.


Based on the gathered information, I can now provide a final response:

finalizedTransaction is correctly obtained and used in getGasCosts

The code correctly obtains finalizedTransaction from finalizeTransaction method, which returns a properly typed object containing either a LegacyTransaction or FeeMarketEIP1559Transaction. The getOPfees method correctly uses this transaction object to calculate Optimism L1 fees by serializing the transaction and calling the price oracle contract. The implementation shows proper error handling and type safety throughout the flow.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for all usages of `finalizedTransaction` to ensure it's properly obtained and used.

rg --type=ts --pcre2 "(const|let|var)\s+\{[^}]*finalizedTransaction[^}]*\}\s+=\s+await\s+this\.finalizeTransaction"

Length of output: 263


Script:

#!/bin/bash
# Search for the implementation of finalizeTransaction
ast-grep --pattern 'finalizeTransaction($$$) {
  $$$
}'

# Also check for the interface or type definition
rg --type=ts "finalizeTransaction.*:" -A 3

Length of output: 549


Script:

#!/bin/bash
# Get the implementation of finalizeTransaction
rg --type=ts -A 30 "async finalizeTransaction\("

# Get the type definitions
rg --type=ts "type FinalizedFeeMarketEthereumTransaction|type FinalizedLegacyEthereumTransaction" -A 5

Length of output: 3517


Script:

#!/bin/bash
# Search for getOPfees implementation and its usage of finalizedTransaction
rg --type=ts "getOPfees.*\(" -A 10

# Also check the type definitions for the transaction types used
rg --type=ts "type LegacyTransaction|type FeeMarketEIP1559Transaction" -A 5

Length of output: 3657

@NickKelly1 NickKelly1 self-requested a review November 21, 2024 23:36
@kvhnuke kvhnuke changed the title fix: base max fee fix: base max fee + hw wallet shaded area Nov 21, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
packages/extension/src/ui/action/views/swap/views/swap-best-offer/index.vue (3)

Line range hint 386-386: Address the "problem" comment in swap execution

There's a comment indicating a known issue in the swap execution logic. This needs to be properly documented or resolved.

Would you like me to help investigate the potential issues in the swap execution logic or create a GitHub issue to track this?


Line range hint 386-434: Enhance error handling in swap execution

The error handling in the swap execution could be improved:

  1. Replace generic console.error with structured logging
  2. Add specific error handling for different network types
  3. Sanitize error messages before displaying to users

Consider refactoring the error handling:

-      .catch(err => {
-        console.error(err);
-        isTXSendError.value = true;
-        TXSendErrorMessage.value = err.error ? err.error.message : err.message;
+      .catch(err => {
+        const errorContext = {
+          network: network.value?.name,
+          provider: pickedTrade.value?.provider,
+          errorType: err.name
+        };
+        console.error('Swap execution failed:', errorContext, err);
+        isTXSendError.value = true;
+        // Sanitize error message for user display
+        TXSendErrorMessage.value = getSanitizedErrorMessage(err);

Line range hint 196-208: Improve warning system configuration

The warning system uses hardcoded values and could benefit from:

  1. Moving magic numbers to configuration
  2. Adding documentation for warning thresholds
  3. Preparing for internationalization

Consider refactoring:

+const PRICE_DIFFERENCE_THRESHOLD = -0.2; // 20% price impact threshold
+const WARNING_CONFIG = {
+  PRICE_DIFFERENCE_THRESHOLD,
+  // Add other warning thresholds here
+};

-  if (1 - Number(swapData.priceDifference) < -0.2) {
+  if (1 - Number(swapData.priceDifference) < WARNING_CONFIG.PRICE_DIFFERENCE_THRESHOLD) {
     warning.value = SwapBestOfferWarnings.BAD_PRICE;
     return;
   }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4e7071a and aa5c165.

📒 Files selected for processing (3)
  • packages/extension/src/ui/action/views/swap/components/swap-error/index.vue (1 hunks)
  • packages/extension/src/ui/action/views/swap/components/swap-loading/index.vue (1 hunks)
  • packages/extension/src/ui/action/views/swap/views/swap-best-offer/index.vue (1 hunks)
🔇 Additional comments (3)
packages/extension/src/ui/action/views/swap/components/swap-loading/index.vue (1)

87-87: LGTM! Height change improves responsiveness.

The change from fixed height to 100% makes the component more flexible and responsive. Since this is a loading overlay, full viewport height is appropriate.

Let's verify the component's behavior across different viewport sizes:

✅ Verification successful

Height change is safe and consistent with parent components

The verification shows that the parent components (swap-best-offer/index.vue and index.vue) both use height: 100% and have proper height constraints:

  • The main swap view sets a base height of 600px
  • The best offer view uses height: 100% with calculated internal spacing
  • Other loading/error components in the same directory also use height: 100% consistently

This confirms that the loading component's switch to height: 100% is well-supported by its parent container structure and follows the established pattern for overlay components in this view.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential viewport/responsive issues
# Look for any media queries or responsive styles that might affect this component
rg -g '*.vue' -g '*.less' "height:|@media" ./packages/extension/src/ui/action/views/swap/

Length of output: 11791

packages/extension/src/ui/action/views/swap/components/swap-error/index.vue (1)

133-133: LGTM! Improved responsive design.

The change from fixed height to 100% makes the component more flexible and responsive. Since this is a modal overlay component, using 100% height is the correct approach.

Let's verify this change doesn't affect the component's appearance in different scenarios:

✅ Verification successful

LGTM! The height change is safe and aligns with the design.

The change from fixed height to 100% in the swap-error component is correct since:

  1. The parent component .swap-looking__container is positioned fixed and covers the full viewport
  2. The component is used as a modal overlay, where 100% height is the standard approach
  3. No other components rely on its fixed height
  4. The change aligns with other responsive modal components in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other components that might rely on the fixed height
# Look for any explicit height references or related styling

# Search for any components that might be importing or using this component
rg -l "swap-error"

# Look for related height definitions that might need similar updates
rg "height: 600px" --type css --type vue

Length of output: 143


Script:

#!/bin/bash
# Search for any components that might be importing or using this component
# Using proper file type for Vue files
rg -l "swap-error" --type-add 'vue:*.vue' --type vue

# Look for related height definitions that might need similar updates
rg "height: 600px" --type-add 'vue:*.vue' --type vue

# Check the parent component to understand the layout context
cat "packages/extension/src/ui/action/views/swap/index.vue"

Length of output: 33589

packages/extension/src/ui/action/views/swap/views/swap-best-offer/index.vue (1)

14-14: Verify hardware wallet message component styling

The removal of inline width style (90%) from hardware-wallet-msg component could affect its layout. Ensure that the component's width is properly controlled through CSS classes.

✅ Verification successful

Let me search for the styling of the hardware-wallet-msg component to verify if the width is properly handled.


Let me check the referenced styles to verify how the component's width is handled.


Let me check the actual content of the verify-transaction styles to see how the hardware wallet message component is styled.


Based on the code analysis, I can now provide the final response:

Removal of inline width style is safe and follows proper styling

The hardware wallet message component's width is properly controlled through the CSS class provider-verify-transaction__block which sets width: 100% and includes appropriate padding and margins. The removal of the inline style width: 90% is actually an improvement as it:

  1. Follows the component's built-in responsive design
  2. Maintains consistency with other instances of the component across the codebase
  3. Relies on the proper CSS cascade through class-based styling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the width is handled in component's CSS or parent styles
rg -g '*.vue' -g '*.less' -g '*.css' 'hardware-wallet-msg' -A 5 -B 5

Length of output: 37473


Script:

#!/bin/bash
# Check the hardware-wallet-msg component's styling
rg -g '*.vue' -g '*.less' -g '*.css' 'hardware-wallet-msg' -A 10 -B 10 --context-separator="---" | grep -A 10 -B 10 "style\|class"

# Look for the actual component file to check its internal styling
fd -e vue "hardware-wallet-msg.vue" | xargs cat

Length of output: 50258


Script:

#!/bin/bash
# Check the styles in the referenced less files
cat << 'EOF' | xargs -I {} sh -c 'echo "=== {} ==="; cat {} 2>/dev/null || true'
@action/styles/theme.less
@/providers/ethereum/ui/styles/common-popup.less
@/providers/common/ui/verify-transaction/styles/verify-transaction.less
EOF

# Find any other relevant style files
fd -e less "verify-transaction.less|common-popup.less"

Length of output: 883


Script:

#!/bin/bash
# Check the content of verify-transaction.less files
cat packages/extension/src/providers/common/ui/styles/verify-transaction.less
echo "---"
cat packages/extension/src/providers/bitcoin/ui/styles/verify-transaction.less
echo "---"
cat packages/extension/src/providers/ethereum/ui/styles/common-popup.less

Length of output: 23768

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
packages/extension/src/providers/solana/libs/api.ts (1)

67-67: Consider using a specific tag/commit instead of master branch.

While using Solflare's token list is a good choice, referencing the master branch directly could lead to unexpected changes. Consider using a specific tag or commit hash for better stability and predictability.

Example URL format:

-'https://raw.githubusercontent.com/solflare-wallet/token-list/refs/heads/master/solana-tokenlist.json'
+'https://raw.githubusercontent.com/solflare-wallet/token-list/<specific-commit-or-tag>/solana-tokenlist.json'
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between aa5c165 and d1b8c83.

📒 Files selected for processing (2)
  • packages/extension/src/providers/ethereum/libs/transaction/gas-utils.ts (1 hunks)
  • packages/extension/src/providers/solana/libs/api.ts (2 hunks)
🔇 Additional comments (2)
packages/extension/src/providers/solana/libs/api.ts (1)

77-77: Verify the impact of increased cache duration.

The increase in cache duration from 1 hour to 6 hours is reasonable for token lists, but let's verify if this affects any time-sensitive features.

✅ Verification successful

Based on the search results, I can now generate the final response:

The 6-hour cache duration for token info is safe to implement

The token info cache is primarily used for:

  • Displaying token details (name, symbol, decimals) in transaction decoding
  • Asset watching/listing functionality
  • Balance display

These use cases are not time-sensitive as:

  • Token metadata (name, symbol, decimals) rarely changes
  • No swap-related code directly depends on this cached data
  • Critical operations like swaps use separate APIs and price feeds
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any code that might depend on fresh token info updates

# Look for references to getTokenInfo that might need fresh data
rg -A 5 "getTokenInfo" --type ts

# Check for any swap-related code that might need fresh token data
rg -A 5 "swap.*token" --type ts

Length of output: 11226

packages/extension/src/providers/ethereum/libs/transaction/gas-utils.ts (1)

65-65: Significant increase in minimum priority fee.

The minimum priority fee has been increased from 0.1 gwei to 1 gwei (10x increase). While this change is reasonable given current network conditions and helps prevent stuck transactions, it will increase the base transaction costs across all fee types.

Let's verify the impact on transaction costs across different fee types:

✅ Verification successful

Based on the search results, I can now provide a conclusive verification of the review comment. The getMinPriorityFee function is used in several critical paths within the gas-utils.ts file:

  1. As a fallback when fee is zero: if (fee.eqn(0)) return getMinPriorityFee();
  2. As a fallback when gas fee history is empty: if (gasFeeHistory.blocks.length === 0) return getMinPriorityFee();
  3. As a default case in the gas price type switch statement

Let's verify if there are any gas fee calculations or tests that might be affected by this change:


Minimum priority fee increase is safe and localized

The change to increase the minimum priority fee from 0.1 to 1 gwei is safe because:

  • The getMinPriorityFee function is only used within gas-utils.ts as a fallback mechanism
  • It's used in three specific scenarios: when fee is zero, when gas fee history is empty, or as a default case
  • No other files in the codebase directly use the gwei calculations or have hardcoded assertions about priority fees
  • The change provides a more realistic floor value that helps prevent stuck transactions in current network conditions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for references to getMinPriorityFee to understand usage impact

# Find direct usage of getMinPriorityFee
echo "Direct usage of getMinPriorityFee:"
rg "getMinPriorityFee" -A 3

# Find related test files that might need updates
echo -e "\nRelated test files:"
fd -e test.ts -e spec.ts | xargs rg "priority.*fee" -l

Length of output: 1779


Script:

#!/bin/bash
# Search for gas fee calculations and tests
echo "Files with gas fee calculations:"
rg -l "toWei.*gwei" 

echo -e "\nGas fee test assertions:"
rg "assert.*gwei" -A 2

Length of output: 258

@kvhnuke kvhnuke changed the base branch from develop to prep/release December 4, 2024 18:59
@kvhnuke kvhnuke merged commit 969ea9c into prep/release Dec 4, 2024
4 checks passed
@kvhnuke kvhnuke deleted the fix/base-max-fee branch December 4, 2024 19:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants