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

feat: get chain using the address #1671

Merged
merged 2 commits into from
Nov 25, 2024
Merged

Conversation

AMIRKHANEF
Copy link
Member

@AMIRKHANEF AMIRKHANEF commented Nov 25, 2024

#1670

Summary by CodeRabbit

  • New Features

    • Introduced a new utility function to retrieve chain metadata based on the provided address.
    • Enhanced address handling with improved error logging for invalid addresses.
  • Bug Fixes

    • Improved error handling during asynchronous operations related to address and chain queries.
  • Refactor

    • Streamlined logic for fetching proxies and managing chain state in the address components.
  • Documentation

    • Updated utility functions to clarify their roles in address validation and chain retrieval.

Copy link
Contributor

coderabbitai bot commented Nov 25, 2024

Walkthrough

The changes in this pull request enhance the AddAddressOnly and AddWatchOnlyFullScreen components by introducing new utility functions for managing chain metadata based on genesisHash. The control flow is modified to check for realAddress before fetching proxy information, improving error handling in asynchronous operations. Additionally, the utility functions addressToChain and getSubstrateAddress are integrated to streamline address processing. These updates aim to improve the modularity and clarity of the components’ logic.

Changes

File Path Change Summary
packages/extension-polkagate/src/popup/import/addWatchOnly/index.tsx Added getChain function, updated goToAccountDetail signature, improved error handling.
packages/extension-polkagate/src/popup/import/addWatchOnlyFullScreen/index.tsx Added getChain, updated onChangeGenesis and onAdd functions to incorporate new logic.
packages/extension-polkagate/src/util/utils.ts Added addressToChain function for address validation and chain retrieval.

Possibly related PRs

Suggested labels

new feature

🐰 "In the garden of code, we hop and play,
With chains and addresses, we find our way.
New functions sprout, like carrots in rows,
Error handling blooms, as our logic grows.
From realAddress to genesisHash, we weave,
In this patch of joy, we all believe!" 🌱


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 77e6d9d and f259c54.

📒 Files selected for processing (2)
  • packages/extension-polkagate/src/popup/import/addWatchOnly/index.tsx (3 hunks)
  • packages/extension-polkagate/src/popup/import/addWatchOnlyFullScreen/index.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/extension-polkagate/src/popup/import/addWatchOnly/index.tsx
  • packages/extension-polkagate/src/popup/import/addWatchOnlyFullScreen/index.tsx

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

🧹 Outside diff range and nitpick comments (4)
packages/extension-polkagate/src/popup/import/addWatchOnly/index.tsx (2)

39-43: Consider enhancing error handling feedback.

While the error is logged, consider providing user feedback for failed chain metadata retrieval.

 const getChain = useCallback((genesisHash: string) => {
   getMetadata(genesisHash, true).then(setChain).catch((error): void => {
     console.error(error);
+    // Consider adding user feedback
+    onAction('/error', { error: t('Failed to retrieve chain metadata') });
   });
 }, []);

56-69: Consider optimizing state updates.

The chain detection logic is sound, but consider memoizing the addressChain result to prevent unnecessary re-renders.

+ const addressChain = useMemo(() => 
+   realAddress ? addressToChain(realAddress) : null,
+ [realAddress]);

 useEffect(() => {
   if (realAddress) {
-    const addressChain = addressToChain(realAddress);
     addressChain?.genesisHash && getChain(addressChain.genesisHash);
     // ... rest of the effect
   }
 }, [api, getChain, realAddress]);
packages/extension-polkagate/src/popup/import/addWatchOnlyFullScreen/index.tsx (2)

70-74: Consider adding loading state management.

While the chain metadata fetching logic is sound, consider adding a loading state to handle the asynchronous nature of getChain and improve user feedback.

+ const [isLoadingChain, setIsLoadingChain] = useState(false);

  const getChain = useCallback((genesisHash: string) => {
+   setIsLoadingChain(true);
    getMetadata(genesisHash, true)
      .then(setChain)
      .catch((error): void => {
        console.error(error);
      })
+     .finally(() => setIsLoadingChain(false));
  }, []);

90-96: Consider adding user feedback for account creation process.

While the account creation logic is solid, consider providing feedback to users during the process, especially for error cases.

  createAccountExternal(name, realAddress, chain.genesisHash as HexString)
    .then(() => {
      setStorage('profile', PROFILE_TAGS.WATCH_ONLY).catch(console.error);
    })
    .finally(() => openOrFocusTab(`/accountfs/${substrateAddress}/0`, true))
    .catch((error: Error) => {
      setIsBusy(false);
+     // Consider using a toast or notification system
+     console.error('Failed to create account:', error);
    });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2f43157 and 77e6d9d.

📒 Files selected for processing (3)
  • packages/extension-polkagate/src/popup/import/addWatchOnly/index.tsx (3 hunks)
  • packages/extension-polkagate/src/popup/import/addWatchOnlyFullScreen/index.tsx (5 hunks)
  • packages/extension-polkagate/src/util/utils.ts (2 hunks)
🔇 Additional comments (7)
packages/extension-polkagate/src/popup/import/addWatchOnly/index.tsx (2)

22-22: LGTM!

The new utility imports are appropriate for the enhanced address and chain handling functionality.


24-24: Verify component integration with related features.

Let's verify the integration with related components and features.

✅ Verification successful

Component integration verified successfully

The component is well-integrated within the codebase:

  • Properly shares common utilities (addressToChain, getSubstrateAddress) with other components in the staking, proxy management, and account-related features
  • Correctly integrated with the watch-only account system, alongside other related components like addWatchOnlyFullScreen
  • Well-connected to the proxy management system through ProxyTable component usage
  • No duplicate or conflicting implementations found
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for related components and potential integration points

# Check for other components using the same utilities
echo "Components using addressToChain or getSubstrateAddress:"
rg -l "addressToChain|getSubstrateAddress" --type typescript

# Check for other watch-only account related components
echo "Related watch-only components:"
rg -l "Watch-Only|WatchOnly" --type typescript

# Check for proxy-related components
echo "Related proxy components:"
rg -l "ProxyTable" --type typescript

Length of output: 506


Script:

#!/bin/bash
# Description: Check for related components and potential integration points with correct file type

# Check for other components using the same utilities
echo "Components using addressToChain or getSubstrateAddress:"
rg -l "addressToChain|getSubstrateAddress"

# Check for other watch-only account related components
echo "Related watch-only components:"
rg -l "Watch-Only|WatchOnly"

# Check for proxy-related components
echo "Related proxy components:"
rg -l "ProxyTable"

# Check for direct imports or usage of AddAddressOnly
echo "Components referencing AddAddressOnly:"
rg -l "AddAddressOnly"

Length of output: 5541

packages/extension-polkagate/src/popup/import/addWatchOnlyFullScreen/index.tsx (3)

28-28: LGTM! New utility imports enhance address processing capabilities.

The addition of addressToChain and getSubstrateAddress utilities improves the modularity of address processing logic.


52-56: LGTM! Well-structured chain metadata fetching utility.

The getChain function is properly memoized and includes error handling.


28-28: Verify the usage of new utility functions across the codebase.

Let's ensure the new utility functions are consistently used across the codebase.

Also applies to: 90-91

✅ Verification successful

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

The utility functions are consistently used across the codebase

  • addressToChain is used in both watch-only import components
  • getSubstrateAddress is widely used across 40+ files for consistent address handling, particularly in:
    • Account management components
    • Staking operations (solo and pool)
    • Proxy management
    • Identity handling
    • Transaction reviews
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check usage of addressToChain and getSubstrateAddress functions

# Check for addressToChain usage
echo "Checking addressToChain usage:"
rg "addressToChain\(" --type ts

# Check for getSubstrateAddress usage
echo -e "\nChecking getSubstrateAddress usage:"
rg "getSubstrateAddress\(" --type ts

# Check for potential similar implementations
echo -e "\nChecking for potential similar implementations:"
rg "\.encode|\.decode" --type ts

Length of output: 9387

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

19-20: LGTM!

The new imports are correctly placed and properly used in the new functionality.


583-605: Verify comprehensive test coverage for address formats.

Please ensure that the function is tested with:

  1. Addresses from all supported chains
  2. Invalid addresses
  3. Edge cases (empty string, malformed addresses)
  4. Addresses with different SS58 formats
✅ Verification successful

Based on the comprehensive analysis of the codebase, I can now provide a final response regarding the address format verification concern:

Address format handling is properly implemented and secure

The implementation of addressToChain function is robust and covers all necessary cases:

  1. Input validation is handled through isValidAddress which properly validates addresses using encodeAddress/decodeAddress from @polkadot/util-crypto
  2. Substrate format is checked via getSubstrateAddress
  3. Chain detection uses SS58 format matching against allChains which contains the complete chain registry
  4. Default fallback to Westend (42) format when no specific chain is matched
  5. Proper error handling with null returns for invalid cases

The function is used consistently across the codebase in address input components and identity verification flows, with proper chain-specific SS58 format handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify test coverage and usage of addressToChain function

# Check for test files
echo "Checking for test files..."
fd -e test.ts -e spec.ts

# Look for existing test cases
echo "Searching for existing test cases..."
rg -A 5 "addressToChain" --type ts

# Check for different address format handling
echo "Checking address format handling..."
ast-grep --pattern 'isValidAddress($addr)' --type ts

Length of output: 3657


Script:

#!/bin/bash
# Let's verify the test coverage and implementation details more thoroughly

# Check for test files specifically related to address handling
echo "Checking for address-related test files..."
rg -l "address|isValidAddress" $(fd -e test.ts -e spec.ts)

# Look for the implementation of isValidAddress and its dependencies
echo "Checking isValidAddress implementation..."
rg "isValidAddress" --type ts -A 5

# Check for SS58 format handling across the codebase
echo "Checking SS58 format handling..."
rg "ss58Format|encodeAddress|decodeAddress" --type ts -A 3

# Check for chain definitions to verify coverage
echo "Looking for chain definitions..."
rg "WESTEND_GENESIS_HASH|allChains" --type ts -A 3

Length of output: 70751

@Nick-1979 Nick-1979 merged commit 1fa7798 into PolkaGate:main Nov 25, 2024
8 checks passed
github-actions bot pushed a commit that referenced this pull request Nov 25, 2024
# [0.33.0](v0.32.1...v0.33.0) (2024-11-25)

### Features

* get chain using the address ([#1671](#1671)) ([1fa7798](1fa7798))
@AMIRKHANEF AMIRKHANEF deleted the WatchOnly 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