-
Notifications
You must be signed in to change notification settings - Fork 5
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
Conversation
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 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. WalkthroughThe 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
Assessment against linked issues
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 (
|
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: 5
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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 thesendMessage
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 inuseAssetsBalances.ts
with appropriate error handling using acatch
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 theRequestSignatures
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
andMetadataDef
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 theExtension
class.This change aligns with the PR's objectives to enhance metadata handling capabilities.
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 }; | ||
} |
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.
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:
- Performance: The use of
find
onendpoints
(line 20) could be optimized if the list is large. Consider preprocessing or indexing if performance becomes an issue. - 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.
- 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.
packages/extension-polkagate/src/util/workers/getAssetOnMultiAssetChain.js
Outdated
Show resolved
Hide resolved
packages/extension-polkagate/src/util/workers/getAssetOnAssetHub.js
Outdated
Show resolved
Hide resolved
if ('metadata' in parsedMessage) { | ||
const metadata = parsedMessage?.['metadata']; | ||
|
||
updateMetadata(metadata as unknown as MetadataDef).catch(console.error); | ||
|
||
return; | ||
} |
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.
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.
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; | |
} |
private metadataUpdate(metadata: MetadataDef): boolean { | ||
assert(metadata, 'Unable to update metadata'); | ||
|
||
this.#state.saveMetadata(metadata); | ||
|
||
return true; | ||
} |
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.
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.
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
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
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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 functionmetadataFromApi
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 ofapi
properties and external utility functions to populate the metadata object. The code is readable and maintainable.Some good practices observed:
- Using
DEFAULT_DECIMALS
andDEFAULT_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 theendpoints
array.- Using appropriate naming conventions for variables and constants.
- Returning an object with a
metadata
property for clarity.The code changes are approved.
# [0.11.0](v0.10.2...v0.11.0) (2024-09-21) ### Features * Auto update metadata while fetching accounts balances ([#1517](#1517)) ([17367eb](17367eb))
Works Done
getMetadata.js
.getMetadata.js
insidegetAssetOnAssetHub.js
,getAssetOnMultiAssetChain.js
,getAssetOnRelayChain.js
.'pri(metadata.update)'
inmessaging.ts
.metadataUpdate
function inExtension.ts
.useAssetsBalances
hook.Close: #1368
Summary by CodeRabbit
New Features
Bug Fixes