-
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
refactor: using shared worker for fetching assets balances #1666
Conversation
WalkthroughThe changes in this pull request introduce a new context, Changes
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
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: 21
🧹 Outside diff range and nitpick comments (25)
packages/extension-polkagate/src/hooks/useWorker.ts (3)
6-6
: Consider using a more specific import pathThe import path
'../components'
is quite generic. Consider importing directly from the specific context file (e.g.,'../components/contexts'
or similar) to improve maintainability and make dependencies more explicit.
8-16
: Add TypeScript type annotations and JSDoc documentationThe hook implementation would benefit from explicit type annotations and documentation:
+ /** + * Custom hook to access the shared worker instance from WorkerContext + * @throws {Error} If used outside of WorkerProvider + * @returns {Worker} The shared worker instance + */ - export const useWorker = () => { + export const useWorker = (): Worker => { const worker = useContext(WorkerContext); if (worker === undefined) { throw new Error('useWorker must be used within a WorkerProvider'); } return worker; };
11-13
: Consider adding more descriptive error messageThe error message could be more helpful by suggesting how to fix the issue.
if (worker === undefined) { - throw new Error('useWorker must be used within a WorkerProvider'); + throw new Error('useWorker must be used within a WorkerProvider. Wrap your component tree with <WorkerProvider>'); }tsconfig.json (1)
14-14
: Consider TypeScript migration and pattern consistency.While the configuration change works, consider the following improvements:
- Migrate
getAssetOnMultiAssetChain.js
to TypeScript to maintain consistency with the project's TypeScript codebase.- Instead of adding specific JS files, consider using a more general pattern like
"packages/extension-polkagate/src/util/workers/**/*"
to include all worker-related files.- "packages/extension/public/offscreen.js" -, "packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnMultiAssetChain.js" ], + "packages/extension/public/offscreen.js", + "packages/extension-polkagate/src/util/workers/**/*" + ],packages/extension-polkagate/src/util/workers/shared-helpers/getPooledBalance.js (1)
10-23
: Enhance error handling and validation.While the current implementation handles basic error cases, it could be more explicit about failure scenarios.
Consider this enhanced implementation:
export async function getPooledBalance (api, address) { + if (!api?.query?.nominationPools) { + throw new Error('Nomination pools not supported'); + } + const response = await api.query.nominationPools.poolMembers(address); const member = response?.unwrapOr(undefined); if (!member) { return BN_ZERO; } const poolId = member.poolId; + if (!poolId || poolId.isZero()) { + return BN_ZERO; + } + const accounts = poolId && getPoolAccounts(api, poolId); - if (!accounts) { + if (!accounts?.stashId) { return BN_ZERO; }packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnAssetHub.js (2)
7-8
: Remove unnecessary @ts-ignore commentThis standalone @ts-ignore comment doesn't serve any purpose as it's not associated with any code.
-// @ts-ignore -
13-15
: Improve worker message handlingThe current implementation lacks error handling for metadata extraction and uses an unstructured message format.
Consider implementing a more robust message structure:
- const { metadata } = metadataFromApi(api); - postMessage(JSON.stringify({ functionName: 'getAssetOnAssetHub', metadata })); + try { + const { metadata } = metadataFromApi(api); + postMessage(JSON.stringify({ + type: 'METADATA_UPDATE', + payload: { + functionName: 'getAssetOnAssetHub', + metadata, + timestamp: Date.now() + } + })); + } catch (error) { + postMessage(JSON.stringify({ + type: 'ERROR', + payload: { + functionName: 'getAssetOnAssetHub', + error: error.message + } + })); + }packages/extension-polkagate/src/util/workers/shared-helpers/getBalances.js (1)
11-46
: Consider adding resilience patternsAs this is a worker-based implementation handling blockchain interactions, consider implementing:
- Retry mechanisms with exponential backoff for failed API calls
- Rate limiting when fetching balances for multiple addresses
- Batch processing for large address lists to prevent memory issues
- Circuit breaker pattern for API endpoints that consistently fail
This would improve the reliability and scalability of the balance fetching mechanism.
packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnRelayChain.js (2)
11-13
: Add JSDoc documentation and type annotationsThe function lacks documentation explaining its purpose, parameters, and return value. Consider adding JSDoc comments and TypeScript types:
+/** + * Fetches asset information on a relay chain for given addresses + * @param {string[]} addresses - List of addresses to fetch balances for + * @param {string} chainName - Name of the relay chain + * @param {object} userAddedEndpoints - Custom endpoints configuration + * @returns {Promise<void>} - Posts message with results via worker + */ -export async function getAssetOnRelayChain (addresses, chainName, userAddedEndpoints) { +export async function getAssetOnRelayChain( + addresses: string[], + chainName: string, + userAddedEndpoints: Record<string, unknown> +): Promise<void> {
11-45
: Consider caching and worker lifecycle managementAs this is a worker helper function that fetches blockchain data:
- Consider implementing a caching mechanism to avoid redundant API calls for the same addresses within a short time window
- Add proper cleanup handling for worker termination
- Consider implementing retry logic for failed API calls
Would you like assistance in implementing these improvements?
packages/extension-polkagate/src/util/workers/sharedWorker.js (3)
4-10
: Add error handling for assets initializationThe initialization of
assetsChains
should include error handling to ensure the worker can gracefully handle initialization failures.-const assetsChains = createAssets(); +let assetsChains; +try { + assetsChains = createAssets(); +} catch (error) { + console.error('Failed to initialize assets:', error); + assetsChains = {}; +}
52-56
: Enhance global error handlingThe global error handler should provide more context about the error and potentially handle different error types differently.
} catch (error) { - console.error(`Error while shared worker probably running ${functionName}`, error); - return postMessage({ functionName }); + console.error(`SharedWorker error while executing ${functionName}:`, error); + return postMessage({ + functionName, + error: error.message || 'WORKER_ERROR', + details: error.stack + }); }
1-57
: Consider browser compatibility and worker lifecycleAs this implements a SharedWorker:
- Consider adding a feature detection for SharedWorker support
- Implement proper worker termination handling
- Consider fallback mechanism for browsers that don't support SharedWorker
Consider implementing a feature detection wrapper:
if (typeof SharedWorker !== 'undefined') { // SharedWorker implementation } else { // Fallback implementation }🧰 Tools
🪛 Biome (1.9.4)
[error] 25-25: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 11-12: A global variable should not be reassigned.
Assigning to a global variable can override essential functionality.
(lint/suspicious/noGlobalAssign)
packages/extension-polkagate/src/components/contexts.tsx (1)
30-30
: Consider importing Worker type and adding documentation.The context implementation looks good, but could be enhanced with:
- Explicit import of the
Worker
type from lib.dom- JSDoc comment explaining the context's purpose and usage
+import type { Worker } from 'lib.dom'; + +/** + * Context for sharing a Web Worker instance across components. + * Used for offloading asset balance calculations to a background thread. + */ const WorkerContext = React.createContext<Worker | undefined>(undefined);packages/extension-polkagate/src/fullscreen/accountDetails/components/AOC.tsx (1)
132-139
: Consider improving the filtering logic and documentation.A few suggestions to enhance the code:
- The comment "filter non selected chains" is redundant and can be removed
- The else condition's purpose could be more explicit
- Consider adding type safety checks
Here's a suggested improvement:
const assets = useMemo(() => { - if (accountAssets && accountAssets.length > 0 && selectedChains) { - // filter non selected chains - - return accountAssets.filter(({ genesisHash }) => selectedChains.includes(genesisHash)); + if (!accountAssets?.length || !selectedChains?.length) { + // Return two undefined values to render skeleton loading states + return [undefined, undefined]; + } + + return accountAssets.filter(({ genesisHash }) => { + if (!genesisHash) return false; + return selectedChains.includes(genesisHash); + }); - } else { - return [undefined, undefined]; // two undefined to show two skeletons - } }, [accountAssets, selectedChains]);packages/extension-ui/src/Popup/index.tsx (1)
328-418
: Consider reducing context nesting depth.The deep nesting of context providers (13 levels) makes the code harder to maintain and could impact performance. Consider:
- Combining related contexts
- Using context composition
- Moving some contexts to specific routes where they're needed
Example refactor for combining related contexts:
// Create a combined context type CombinedAuthContext = { authRequests: AuthorizeRequest[]; metaRequests: MetadataRequest[]; signRequests: SigningRequest[]; }; // Use a single provider instead of three <CombinedAuthContext.Provider value={{authRequests, metaRequests, signRequests}}> {/* child components */} </CombinedAuthContext.Provider>packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnMultiAssetChain.js (2)
57-57
: Logging level adjustmentThe logging statement has changed from
console.log
toconsole.info
. Ensure that this aligns with the application's logging conventions and thatconsole.info
is appropriately used for informational messages.
Line range hint
10-61
: Removal of error handling and retry logicThe previous error handling and retry mechanisms have been removed from the function. This might affect the robustness of the asset fetching process, especially in cases of network instability or API errors. Consider reintroducing error handling or implementing it at a higher level to ensure reliability.
Would you like assistance in designing an improved error handling strategy for this function?
packages/extension-polkagate/src/util/workers/shared-helpers/getAssets.js (3)
9-9
: Avoid overusing@ts-ignore
directivesThe
@ts-ignore
comment before the function suppresses TypeScript errors, which might mask underlying issues. Consider resolving the type errors instead of ignoring them to improve code reliability and maintainability.
Line range hint
41-55
: Ensure consistent data types for balance propertiesThe balance properties within the
item
object use a mix of data types (string
,number
,BN
instances). For consistency and to prevent potential type-related bugs, standardize the data types across all balance-related properties.Consider converting all balance-related values to strings or a consistent numeric type based on how they're used elsewhere in the application.
59-59
: Simplify logic for updatingresults
The current method of updating
results[_index]
using optional chaining and the nullish coalescing operator may reduce readability. Consider simplifying the logic for clarity.Suggested refactor:
- results[_index]?.push(item) ?? (results[_index] = [item]); + if (!results[_index]) { + results[_index] = []; + } + results[_index].push(item);packages/extension-polkagate/src/hooks/useAssetsBalances.ts (4)
267-267
: Consider removing or conditionally wrapping debug logsThe
console.info('workerCallsCount.current', workerCallsCount.current);
line appears to be for debugging purposes. Consider removing it or wrapping it with a condition to prevent logging in production builds.
384-393
: Consolidateworker.onerror
handling to avoid redundant definitionsIn the functions
fetchAssetOnRelayChain
,fetchAssetOnAssetHubs
, andfetchAssetOnMultiAssetChain
, theworker.onerror
handler is assigned within each function. This results in redefining the error handler multiple times. Consider consolidating theworker.onerror
assignment to a single location to avoid redundancy and ensure consistent error handling.Apply this diff to set
worker.onerror
once, possibly in auseEffect
:+ useEffect(() => { + if (worker) { + worker.onerror = (err) => { + console.error('Worker error:', err); + }; + } + }, [worker]); - // Remove worker.onerror assignments from individual functions - worker.onerror = (err) => { - console.log(err); - };Also applies to: 395-407, 409-423
306-377
: Avoid reassigningworker.onmessage
multiple timesThe
worker.onmessage
handler is assigned within thehandleWorkerMessages
function, which is called in multiple places. This could lead to reassigning the message handler multiple times. Consider assigningworker.onmessage
once, perhaps in auseEffect
, to avoid unnecessary reassignments.Apply this diff to set
worker.onmessage
once:+ useEffect(() => { + if (worker) { + worker.onmessage = (e: MessageEvent<string>) => { + // Existing onmessage handler code + }; + } + }, [worker]); - // Remove calls to handleWorkerMessages() where it only sets worker.onmessage🧰 Tools
🪛 Biome (1.9.4)
[error] 352-352: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
[error] 368-368: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
352-352
: Avoid usingdelete
operator to improve performanceUsing the
delete
operator on objects (lines 352 and 368) can impact performance because it alters the object's shape and deoptimizes property access. Instead of deleting properties, consider setting them toundefined
ornull
.Apply this diff to replace
delete
with assignment toundefined
:- delete _assets[address][0].balanceDetails; + _assets[address][0].balanceDetails = undefined; - delete temp.balanceDetails; + temp.balanceDetails = undefined;Also applies to: 368-368
🧰 Tools
🪛 Biome (1.9.4)
[error] 352-352: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (14)
packages/extension-polkagate/src/components/contexts.tsx
(2 hunks)packages/extension-polkagate/src/fullscreen/accountDetails/components/AOC.tsx
(3 hunks)packages/extension-polkagate/src/hooks/useAssetsBalances.ts
(11 hunks)packages/extension-polkagate/src/hooks/useWorker.ts
(1 hunks)packages/extension-polkagate/src/util/workers/getAssetOnRelayChain.js
(0 hunks)packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnAssetHub.js
(1 hunks)packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnMultiAssetChain.js
(2 hunks)packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnRelayChain.js
(1 hunks)packages/extension-polkagate/src/util/workers/shared-helpers/getAssets.js
(2 hunks)packages/extension-polkagate/src/util/workers/shared-helpers/getBalances.js
(1 hunks)packages/extension-polkagate/src/util/workers/shared-helpers/getPooledBalance.js
(1 hunks)packages/extension-polkagate/src/util/workers/sharedWorker.js
(1 hunks)packages/extension-ui/src/Popup/index.tsx
(5 hunks)tsconfig.json
(1 hunks)
💤 Files with no reviewable changes (1)
- packages/extension-polkagate/src/util/workers/getAssetOnRelayChain.js
🧰 Additional context used
🪛 Biome (1.9.4)
packages/extension-polkagate/src/hooks/useAssetsBalances.ts
[error] 352-352: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
[error] 368-368: Avoid the delete operator which can impact performance.
Unsafe fix: Use an undefined assignment instead.
(lint/performance/noDelete)
packages/extension-polkagate/src/util/workers/sharedWorker.js
[error] 25-25: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 11-12: A global variable should not be reassigned.
Assigning to a global variable can override essential functionality.
(lint/suspicious/noGlobalAssign)
🔇 Additional comments (17)
packages/extension-polkagate/src/hooks/useWorker.ts (1)
8-16
: Verify WorkerContext implementation and usage
Let's verify that the WorkerContext is properly implemented and the worker is being provided correctly.
✅ Verification successful
WorkerContext implementation and usage is properly configured
The verification shows that:
- The WorkerContext is properly initialized in Popup/index.tsx with a Web Worker that handles shared functionality
- The worker is correctly provided through the WorkerContext.Provider component
- The useWorker hook correctly accesses this context
- The shared worker implementation (sharedWorker.js) contains proper message handling for various asset-related operations
The implementation follows React's context pattern correctly and the worker is properly initialized, provided, and cleaned up in the component lifecycle.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify WorkerContext implementation and usage
# Check WorkerContext implementation
echo "Checking WorkerContext implementation..."
ast-grep --pattern 'const WorkerContext = createContext<Worker | undefined>'
# Check WorkerProvider usage
echo "Checking WorkerProvider usage..."
rg -l "WorkerProvider" --type ts --type tsx
# Check other uses of useWorker
echo "Checking useWorker usage..."
rg "useWorker\(\)" --type ts --type tsx -A 3
Length of output: 456
Script:
#!/bin/bash
# Let's try a different approach to verify the WorkerContext implementation and usage
# Check for WorkerContext definition
echo "Checking WorkerContext definition..."
rg "WorkerContext.*=.*createContext" -A 2
# Check for WorkerProvider component
echo "Checking WorkerProvider component..."
rg "WorkerProvider.*=.*" -A 5
# Check for useWorker hook usage
echo "Checking useWorker hook usage..."
rg "useWorker" -A 2
# Look for Worker type/interface definition
echo "Checking Worker type definition..."
rg "type Worker|interface Worker" -A 3
Length of output: 1735
Script:
#!/bin/bash
# Let's check for the WorkerProvider implementation and its usage
# Check the full content of contexts.tsx
echo "Checking contexts.tsx content..."
cat packages/extension-polkagate/src/components/contexts.tsx
# Find where WorkerProvider is used
echo "Finding WorkerProvider usage..."
rg -l "WorkerProvider"
# Look for Worker related imports
echo "Checking Worker related imports..."
rg "import.*Worker" -A 1
Length of output: 3778
Script:
#!/bin/bash
# Let's find where the Worker is actually provided to the context
# Check Popup/index.tsx content since it imports WorkerContext
echo "Checking Popup/index.tsx content..."
cat "packages/extension-ui/src/Popup/index.tsx"
# Look for any Web Worker initialization
echo "Checking for Web Worker initialization..."
rg "new Worker\(" -A 2
Length of output: 31724
Script:
#!/bin/bash
# Let's verify the shared worker implementation
# Check the shared worker implementation
echo "Checking shared worker implementation..."
cat "packages/extension-polkagate/src/util/workers/sharedWorker.js"
# Check if there are any worker-related types
echo "Checking for Worker type definitions..."
rg "type Worker" -A 3 --type ts
Length of output: 2291
packages/extension-polkagate/src/util/workers/shared-helpers/getPooledBalance.js (1)
1-43
: Verify worker integration and usage.
Let's verify how this helper is integrated with the worker context and where it's being used.
packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnAssetHub.js (1)
22-31
: Clarify status of foreign assets calculation
There's a significant block of commented code for calculating foreign token IDs. If this functionality is needed, it should be implemented properly. If not, the commented code should be removed to maintain code clarity.
Let's check if this functionality is implemented elsewhere:
packages/extension-polkagate/src/util/workers/sharedWorker.js (1)
12-15
: 🛠️ Refactor suggestion
Potential parameter ordering issue with Object.values
Using Object.values
to extract parameters may lead to incorrect parameter ordering if the object keys are not consistently ordered. Consider explicitly destructuring the required parameters to ensure correct ordering.
- const params = Object.values(parameters);
+ // Explicitly destructure parameters based on the function requirements
+ const getParams = (funcName) => {
+ switch (funcName) {
+ case 'getAssetOnRelayChain':
+ const { param1, param2 } = parameters;
+ return [param1, param2];
+ // Add cases for other functions
+ default:
+ return [];
+ }
+ };
packages/extension-polkagate/src/components/contexts.tsx (1)
48-49
: LGTM!
The WorkerContext is properly exported and maintains alphabetical ordering with other contexts.
packages/extension-polkagate/src/fullscreen/accountDetails/components/AOC.tsx (3)
17-17
: LGTM!
The useSelectedChains
hook import follows React conventions and is appropriately grouped with other hooks.
123-123
: LGTM!
The useSelectedChains
hook is correctly used at the component level.
132-139
: Verify handling of edge cases.
Please ensure that:
- The component gracefully handles the case when no chains are selected
- Users are properly informed when their assets are not displayed due to chain filtering
✅ Verification successful
Based on the shell script results, I can now generate the final response as there's enough evidence to verify the concern:
Edge cases are properly handled in the asset filtering logic
The code's handling of edge cases is appropriate because:
- When no chains are selected, it returns
[undefined, undefined]
to show two skeletons, providing visual feedback to users - The filtering logic
accountAssets.filter(({ genesisHash }) => selectedChains.includes(genesisHash))
only runs when bothaccountAssets
andselectedChains
are available - The component is part of a larger system that manages selected chains state via
useSelectedChains
hook, which provides default selected chains if none are explicitly chosen
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for error handling and user feedback in the codebase
# Check for error messages or notifications related to chain selection
rg -A 2 "no.*chains.*selected" --glob "*.{ts,tsx}"
rg -A 2 "select.*chain" --glob "*.{ts,tsx}"
# Check how useSelectedChains is used across the codebase
rg -A 5 "useSelectedChains" --glob "*.{ts,tsx}"
Length of output: 25123
packages/extension-ui/src/Popup/index.tsx (2)
148-148
: Verify worker availability before usage.
The worker is passed to useAssetsBalances
without checking its initialization status.
166-175
: Verify worker message handling.
The worker initialization is present, but there's no visible message handling setup. Ensure proper communication is established between the worker and the main thread.
Also applies to: 328-418
✅ Verification successful
Let me check the worker implementation and message handling in the file under review.
Let me check how this worker is used in the Popup component.
Let me check how the worker is used in the useAssetsBalances hook since it's the main consumer of the worker in the Popup component.
Worker communication is properly implemented through useAssetsBalances hook
The worker communication is correctly established in the Popup component through the useAssetsBalances hook. Here's how it works:
- The worker is initialized in Popup's useEffect and stored in workerRef
- The worker is passed to useAssetsBalances hook which:
- Sets up message handling via worker.onmessage
- Sends messages via worker.postMessage for different asset fetching operations
- Handles worker responses to update the assets state
- The worker implementation (sharedWorker.js) properly handles incoming messages and responds with the processed data
The review comment's concern about missing message handling is incorrect as the communication is properly implemented through the useAssetsBalances hook.
[incorrect_review_comment]
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Look for worker message handling
rg -A 5 "worker.*postMessage|worker.*onmessage"
Length of output: 4363
Script:
#!/bin/bash
# Look for worker message handling in the Popup component
rg -A 10 "workerRef\.current\.(onmessage|postMessage)" packages/extension-ui/src/Popup/index.tsx
# Check the worker implementation
cat packages/extension-polkagate/src/util/workers/sharedWorker.js
Length of output: 2176
Script:
#!/bin/bash
# Search for worker usage in the Popup component
rg -C 20 "workerRef" packages/extension-ui/src/Popup/index.tsx
Length of output: 6359
Script:
#!/bin/bash
# Check the implementation of useAssetsBalances hook
cat packages/extension-polkagate/src/hooks/useAssetsBalances.ts
Length of output: 17001
packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnMultiAssetChain.js (4)
16-16
: Consistency in postMessage
payload
The postMessage
now includes functionName
and metadata
. Confirm that the worker's message handler expects this structure to prevent potential mismatches.
61-61
: Ensure postMessage
results are handled correctly
The final postMessage
sends { functionName: 'getAssetOnMultiAssetChain', results }
. Verify that the message receiver processes the results
as expected.
14-14
: Verify the structure returned by metadataFromApi(api)
The code now destructures metadata
from the result of metadataFromApi(api)
. Ensure that this function returns an object containing the metadata
property to avoid undefined
errors.
Run the following script to check the definition of metadataFromApi
and confirm it returns an object with a metadata
property:
✅ Verification successful
The destructuring of metadata
from metadataFromApi(api)
is correct
The function metadataFromApi
is defined in packages/extension-polkagate/src/util/workers/utils/metadataFromApi.ts
and explicitly returns an object with the metadata
property as shown in its type signature:
export function metadataFromApi (api: ApiPromise): {metadata: MetadataDef}
The function is used consistently across multiple files in the codebase with the same destructuring pattern:
getBalances.js
getAssetOnMultiAssetChain.js
getAssetOnAssetHub.js
addNewChain/index.tsx
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check the return structure of `metadataFromApi`.
# Find the definition of `metadataFromApi`
ast-grep --pattern 'function metadataFromApi($_) {
$$$
return { metadata: $_$ };
}' --lang javascript
Length of output: 107
Script:
#!/bin/bash
# Let's try a broader search for metadataFromApi definition
rg "metadataFromApi" -A 5 -B 5
# Also search for any exports of metadataFromApi
rg "export.*metadataFromApi"
# Search for files containing metadataFromApi in their name
fd "metadataFromApi"
Length of output: 11292
10-10
: Updated function signature and export status
The function getAssetOnMultiAssetChain
is now exported and has an updated parameter order. Ensure that all modules importing and calling this function have been updated accordingly to prevent potential issues.
Run the following script to find all usages of getAssetOnMultiAssetChain
and verify that the import statements and function calls match the new signature:
packages/extension-polkagate/src/util/workers/shared-helpers/getAssets.js (2)
6-6
: Verify import path for 'decodeMultiLocation'
Ensure that the relative import path '../../utils'
correctly points to the module exporting decodeMultiLocation
. Incorrect import paths can lead to runtime errors during module resolution.
61-61
: Enhanced error logging with chainName
context
Including chainName
in the error message provides additional context for debugging, improving maintainability.
packages/extension-polkagate/src/hooks/useAssetsBalances.ts (1)
136-136
: Verify that all calls to useAssetsBalances
handle the new worker
parameter
The useAssetsBalances
function now accepts an optional worker
parameter. Ensure that all components using this hook are updated accordingly to pass the worker
instance or handle its absence to maintain functionality.
Summary by CodeRabbit
Release Notes
New Features
WorkerContext
for better management of worker instances across components.useWorker
hook to access the worker context easily.AOC
component based on selected chains.Bug Fixes
Documentation
Chores