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

refactor: using shared worker for fetching assets balances #1666

Merged
merged 1 commit into from
Nov 25, 2024

Conversation

Nick-1979
Copy link
Member

@Nick-1979 Nick-1979 commented Nov 21, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced WorkerContext for better management of worker instances across components.
    • Added useWorker hook to access the worker context easily.
    • Enhanced asset filtering in the AOC component based on selected chains.
    • New functions for fetching asset information from various sources, improving asset retrieval processes.
  • Bug Fixes

    • Improved error handling and logging in asset fetching functions.
  • Documentation

    • Updated TypeScript configuration to include new worker helper files for better type checking.
  • Chores

    • Removed outdated asset fetching functions to streamline the codebase.

@Nick-1979 Nick-1979 requested a review from AMIRKHANEF November 21, 2024 15:14
Copy link
Contributor

coderabbitai bot commented Nov 21, 2024

Walkthrough

The changes in this pull request introduce a new context, WorkerContext, and several modifications across multiple components and hooks to integrate worker functionality for asynchronous operations. Key updates include the addition of a useWorker hook, enhancements to the useAssetsBalances hook to utilize a worker, and the introduction of new asset-fetching functions. The refactor also includes the removal of outdated functions related to asset retrieval, streamlining the overall architecture for managing asset data in a Polkadot-based application.

Changes

File Change Summary
packages/extension-polkagate/src/components/contexts.tsx Added new context WorkerContext and updated the export statement.
packages/extension-polkagate/src/fullscreen/accountDetails/components/AOC.tsx Introduced useSelectedChains hook for filtering accountAssets based on selectedChains. Updated method signature for AOC component.
packages/extension-polkagate/src/hooks/useAssetsBalances.ts Added optional worker parameter to the useAssetsBalances function. Updated asset fetching logic and state management for worker integration.
packages/extension-polkagate/src/hooks/useWorker.ts Created a new hook useWorker to access WorkerContext.
packages/extension-polkagate/src/util/workers/getAssetOnRelayChain.js Removed file containing asset retrieval functions for relay chains.
packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnAssetHub.js Added new function getAssetOnAssetHub for fetching asset information from asset hubs.
packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnMultiAssetChain.js Updated getAssetOnMultiAssetChain function signature and streamlined logic.
packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnRelayChain.js Introduced new function getAssetOnRelayChain for retrieving asset information on relay chains.
packages/extension-polkagate/src/util/workers/shared-helpers/getAssets.js Updated getAssets function to enhance error handling and remove the getAssetOnAssetHub function.
packages/extension-polkagate/src/util/workers/shared-helpers/getBalances.js Added new function getBalances to retrieve balance information for addresses.
packages/extension-polkagate/src/util/workers/shared-helpers/getPooledBalance.js Added new function getPooledBalance for calculating pooled balances in nomination pools.
packages/extension-polkagate/src/util/workers/sharedWorker.js Implemented a shared web worker for handling asset-related requests.
packages/extension-ui/src/Popup/index.tsx Integrated WorkerContext into the Popup component and updated the structure for worker access.
tsconfig.json Added path to include array to expand TypeScript compiler scope.

Possibly related PRs

Suggested labels

change requested, new feature

Suggested reviewers

  • AMIRKHANEF

Poem

🐰 In the fields where the data flows,
A new worker hops where the context grows.
With assets fetched and balances bright,
The rabbit's code shines with delight!
So let us cheer for the changes made,
In the world of code, let joy cascade! 🌼


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

🧹 Outside diff range and nitpick comments (25)
packages/extension-polkagate/src/hooks/useWorker.ts (3)

6-6: Consider using a more specific import path

The 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 documentation

The 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 message

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

  1. Migrate getAssetOnMultiAssetChain.js to TypeScript to maintain consistency with the project's TypeScript codebase.
  2. 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 comment

This standalone @ts-ignore comment doesn't serve any purpose as it's not associated with any code.

-// @ts-ignore
-

13-15: Improve worker message handling

The 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 patterns

As this is a worker-based implementation handling blockchain interactions, consider implementing:

  1. Retry mechanisms with exponential backoff for failed API calls
  2. Rate limiting when fetching balances for multiple addresses
  3. Batch processing for large address lists to prevent memory issues
  4. 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 annotations

The 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 management

As this is a worker helper function that fetches blockchain data:

  1. Consider implementing a caching mechanism to avoid redundant API calls for the same addresses within a short time window
  2. Add proper cleanup handling for worker termination
  3. 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 initialization

The 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 handling

The 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 lifecycle

As this implements a SharedWorker:

  1. Consider adding a feature detection for SharedWorker support
  2. Implement proper worker termination handling
  3. 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:

  1. Explicit import of the Worker type from lib.dom
  2. 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:

  1. The comment "filter non selected chains" is redundant and can be removed
  2. The else condition's purpose could be more explicit
  3. 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:

  1. Combining related contexts
  2. Using context composition
  3. 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 adjustment

The logging statement has changed from console.log to console.info. Ensure that this aligns with the application's logging conventions and that console.info is appropriately used for informational messages.


Line range hint 10-61: Removal of error handling and retry logic

The 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 directives

The @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 properties

The 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 updating results

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 logs

The 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: Consolidate worker.onerror handling to avoid redundant definitions

In the functions fetchAssetOnRelayChain, fetchAssetOnAssetHubs, and fetchAssetOnMultiAssetChain, the worker.onerror handler is assigned within each function. This results in redefining the error handler multiple times. Consider consolidating the worker.onerror assignment to a single location to avoid redundancy and ensure consistent error handling.

Apply this diff to set worker.onerror once, possibly in a useEffect:

+ 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 reassigning worker.onmessage multiple times

The worker.onmessage handler is assigned within the handleWorkerMessages function, which is called in multiple places. This could lead to reassigning the message handler multiple times. Consider assigning worker.onmessage once, perhaps in a useEffect, 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 using delete operator to improve performance

Using 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 to undefined or null.

Apply this diff to replace delete with assignment to undefined:

- 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f43157 and 148540f.

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

  1. The WorkerContext is properly initialized in Popup/index.tsx with a Web Worker that handles shared functionality
  2. The worker is correctly provided through the WorkerContext.Provider component
  3. The useWorker hook correctly accesses this context
  4. 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:

  1. The component gracefully handles the case when no chains are selected
  2. 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 both accountAssets and selectedChains 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:

  1. The worker is initialized in Popup's useEffect and stored in workerRef
  2. 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
  3. 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.

@Nick-1979 Nick-1979 merged commit cbe564b into main Nov 25, 2024
8 checks passed
@Nick-1979 Nick-1979 deleted the sharedWorker branch November 25, 2024 12:36
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