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: Auto update metadata while fetching accounts balances #1517

Merged
merged 12 commits into from
Sep 21, 2024

Conversation

AMIRKHANEF
Copy link
Member

@AMIRKHANEF AMIRKHANEF commented Aug 31, 2024

Works Done

  • Create getMetadata.js.
  • Use getMetadata.js inside getAssetOnAssetHub.js, getAssetOnMultiAssetChain.js, getAssetOnRelayChain.js.
  • Add new message 'pri(metadata.update)' in messaging.ts.
  • create metadataUpdate function in Extension.ts.
  • Update useAssetsBalances hook.

Close: #1368

Summary by CodeRabbit

  • New Features

    • Introduced functionality for handling metadata updates within the PolkaGate extension.
    • Added a new asynchronous function to facilitate metadata updates via messaging.
    • Enhanced messaging capabilities to support metadata updates.
    • Expanded the API to allow for more granular control over metadata management.
  • Bug Fixes

    • Improved control flow to ensure proper processing of metadata requests.

Copy link
Contributor

coderabbitai bot commented Aug 31, 2024

Warning

Rate limit exceeded

@Nick-1979 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 12 seconds before requesting another review.

How to resolve this issue?

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

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

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

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

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 02b29b6 and 5bbcfdc.

Walkthrough

The changes introduce a new mechanism for handling metadata updates within the PolkaGate extension. This includes the addition of a private method for processing metadata, a new messaging interface for updates, and enhancements to various utility functions that retrieve and manage metadata. The overall structure of the codebase is modified to support these functionalities, allowing for more efficient metadata management.

Changes

Files Change Summary
packages/extension-base/src/background/handlers/Extension.ts Added metadataUpdate method for handling metadata updates. Modified switch statement for new case.
packages/extension-base/src/background/types.ts Added 'pri(metadata.update)' entry to RequestSignatures interface.
packages/extension-polkagate/src/messaging.ts Introduced updateMetadata function to send metadata update messages.

Assessment against linked issues

Objective Addressed Explanation
Create and use a new hook useUpdateMetadata.ts ( #1368 ) No new hook was created as specified.
Create new message pri(metadata.update) ( #1368 )
Update ApiContext type ( #1368 ) No changes to ApiContext type were made.

🐰 In the meadow, where the data flows,
A rabbit hops where the metadata grows.
With updates swift and messages bright,
Our PolkaGate shines, a joyful sight!
Hooray for changes, let the code dance,
In this digital world, we take a chance! 🌼


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

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f05660a and 5f572e2.

Files selected for processing (9)
  • packages/extension-base/src/background/handlers/Extension.ts (2 hunks)
  • packages/extension-base/src/background/types.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useAssetsBalances.ts (2 hunks)
  • packages/extension-polkagate/src/messaging.ts (1 hunks)
  • packages/extension-polkagate/src/util/workers/getAssetOnAssetHub.js (1 hunks)
  • packages/extension-polkagate/src/util/workers/getAssetOnMultiAssetChain.js (1 hunks)
  • packages/extension-polkagate/src/util/workers/getAssetOnRelayChain.js (2 hunks)
  • packages/extension-polkagate/src/util/workers/utils/getMetadata.js (1 hunks)
  • packages/extension-polkagate/src/util/workers/utils/index.js (1 hunks)
Files skipped from review due to trivial changes (1)
  • packages/extension-polkagate/src/util/workers/utils/index.js
Additional comments not posted (5)
packages/extension-polkagate/src/util/workers/getAssetOnRelayChain.js (1)

57-60: Verify metadata handling and communication.

The integration of metadata fetching within the balance retrieval process is a significant enhancement. However, it's crucial to ensure that the metadata is correctly fetched, formatted, and communicated. Consider adding error handling around the metadata fetching and verify that the postMessage correctly handles the metadata format.

Run the following script to verify the metadata handling:

packages/extension-polkagate/src/messaging.ts (1)

217-220: Verify metadata update messaging.

The implementation of the updateMetadata function enhances the messaging capabilities by allowing metadata updates. Ensure that the function correctly handles the metadata and communicates it without errors. Consider adding error handling around the sendMessage function to ensure robustness.

Run the following script to verify the metadata update messaging:

Verification successful

Metadata update messaging is correctly handled.

The updateMetadata function is used in useAssetsBalances.ts with appropriate error handling using a catch block. This ensures that any errors during the messaging process are managed, aligning with the suggestion for robust error handling. Further manual verification of the messaging process may be considered to ensure complete reliability.

  • File: packages/extension-polkagate/src/hooks/useAssetsBalances.ts
  • Usage: updateMetadata(metadata as unknown as MetadataDef).catch(console.error);
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the metadata update messaging.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type typescript -A 5 $'updateMetadata'

Length of output: 77


Script:

#!/bin/bash
# Description: Verify the metadata update messaging.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type ts -A 5 $'updateMetadata'

Length of output: 1800

packages/extension-base/src/background/types.ts (1)

105-105: Verify request and response types for metadata updates.

The addition of 'pri(metadata.update)' in the RequestSignatures interface enhances the functionality related to metadata updates. Ensure that the interface correctly defines the request (MetadataDef) and response (boolean) types for the metadata update. Consider adding tests to verify the correct handling of these types.

Run the following script to verify the request and response types:

packages/extension-polkagate/src/hooks/useAssetsBalances.ts (1)

23-24: Imports and type definitions are correctly placed.

The new imports for updateMetadata and MetadataDef are correctly added to handle metadata updates. This aligns with the PR's objectives to enhance metadata handling.

packages/extension-base/src/background/handlers/Extension.ts (1)

625-627: Correct integration of new switch case for metadata updates.

The addition of the pri(metadata.update) case in the switch statement is correctly implemented. It ensures that metadata updates are handled appropriately within the existing message processing framework of the Extension class.

This change aligns with the PR's objectives to enhance metadata handling capabilities.

Comment on lines 13 to 39
export function getMetadata (api) {
const endpoints = createWsEndpoints();

const DEFAULT_DECIMALS = api.registry.createType('u32', 12);
const DEFAULT_SS58 = api.registry.createType('u32', 42);
const chainName = api.runtimeChain.toHuman();
const chainGenesisHash = api.genesisHash.toHex();
const color = endpoints.find(({ genesisHash, ui }) => genesisHash === chainGenesisHash && ui.color)?.ui.color;

const metadata = {
chain: chainName,
chainType: 'substrate',
color,
genesisHash: chainGenesisHash,
icon: 'substrate',
metaCalls: base64Encode(api.runtimeMetadata.asCallsOnly.toU8a()),
specVersion: api.runtimeVersion.specVersion.toNumber(),
ss58Format: isNumber(api.registry.chainSS58)
? api.registry.chainSS58
: DEFAULT_SS58.toNumber(),
tokenDecimals: (api.registry.chainDecimals || [DEFAULT_DECIMALS.toNumber()])[0],
tokenSymbol: (api.registry.chainTokens || formatBalance.getDefaults().unit)[0],
types: getSpecTypes(api.registry, chainName, api.runtimeVersion.specName, api.runtimeVersion.specVersion)
};

return { metadata };
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Review of getMetadata function: Well-structured but consider potential optimizations.

The getMetadata function is well-structured and correctly utilizes the Polkadot API and utilities to construct the metadata object. Here are a few observations and suggestions:

  1. Performance: The use of find on endpoints (line 20) could be optimized if the list is large. Consider preprocessing or indexing if performance becomes an issue.
  2. Error Handling: Currently, the function does not handle possible exceptions from API calls or missing fields in the API response. Consider adding error handling to improve robustness.
  3. Documentation: While there is a basic comment describing the function, adding more detailed documentation regarding the parameters and the return value could enhance maintainability.

Overall, the function is implemented correctly but could benefit from minor improvements in error handling and documentation.

Comment on lines 318 to 324
if ('metadata' in parsedMessage) {
const metadata = parsedMessage?.['metadata'];

updateMetadata(metadata as unknown as MetadataDef).catch(console.error);

return;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Enhance error handling in metadata update logic.

The new logic for handling metadata updates is correctly implemented. However, it would be beneficial to enhance error handling around the updateMetadata call to ensure that any issues during metadata processing do not negatively impact the user experience.

Consider wrapping the updateMetadata call in a more comprehensive error handling structure, such as a try-catch block, to handle potential exceptions more gracefully.

- updateMetadata(metadata as unknown as MetadataDef).catch(console.error);
+ try {
+   await updateMetadata(metadata as unknown as MetadataDef);
+ } catch (error) {
+   console.error('Failed to update metadata:', error);
+   // Handle error appropriately, possibly setting an error state or retrying
+ }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if ('metadata' in parsedMessage) {
const metadata = parsedMessage?.['metadata'];
updateMetadata(metadata as unknown as MetadataDef).catch(console.error);
return;
}
if ('metadata' in parsedMessage) {
const metadata = parsedMessage?.['metadata'];
try {
await updateMetadata(metadata as unknown as MetadataDef);
} catch (error) {
console.error('Failed to update metadata:', error);
// Handle error appropriately, possibly setting an error state or retrying
}
return;
}

Comment on lines +304 to +310
private metadataUpdate(metadata: MetadataDef): boolean {
assert(metadata, 'Unable to update metadata');

this.#state.saveMetadata(metadata);

return true;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Refine error handling in metadataUpdate method.

The metadataUpdate method is crucial for handling metadata updates. While the use of assert ensures that metadata is not null, it would be beneficial to provide more specific error messages for better debugging and user feedback.

Consider enhancing the error handling to include specific messages:

- assert(metadata, 'Unable to update metadata');
+ assert(metadata && Object.keys(metadata).length > 0, 'Metadata is required and cannot be empty');

This change ensures that the metadata is not only present but also contains data before proceeding with the update.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private metadataUpdate(metadata: MetadataDef): boolean {
assert(metadata, 'Unable to update metadata');
this.#state.saveMetadata(metadata);
return true;
}
private metadataUpdate(metadata: MetadataDef): boolean {
assert(metadata && Object.keys(metadata).length > 0, 'Metadata is required and cannot be empty');
this.#state.saveMetadata(metadata);
return true;
}

add metadataFromApi to two other calls in useAsset/balances
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5f572e2 and 506b6f1.

Files selected for processing (6)
  • packages/extension-polkagate/src/hooks/useAssetsBalances.ts (5 hunks)
  • packages/extension-polkagate/src/util/workers/getAssetOnAssetHub.js (1 hunks)
  • packages/extension-polkagate/src/util/workers/getAssetOnMultiAssetChain.js (1 hunks)
  • packages/extension-polkagate/src/util/workers/getAssetOnRelayChain.js (2 hunks)
  • packages/extension-polkagate/src/util/workers/utils/index.ts (1 hunks)
  • packages/extension-polkagate/src/util/workers/utils/metadataFromApi.ts (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • packages/extension-polkagate/src/hooks/useAssetsBalances.ts
  • packages/extension-polkagate/src/util/workers/getAssetOnAssetHub.js
  • packages/extension-polkagate/src/util/workers/getAssetOnMultiAssetChain.js
  • packages/extension-polkagate/src/util/workers/getAssetOnRelayChain.js
Additional comments not posted (3)
packages/extension-polkagate/src/util/workers/utils/index.ts (2)

4-4: LGTM!

The removal of the redundant export statement for balancify.js is approved.


8-8: Verify the usage of the new utility function metadataFromApi in the codebase.

The addition of the export statement for metadataFromApi is approved. Please ensure that the new utility function is being used correctly in the codebase.

Run the following script to verify the usage of metadataFromApi:

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

15-39: LGTM!

The metadataFromApi function is well-structured and follows a clear logic to generate the metadata object from an API instance. It uses appropriate type annotations, handles edge cases, and uses a mix of api properties and external utility functions to populate the metadata object. The code is readable and maintainable.

Some good practices observed:

  • Using DEFAULT_DECIMALS and DEFAULT_SS58 constants for default values.
  • Handling the case when api.registry.chainSS58 is not a number by using a default value.
  • Using optional chaining to safely access the color property from the endpoints array.
  • Using appropriate naming conventions for variables and constants.
  • Returning an object with a metadata property for clarity.

The code changes are approved.

@AMIRKHANEF AMIRKHANEF changed the title Auto update metadata while fetching accounts balances feat: Auto update metadata while fetching accounts balances Sep 8, 2024
@Nick-1979 Nick-1979 merged commit 17367eb into PolkaGate:main Sep 21, 2024
5 checks passed
github-actions bot pushed a commit that referenced this pull request Sep 21, 2024
# [0.11.0](v0.10.2...v0.11.0) (2024-09-21)

### Features

* Auto update metadata while fetching accounts balances ([#1517](#1517)) ([17367eb](17367eb))
@coderabbitai coderabbitai bot mentioned this pull request Sep 22, 2024
@AMIRKHANEF AMIRKHANEF deleted the AutoUpdateMetaData branch November 18, 2024 11:18
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