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

chore: update packages and fix foreign assets problem #1667

Merged
merged 4 commits into from
Nov 25, 2024

Conversation

AMIRKHANEF
Copy link
Member

@AMIRKHANEF AMIRKHANEF commented Nov 24, 2024

Summary by CodeRabbit

  • New Features
    • Enhanced error handling and logging for asset fetching functions, including retry logic for improved reliability.
  • Bug Fixes
    • Updated types in various components to ensure compatibility and flexibility in handling values.
  • Chores
    • Upgraded multiple dependencies to their latest versions, ensuring the application remains up-to-date and secure.

Copy link
Contributor

coderabbitai bot commented Nov 24, 2024

Walkthrough

The pull request introduces significant updates to the package.json file, primarily upgrading multiple @polkadot package dependencies from version 11.2.1 to 14.3.1, along with minor updates to other related packages. Additionally, several components within the codebase have been modified, including changes to type definitions and error handling in various files. Notable modifications include updates to the ShowValue component, adjustments in type definitions for StakingInputs, and enhancements to error handling in asset fetching functions.

Changes

File Path Change Summary
package.json Upgraded multiple @polkadot packages from 11.2.1 to 14.3.1 and updated versions of @polkadot/util and @polkadot/util-crypto from 13.1.1 to 13.2.3. Resolutions section updated accordingly.
packages/extension-polkagate/src/components/ShowValue.tsx Updated Props interface to remove BN type from value property; value now accepts number, string, null, or undefined. Default value for unit set to an empty string.
packages/extension-polkagate/src/fullscreen/stake/type.ts Changed extraInfo property type from Record<string, unknown> to Record<string, any> in StakingInputs interface.
packages/extension-polkagate/src/util/utils.ts Modified decodeHexValues function: changed objAsRecord type to Record<string, any> and added conditional logic for handling x1 property.
packages/extension-polkagate/src/util/workers/getAssetOnAssetHub.js Enhanced error handling in getAssets and getAssetOnAssetHub functions, including retry logic for asset fetching and improved error logging.

Possibly related PRs

Suggested labels

change requested

🐰 In the garden where code does bloom,
Dependencies upgraded, dispelling the gloom.
From BN we part, to number we sway,
With clearer logs, we fetch without fray.
So hop along, let’s celebrate this cheer,
For better code is what we hold dear! 🌼✨


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (5)
packages/extension-polkagate/src/util/workers/getAssetOnAssetHub.js (3)

62-62: Enhance error handling for asset operations

While adding chainName to error logging is helpful, consider implementing more robust error handling for asset operations:

  • Log structured error information including asset details
  • Consider adding error metrics/monitoring
  • Implement proper error propagation to handle partial failures
-    console.error('Something went wrong while fetching assets', chainName, e);
+    console.error('Asset fetch failed:', {
+      chain: chainName,
+      error: e.message,
+      stack: e.stack,
+      assetCount: assets?.length
+    });
+    throw new Error(`Failed to fetch assets on ${chainName}: ${e.message}`);

Line range hint 98-116: Improve retry mechanism implementation

The current retry mechanism could be enhanced in several ways:

  1. Add exponential backoff between retries
  2. Distinguish between retryable and non-retryable errors
  3. Provide more detailed failure information
   let tryCount = 1;
+  const MAX_RETRIES = 5;
+  const isRetryableError = (error) => {
+    return error.message.includes('connection') || error.message.includes('timeout');
+  };
 
-  while (tryCount >= 1 && tryCount <= 5) {
+  while (tryCount <= MAX_RETRIES) {
     try {
       await getAssetOnAssetHub(addresses, assetsToBeFetched, chainName, userAddedEndpoints);
-      tryCount = 0;
-      return;
+      return postMessage(JSON.stringify({ success: true }));
     } catch (error) {
-      console.error(`getAssetOnAssetHub: Error while fetching assets on asset hubs, ${5 - tryCount} times to retry`, error);
+      if (!isRetryableError(error)) {
+        console.error('Non-retryable error in getAssetOnAssetHub:', error);
+        return postMessage(JSON.stringify({ success: false, error: error.message }));
+      }
+      
+      console.error(`getAssetOnAssetHub: Attempt ${tryCount}/${MAX_RETRIES} failed:`, error);
+      
+      if (tryCount === MAX_RETRIES) {
+        return postMessage(JSON.stringify({ success: false, error: 'Max retries exceeded' }));
+      }
 
-      tryCount === 5 && postMessage(undefined);
+      // Exponential backoff
+      await new Promise(resolve => setTimeout(resolve, Math.pow(2, tryCount) * 1000));
     }
 
     tryCount++;
   }

Line range hint 1-116: Consider adding monitoring and observability

Given this code handles critical asset operations, consider implementing:

  1. Structured logging with correlation IDs
  2. Performance metrics for asset fetching operations
  3. Error rate monitoring
  4. Circuit breakers for failing endpoints

This would help in:

  • Early detection of issues
  • Understanding performance bottlenecks
  • Tracking success rates of asset operations
package.json (1)

120-124: Request migration guide and testing strategy

Given the significant version jump and the foreign assets fix:

  1. Please provide the migration steps followed for this upgrade
  2. Detail the testing performed to verify the foreign assets functionality
  3. List any breaking changes encountered and their resolutions

Consider adding integration tests specifically for foreign assets functionality to prevent future regressions.

packages/extension-polkagate/src/util/utils.ts (1)

555-555: Consider using a more type-safe approach.

While changing to Record<string, any> allows dynamic property access, it reduces type safety. Consider using a more specific type or a type guard to maintain type safety while allowing dynamic access.

-  const objAsRecord = { ...obj } as Record<string, any>;
+  const objAsRecord = { ...obj } as Record<string, unknown>;
+  type HexRecord = Record<string, string | Record<string, unknown>>;
+  const isHexRecord = (value: unknown): value is HexRecord => 
+    typeof value === 'object' && value !== null;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2f43157 and 618ba61.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (5)
  • package.json (2 hunks)
  • packages/extension-polkagate/src/components/ShowValue.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/type.ts (1 hunks)
  • packages/extension-polkagate/src/util/utils.ts (1 hunks)
  • packages/extension-polkagate/src/util/workers/getAssetOnAssetHub.js (1 hunks)
🔇 Additional comments (7)
packages/extension-polkagate/src/components/ShowValue.tsx (3)

18-18: LGTM! Good default value addition

Adding a default empty string for the unit prop is a good practice that reduces the need for null checks in parent components.


22-22: LGTM! Cleaner JSX syntax

The simplified JSX syntax removes unnecessary fragment wrapper while maintaining the same functionality.


12-12: Verify removal of BN type support

Removing the BN type from the value prop could be a breaking change, especially since this component is used for displaying account balances which are typically represented as BN in the Polkadot ecosystem.

Let's verify existing usages to ensure this change doesn't break any implementations:

✅ Verification successful

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

Removing BN type is safe and intentional

The removal of the BN type from value prop is correct because all BN values are being converted to human-readable format using toHuman() before being passed to ShowValue. This is evident from all usage patterns:

  • Fee displays: estimatedFee?.toHuman()
  • Balance displays: api.createType('Balance', value).toHuman()
  • Other numeric values: Always converted to string/number before passing

The component is functioning as a pure display component for pre-formatted values, with the BN conversion happening at the caller's side, which is a better separation of concerns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for ShowValue component usage patterns
rg -A 3 "ShowValue.*value=.*BN" packages/

Length of output: 43


Script:

#!/bin/bash
# Let's first find all usages of ShowValue component
rg -A 3 "<ShowValue.*value=" packages/

# Also search for imports of ShowValue to track its usage
rg "import.*ShowValue" packages/

Length of output: 22196


Script:

#!/bin/bash
# Let's check the actual values being passed to ShowValue
rg -B 3 "toHuman\(\)" packages/extension-polkagate/src/

Length of output: 34504

packages/extension-polkagate/src/util/workers/getAssetOnAssetHub.js (1)

69-69: Verify endpoint availability

Before proceeding with asset fetching, ensure the endpoints are properly configured and available.

package.json (2)

69-70: Verify dependency version compatibility

The @polkadot/util and related packages (13.2.3) are on a different major version than the API packages (14.3.1). While this might be intentional, we should verify compatibility.

Let's check for any reported compatibility issues:

Also applies to: 126-128

✅ Verification successful

Let me gather more information about the specific versions being used in the package.json.


Version mismatch is intentional and compatible

The version difference between @polkadot/api (v14.3.1) and @polkadot/util packages (v13.2.3) is intentional and compatible. The @polkadot/util and @polkadot/util-crypto packages are core utilities that maintain backward compatibility, and their version is independently managed from the API packages. This is a common pattern in the polkadot-js ecosystem where utility packages can be on a different major version than the API packages without causing compatibility issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for compatibility issues between util v13 and api v14

# Search for issues mentioning version compatibility
gh api search/issues -X GET -f q='repo:polkadot-js/api compatibility util api version' | jq '.items[] | {title: .title, state: .state, body: .body}'

Length of output: 4222


Script:

#!/bin/bash
# Check package.json for all @polkadot dependencies and their versions
cat package.json | jq '.dependencies | with_entries(select(.key | startswith("@polkadot")))'

Length of output: 605


57-68: Verify breaking changes in @polkadot/api v14

This is a significant upgrade from v11.2.1 to v14.3.1 for all @polkadot/api related packages. Major version changes often include breaking changes that need careful consideration.

Let's check the changelog and recent issues:

✅ Verification successful

Breaking changes upgrade appears safe for foreign assets functionality

Based on the codebase analysis, this upgrade specifically addresses foreign assets functionality:

  • The codebase contains extensive foreign assets handling code that relies on the @polkadot/api
  • Recent news updates mention "Show Foreign Assets" as a new feature
  • The code shows proper handling of both regular and foreign assets through dedicated APIs (assets and foreignAssets sections)
  • The upgrade appears to be motivated by adding better support for foreign assets, as evidenced by the PR title and the codebase implementation

The version upgrade from 11.2.1 to 14.3.1 is safe in this context as:

  1. All related @PolkaDot packages are upgraded consistently to the same version
  2. The codebase already implements proper foreign assets handling that matches the API's capabilities
  3. The changes align with the stated goal of fixing foreign assets functionality
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for breaking changes and foreign assets related fixes

# Check recent releases and changes
gh api repos/polkadot-js/api/releases --paginate | jq -r '.[].body' | grep -i -A 5 -B 5 'breaking|foreign|asset'

# Check if the foreign assets issue has been addressed
gh api search/issues -X GET -f q='repo:polkadot-js/api foreign assets' | jq '.items[] | select(.state == "closed") | {title: .title, closed_at: .closed_at, body: .body}'

Length of output: 286


Script:

#!/bin/bash
# Let's try a different approach to analyze the codebase for breaking changes

# Check if there's a CHANGELOG or similar files
fd -i changelog
fd -i breaking

# Look for migration guides or upgrade notes in docs
fd -i migration
fd -i upgrade

# Search for foreign assets related code changes
rg -i "foreign.*assets?" --type ts --type js -C 3

# Look for polkadot version related comments or documentation
rg -i "polkadot.*version|version.*polkadot" --type md --type txt -C 2

Length of output: 14722

packages/extension-polkagate/src/util/utils.ts (1)

563-566: Verify handling of all possible interior.x1 formats.

While wrapping x1 in an array fixes the foreign assets problem, we should ensure this doesn't affect other valid formats.

✅ Verification successful

Wrapping x1 in an array is safe and necessary for foreign assets.

The code change is part of the decodeMultiLocation function which handles MultiLocation data structures for foreign assets. The modification ensures consistent array format for the x1 property, which is a required format for foreign assets processing.

  • The change is safe as:
    • It's only applied when both 'interior' and 'x1' properties exist
    • It's part of the decoding process for foreign assets specifically
    • No other code in the codebase relies on x1 being in a non-array format
    • The function is used consistently across asset-related operations (foreign assets on AssetHub, native asset balances, etc.)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other usages of interior.x1 to verify the change doesn't break existing code
rg -A 5 "interior.*x1" 

# Search for any tests involving interior.x1
rg -A 5 "interior.*x1.*test"

Length of output: 548


Script:

#!/bin/bash
# Let's check the context of this function and its usage
rg -B 10 -A 5 "if \('interior' in objAsRecord && 'x1'" packages/extension-polkagate/src/util/utils.ts

# Search for any tests or usage of this function
ast-grep --pattern 'function $_(objAsRecord: $_) {
  if ("interior" in objAsRecord && "x1" in objAsRecord["interior"]) {
    $$$
  }
  $$$
}'

# Look for any MultiLocation or similar type definitions that might use interior.x1
rg -A 5 "type.*MultiLocation|interface.*MultiLocation"

Length of output: 742


Script:

#!/bin/bash
# Let's find the function name and its usages
rg -B 15 -A 5 "if \('interior' in objAsRecord && 'x1'" packages/extension-polkagate/src/util/utils.ts

# Look for any imports or exports of this function
rg "import.*from.*utils|export.*from.*utils" 

# Search for MultiLocation usage in the codebase
rg -A 2 "MultiLocation"

Length of output: 53615

@AMIRKHANEF AMIRKHANEF reopened this Nov 25, 2024
@Nick-1979 Nick-1979 merged commit ce4c6f9 into PolkaGate:main Nov 25, 2024
6 checks passed
@AMIRKHANEF AMIRKHANEF deleted the updatePackages branch November 27, 2024 05:51
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