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

refac: Simplify wallet management system #961

Merged
merged 1 commit into from
Nov 26, 2024

Conversation

Abeeujah
Copy link
Contributor

@Abeeujah Abeeujah commented Nov 23, 2024

Pull Request type

Refactor

Please add the labels corresponding to the type of changes your PR introduces:

  • Bugfix
  • Feature
  • Code style update (formatting, renaming)
  • Refactoring (no functional changes, no API changes)
  • Build-related changes
  • Documentation content changes
  • Testing
  • Other (please describe):

Resolves: #NA
close #953

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new wallet configuration system with comprehensive metadata and connection logic for various cryptocurrency wallets.
    • Added utility functions for managing wallet connections, including retrieving wallet information and sorting connectors.
  • Bug Fixes

    • Minor formatting adjustments in various components for improved consistency and readability.
  • Tests

    • Added a suite of unit tests for wallet configuration functions to ensure robust validation.
    • Removed outdated tests related to the previous connector sorting logic.
  • Chores

    • Removed unused functions and files to streamline the codebase.

Copy link

vercel bot commented Nov 23, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
starknet-quest ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 25, 2024 1:48pm

Copy link

vercel bot commented Nov 23, 2024

@Abeeujah is attempting to deploy a commit to the LFG Labs Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Nov 23, 2024

Walkthrough

The pull request introduces several changes across multiple files, primarily focusing on code formatting and restructuring for improved readability and maintainability. Key modifications include the creation of a new centralized wallet configuration file (utils/walletConfig.ts), the removal of redundant functions and files, and updates to existing components to utilize the new configuration. Additionally, minor formatting adjustments were made to ensure consistency in string usage across various files.

Changes

File Change Summary
app/not-connected/page.tsx Minor formatting adjustments; removed unnecessary space before comments in function calls.
app/provider.tsx Converted single quotes to double quotes; removed isBitgetWalletInstalled function; replaced availableConnectors with getConnectors().
components/UI/iconsComponents/icons/walletIcons.tsx Simplified rendering logic; replaced multiple conditional checks with a single call to getWalletInfo.
components/UI/navbar.tsx Updated import for sortConnectors; standardized attribute formatting to double quotes.
tests/utils/connectors.test.js Deleted file containing unit tests for sortConnectors.
tests/utils/walletConfig.test.js New test file for wallet configuration utilities, including tests for sortConnectors, getConnectorIcon, getConnectorName, and getConnectorDiscovery.
types/frontTypes.d.ts Updated ChartItem type definition from comma to semicolon separation.
utils/connectors.ts Deleted file containing the sortConnectors function.
utils/walletConfig.ts Introduced new file with centralized wallet configuration and utility functions.

Assessment against linked issues

Objective Addressed Explanation
Simplify wallet management by creating a centralized configuration (Issue #953)
Centralize wallet metadata management (Issue #953)
Remove redundant wallet information in different components (Issue #953)
Simplify conditional rendering in wallet icons component (Issue #953)

Possibly related PRs

  • Fix: Rename earn to DeFi in navigation bar #958: The changes in the main PR involve minor formatting adjustments in the Page component, while the retrieved PR modifies the Navbar component. Both PRs focus on formatting and maintain the overall functionality of their respective components, indicating a shared emphasis on code consistency and readability.

Suggested reviewers

  • fricoben

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint (1.23.1)

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

app/not-connected/page.tsx

Oops! Something went wrong! :(

ESLint: 9.15.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (12)
components/UI/iconsComponents/icons/walletIcons.tsx (2)

11-18: Simplified rendering logic improves maintainability.

The refactored code successfully:

  1. Eliminates multiple conditional checks
  2. Removes redundant SVG declarations
  3. Uses a more maintainable image-based approach

However, consider adding error boundaries or fallback UI for cases where the image fails to load.

Consider adding an onError handler:

 <img
   src={walletInfo.icon}
   alt={walletInfo.name}
   className={styles.button_icon}
+  onError={(e) => {
+    e.currentTarget.onerror = null;
+    e.currentTarget.src = '/fallback-wallet-icon.png';
+  }}
 />

6-8: Consider adding prop validation.

Since the component relies on the id prop to fetch wallet information, consider adding runtime validation to ensure the provided id is valid.

 type WalletIconsProps = {
-  id: string;
+  id: string & keyof ReturnType<typeof getWalletInfo>;
 };
app/provider.tsx (3)

4-6: Consider consolidating wallet-related imports

Since we're moving towards a centralized wallet configuration, consider re-exporting the wallet connectors from @utils/walletConfig to reduce the number of direct imports from starknetkit.

-import { InjectedConnector } from "starknetkit/injected";
-import { WebWalletConnector } from "starknetkit/webwallet";
-import { ArgentMobileConnector } from "starknetkit/argentMobile";
 import { getConnectors } from "@utils/walletConfig";

Also applies to: 23-23


Line range hint 42-48: Consider centralizing network configuration

The RPC URL configuration could be moved to the centralized configuration approach, similar to the wallet management.

Consider creating a network configuration utility that manages all network-related settings:

// utils/networkConfig.ts
export const getNetworkConfig = (network: string) => ({
  chain: network === "TESTNET" ? sepolia : mainnet,
  rpc: {
    nodeUrl: process.env.NEXT_PUBLIC_RPC_URL
  }
});

Consider disabling cross-origin iframe recording or implementing content restrictions

The codebase search reveals no embedded iframes, suggesting that the cross-origin iframe recording configuration is likely unnecessary for the current application. Since enabling this feature could potentially capture sensitive data from third-party content if iframes are added in the future, consider either:

  • Disabling the cross-origin iframe recording by setting recordCrossOriginIframes: false
  • Or, if iframe support is planned, implementing a content security policy (CSP) and maintaining a whitelist of allowed iframe sources
🔗 Analysis chain

Line range hint 26-36: Review security implications of cross-origin iframe recording

The PostHog configuration enables recording of cross-origin iframes. This could potentially capture sensitive user data from third-party content.


The previous search didn't yield results, so I'm broadening the search to:

  1. Look for any iframe-related code using case-insensitive pattern
  2. Look for PostHog configuration files that might provide more context about the iframe recording setup
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential sensitive iframes in the codebase
rg -l '<iframe' | while read -r file; do
  echo "=== $file ==="
  rg -A 2 '<iframe' "$file"
done

Length of output: 32


Script:

#!/bin/bash
# Let's check for iframe-related code patterns more broadly
rg -i 'iframe|frame' -A 2

# Also check for any PostHog configuration files
fd -e js -e ts -e tsx -e json posthog

Length of output: 10385

tests/utils/walletConfig.test.js (4)

7-16: Consider migrating to TypeScript for better type safety.

The MockConnector class could benefit from TypeScript interfaces to ensure it correctly implements the wallet connector interface. This would make the tests more maintainable and catch potential interface mismatches early.

interface WalletConnector {
  id: string;
  name: string;
  available(): boolean;
}

class MockConnector implements WalletConnector {
  constructor(
    public readonly id: string,
    public readonly name: string,
    private readonly isAvailable: boolean
  ) {}

  available(): boolean {
    return this.isAvailable;
  }
}

18-63: Add edge cases to strengthen test coverage.

The sortConnectors tests cover the main scenarios well. Consider adding these edge cases:

  1. Single connector array
  2. Array with duplicate connector IDs
  3. Null/undefined values in the array
it("should handle array with a single connector", () => {
  const connectors = [new MockConnector("braavos", "Braavos", true)];
  const sortedConnectors = sortConnectors(connectors);
  expect(sortedConnectors).toHaveLength(1);
  expect(sortedConnectors[0].name).toBe("Braavos");
});

it("should handle array with null/undefined values", () => {
  const connectors = [
    new MockConnector("braavos", "Braavos", true),
    null,
    undefined
  ];
  const sortedConnectors = sortConnectors(connectors);
  expect(sortedConnectors).toHaveLength(1);
  expect(sortedConnectors[0].name).toBe("Braavos");
});

65-87: Improve test readability by extracting SVG constants.

The inline SVG data URLs make the tests harder to read and maintain. Consider extracting them to constants or a separate test fixtures file.

// walletFixtures.js
export const WALLET_ICONS = {
  argentX: "data:image/svg+xml;base64,...",
  braavos: "data:image/svg+xml;base64,...",
};

// walletConfig.test.js
import { WALLET_ICONS } from './walletFixtures';

it("should return the icon for a wallet when the ID matches", () => {
  expect(getConnectorIcon("argentX")).toBe(WALLET_ICONS.argentX);
  expect(getConnectorIcon("braavos")).toBe(WALLET_ICONS.braavos);
});

124-147: Consider using a browser environment simulator.

Instead of manually setting up the navigator object, consider using Jest's browser environment simulator or a dedicated testing library like jest-environment-jsdom.

/**
 * @jest-environment jsdom
 */

describe("getConnectorDiscovery function", () => {
  it("should return the correct download link for the user's browser if available", () => {
    // The browser environment is automatically set up
    expect(getConnectorDiscovery("braavos")).toBe(
      "https://chrome.google.com/webstore/detail/braavos-wallet/jnlgamecbpmbajjfhmmmlhejkemejdma"
    );
  });
});
components/UI/navbar.tsx (2)

300-316: Consider extracting social links to configuration

The social media links could be moved to a configuration file to maintain consistency with the centralization approach and make updates easier to manage.

Consider creating a configuration like this:

// config/social.ts
export const socialLinks = {
  twitter: {
    url: "https://twitter.com/starknet_quest",
    icon: FaTwitter,
    ariaLabel: "Follow us on Twitter"
  },
  discord: {
    url: "https://discord.gg/byEGk6w6T6",
    icon: FaDiscord,
    ariaLabel: "Join our Discord community"
  }
};

Line range hint 264-296: Enhance mobile navigation accessibility

The mobile navigation menu could benefit from improved accessibility:

  1. Add ARIA labels for screen readers
  2. Ensure proper focus management when menu opens/closes
  3. Add keyboard navigation support

Consider these improvements:

 <div
   className={
     nav
       ? "mt-24 lg:hidden fixed left-0 top-0 w-full h-screen bg-black/10 z-10"
       : ""
   }
+  role="dialog"
+  aria-modal="true"
+  aria-label="Mobile navigation menu"
 >
utils/walletConfig.ts (1)

148-148: Remove console.log statement from production code

The console.log({ connectors }); statement may expose internal details and is generally not recommended in production environments. Consider removing or replacing it with a proper logging mechanism if debugging is needed.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0ae9da3 and cdd42a2.

📒 Files selected for processing (9)
  • app/not-connected/page.tsx (2 hunks)
  • app/provider.tsx (4 hunks)
  • components/UI/iconsComponents/icons/walletIcons.tsx (1 hunks)
  • components/UI/navbar.tsx (8 hunks)
  • tests/utils/connectors.test.js (0 hunks)
  • tests/utils/walletConfig.test.js (1 hunks)
  • types/frontTypes.d.ts (1 hunks)
  • utils/connectors.ts (0 hunks)
  • utils/walletConfig.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • tests/utils/connectors.test.js
  • utils/connectors.ts
✅ Files skipped from review due to trivial changes (2)
  • app/not-connected/page.tsx
  • types/frontTypes.d.ts
🧰 Additional context used
🪛 Biome (1.9.4)
tests/utils/walletConfig.test.js

[error] 121-121: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (7)
components/UI/iconsComponents/icons/walletIcons.tsx (1)

4-4: LGTM! Import aligns with centralization objective.

The import of getWalletInfo from the centralized wallet configuration aligns perfectly with the PR's objective of centralizing wallet management.

Let's verify the implementation of getWalletInfo:

✅ Verification successful

Import and implementation verified - good centralization approach

The verification confirms that:

  • getWalletInfo is properly implemented in utils/walletConfig.ts and returns wallet data from a centralized configuration
  • The function provides necessary wallet properties (icon, name) used by the WalletIcons component
  • The implementation aligns with the centralization goal by:
    • Using a single source of truth for wallet data
    • Providing consistent wallet information across components
    • Supporting the simplified rendering approach with img tags
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the getWalletInfo implementation and its exported properties

# Check the implementation of getWalletInfo
ast-grep --pattern 'export function getWalletInfo($_) {
  $$$
}'

# Verify the type definitions for wallet info
ast-grep --pattern 'type $_ = {
  icon?: $_
  name?: $_
  $$$
}'

Length of output: 133


Script:

#!/bin/bash
# Let's try a different approach to locate the getWalletInfo implementation

# Search for files containing getWalletInfo
rg "getWalletInfo" -l

# Search for the actual implementation with context
rg "getWalletInfo" -A 5

# Look for wallet-related type definitions
rg "type.*Wallet" -A 5

Length of output: 3774

app/provider.tsx (2)

38-38: Verify the implementation of getConnectors

The change aligns with the centralization objective. Let's verify the implementation ensures all previously supported wallets are still available.

✅ Verification successful

Implementation of getConnectors is properly centralized and includes all supported wallets

The implementation in utils/walletConfig.ts shows that all previously supported wallets are still available:

  • Braavos and Argent X injected connectors
  • Bitget Wallet connector
  • OKX Wallet connector
  • Web Wallet connector (Argent Web)
  • Argent Mobile connector
  • Keplr connector

The centralization objective has been achieved while maintaining full wallet support. The implementation includes proper configuration for each wallet including icons, download links and discovery URLs.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the implementation of getConnectors
echo "=== Checking getConnectors implementation ==="
ast-grep --pattern 'export function getConnectors() {
  $$$
}'

# Check for any direct wallet connector usage that might have been missed
echo "=== Checking for remaining direct wallet connector usage ==="
rg "new (InjectedConnector|WebWalletConnector|ArgentMobileConnector)"

Length of output: 863


Script:

#!/bin/bash
# Let's check the getConnectors implementation in walletConfig.ts
echo "=== Checking getConnectors in walletConfig.ts ==="
cat utils/walletConfig.ts

# Also check if there are any other files defining getConnectors
echo "=== Checking for other getConnectors definitions ==="
rg "function getConnectors"

Length of output: 33572


Line range hint 103-120: Verify provider composition order

The nesting order of providers can affect context availability. Let's verify that the current composition meets all dependencies.

✅ Verification successful

Let me analyze the provider dependencies based on the context usage results:

  1. StarknetConfig is correctly placed as the outermost provider since useAccount, useContract, and other Starknet-related hooks are used extensively throughout the application, including within other context providers.

  2. NotificationProvider is correctly placed after LocalizationProvider as it doesn't depend on other contexts except StarknetConfig (it uses useAccount).

  3. PostHogProvider and QuestsContextProvider are correctly placed as they depend on upper-level contexts:

    • QuestsContextProvider uses useAccount from StarknetConfig
    • Their placement after NotificationProvider is fine as they don't have circular dependencies

Let me verify the ThemeProvider dependencies:


Let me check for Material-UI theme and date-related component usage since the previous search didn't yield results:


Provider composition order is correctly structured

The current provider nesting order is optimal based on the dependencies found:

  1. StarknetConfig (outermost) - Correctly placed as it provides core functionality (useAccount, useContract) used by other providers and components
  2. StarknetIdJsProvider - Properly placed after StarknetConfig
  3. LocalizationProvider - Correctly positioned as it provides date-time functionality used by DateTimePicker components
  4. NotificationProvider - Appropriately placed as it depends on StarknetConfig (useAccount)
  5. ThemeProvider - Correctly positioned as it provides MUI theming used across many components
  6. PostHogProvider - Properly placed as it has no specific dependencies
  7. QuestsContextProvider (innermost) - Correctly placed as it depends on StarknetConfig (useAccount)

The composition ensures all context dependencies are satisfied, and there are no circular dependencies between providers.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for context usage within providers
echo "=== Checking StarknetConfig context usage ==="
rg -A 2 "useStarknet|useContract|useAccount"

echo "=== Checking NotificationProvider context usage ==="
rg -A 2 "useNotification"

echo "=== Checking QuestsContextProvider context usage ==="
rg -A 2 "useQuests"

Length of output: 20295


Script:

#!/bin/bash
# Check for theme context usage and dependencies
echo "=== Checking ThemeProvider usage ==="
rg -A 2 "useTheme"

echo "=== Checking LocalizationProvider usage ==="
rg -A 2 "useDateAdapter|useLocalization"

Length of output: 241


Script:

#!/bin/bash
# Check for MUI theme and date components usage
echo "=== Checking MUI theme usage ==="
rg "@mui/material"

echo "=== Checking date-related components usage ==="
rg "DatePicker|TimePicker|Calendar"

Length of output: 5642

tests/utils/walletConfig.test.js (1)

89-110: LGTM! Comprehensive test coverage for wallet names.

The tests cover all wallet types and edge cases effectively.

components/UI/navbar.tsx (2)

34-34: LGTM: Import path update aligns with centralization goal

The updated import path for sortConnectors from @utils/walletConfig aligns with the PR objective of centralizing wallet configuration.


34-34: Verify wallet connection flow with new configuration

The wallet connection logic uses the new centralized configuration. Let's verify that all wallet connectors are properly initialized and working.

Also applies to: 71-82

✅ Verification successful

Let me gather more information about the wallet configuration implementation to ensure there are no issues.


Let me check the wallet configuration implementation and its usage to ensure there are no issues.


Based on the analysis of the code, I can now provide the final response:

Wallet configuration and connection flow is properly implemented

The wallet connection implementation is correctly using the centralized configuration:

  • The sortConnectors function from @utils/walletConfig is properly imported and used with StarknetKit
  • Wallet connection is handled through StarknetKit's modal which uses the sorted connectors
  • No circular dependencies are found in the wallet configuration
  • The connector persistence is properly managed through localStorage
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining references to the old connector configuration
rg -g '!*.{json,md}' -l 'from.*@utils/connectors'

# Verify consistent usage of sortConnectors
rg -g '*.{ts,tsx}' 'sortConnectors'

# Check for any potential circular dependencies
ast-grep --pattern 'import { $_ } from "@utils/walletConfig"'

Length of output: 677


Script:

#!/bin/bash
# Check the implementation of wallet configuration
cat utils/walletConfig.ts

# Check the usage in navbar component
cat components/UI/navbar.tsx

# Look for any wallet-related hooks or context usage
rg -g '*.{ts,tsx}' 'useConnect|useAccount' -A 2

Length of output: 57398


Script:

#!/bin/bash
# Check the implementation of wallet connection in navbar
rg -A 5 'connectWallet' components/UI/navbar.tsx

# Check for any potential circular dependencies in wallet config
rg -g '*.{ts,tsx}' -A 3 'from.*@utils/walletConfig'

# Check the implementation of StarknetKit modal
rg -g '*.{ts,tsx}' 'starknetkitConnectModal'

Length of output: 1969

utils/walletConfig.ts (1)

122-122: Ensure 'NEXT_PUBLIC_APP_LINK' environment variable is set

The url option relies on process.env.NEXT_PUBLIC_APP_LINK. Please verify that this environment variable is defined in all environments to prevent runtime errors during runtime.

Comment on lines 113 to 122
beforeEach(() => {
global.navigator = {
userAgent:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
};
});

afterEach(() => {
delete global.navigator;
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve test cleanup to avoid performance impact.

The delete operator usage in cleanup could impact performance. Consider using undefined assignment instead.

  afterEach(() => {
-   delete global.navigator;
+   global.navigator = undefined;
  });
📝 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
beforeEach(() => {
global.navigator = {
userAgent:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
};
});
afterEach(() => {
delete global.navigator;
});
beforeEach(() => {
global.navigator = {
userAgent:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
};
});
afterEach(() => {
global.navigator = undefined;
});
🧰 Tools
🪛 Biome (1.9.4)

[error] 121-121: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

utils/walletConfig.ts Show resolved Hide resolved
utils/walletConfig.ts Show resolved Hide resolved
utils/walletConfig.ts Show resolved Hide resolved
Copy link
Contributor

@fricoben fricoben left a comment

Choose a reason for hiding this comment

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

Cool ! Some comments made by IA and me but we'll be good soon :)

: notAvailable.push(connector);
});

console.log({ connectors });
Copy link
Contributor

Choose a reason for hiding this comment

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

delete

];

// Check if the Bitget wallet is available on the window object
const isBitgetWalletInstalled = () =>
Copy link
Contributor

Choose a reason for hiding this comment

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

why does this function exist only for bitget? It seems to work just fine to update message based on installation for others so we need to figure this out to have the same way of working than for others

Copy link
Contributor Author

@Abeeujah Abeeujah Nov 25, 2024

Choose a reason for hiding this comment

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

The function exists to check if Bitget is installed or not, this is because starknetkit doesn't support bitget atm, It's also the cause of the bug where if you click on Install Bitget Wallet nothing happens; because every other injected wallet option has their own download site specified, but again, because bitget isn't supported, there's no download link, and as such, no link tag is generated for it.

Copy link
Contributor

Choose a reason for hiding this comment

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

Oh I see ok thx

@fricoben fricoben added the ❌ Change request Change requested from reviewer label Nov 24, 2024
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

🧹 Outside diff range and nitpick comments (6)
components/UI/iconsComponents/icons/walletIcons.tsx (1)

11-18: Verify wallet icon accessibility and loading.

The refactored implementation looks cleaner and aligns with the centralization goal. However, we should ensure proper error handling for icon loading and accessibility.

Consider these improvements:

 const WalletIcons: FunctionComponent<WalletIconsProps> = ({ id }) => {
   const walletInfo = getWalletInfo(id);
   return walletInfo?.icon ? (
     <img
       src={walletInfo.icon}
       alt={walletInfo.name}
+      loading="lazy"
+      onError={(e) => {
+        e.currentTarget.style.display = 'none';
+      }}
       className={styles.button_icon}
     />
   ) : null;
 };

The changes will:

  • Optimize performance with lazy loading
  • Handle gracefully when icons fail to load
tests/utils/walletConfig.test.js (2)

18-63: Consider adding edge case tests for sortConnectors.

While the current test coverage is good, consider adding tests for:

  • Handling null/undefined input
  • Handling invalid connector objects (missing required methods)
 describe("sortConnectors function", () => {
+  it("should handle null/undefined input", () => {
+    expect(sortConnectors(null)).toEqual([]);
+    expect(sortConnectors(undefined)).toEqual([]);
+  });
+
+  it("should handle invalid connector objects", () => {
+    const invalidConnectors = [
+      { id: "invalid", name: "Invalid" },
+      new MockConnector("valid", "Valid", true)
+    ];
+    expect(() => sortConnectors(invalidConnectors)).not.toThrow();
+  });

   // existing tests...
 });

113-118: Consider using a more maintainable approach for browser detection.

Instead of directly manipulating global.navigator, consider introducing a browser detection utility that can be easily mocked in tests.

+ // Add to utils/browser.js
+ export const getBrowserInfo = () => ({
+   userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
+ });

  beforeEach(() => {
-   global.navigator = {
-     userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
-   };
+   jest.mock('../utils/browser', () => ({
+     getBrowserInfo: () => ({
+       userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
+     })
+   }));
  });
utils/walletConfig.ts (3)

113-118: Consider moving hardcoded URLs to configuration

The WebWalletConnector URLs are hardcoded. Consider moving these to a configuration object or environment variables for better maintainability.

+const WEBWALLET_URLS = {
+  TESTNET: "https://web.hydrogen.argent47.net",
+  MAINNET: "https://web.argent.xyz/"
+};

 new WebWalletConnector({
   url:
     getCurrentNetwork() === "TESTNET"
-      ? "https://web.hydrogen.argent47.net"
-      : "https://web.argent.xyz/",
+      ? WEBWALLET_URLS.TESTNET
+      : WEBWALLET_URLS.MAINNET,
 }),

138-155: Consider moving hardcoded connector order to configuration

The order array in sortConnectors is hardcoded. Consider moving this to a configuration constant for better maintainability.

+const CONNECTOR_SORT_ORDER = ["okxwallet", "bitkeep"] as const;

 export const sortConnectors = (connectors: Connector[]): Connector[] => {
   const available: Connector[] = [];
   const notAvailable: Connector[] = [];

   connectors.forEach((connector) => {
     connector.available()
       ? available.push(connector)
       : notAvailable.push(connector);
   });

   return [
     ...available,
     ...notAvailable.sort((a, b) => {
-      const order = ["okxwallet", "bitkeep"];
-      return order.indexOf(a.id) - order.indexOf(b.id);
+      return CONNECTOR_SORT_ORDER.indexOf(a.id as typeof CONNECTOR_SORT_ORDER[number]) 
+        - CONNECTOR_SORT_ORDER.indexOf(b.id as typeof CONNECTOR_SORT_ORDER[number]);
     }),
   ];
 };

1-173: Great implementation of centralized wallet configuration!

The implementation successfully achieves the PR objective of centralizing wallet configurations. The code is well-structured, properly typed, and includes comprehensive documentation. The utility functions provide a clean API for wallet management.

Consider creating a separate configuration file for constants like URLs and sort orders to improve maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cdd42a2 and b22361c.

📒 Files selected for processing (9)
  • app/not-connected/page.tsx (2 hunks)
  • app/provider.tsx (4 hunks)
  • components/UI/iconsComponents/icons/walletIcons.tsx (1 hunks)
  • components/UI/navbar.tsx (8 hunks)
  • tests/utils/connectors.test.js (0 hunks)
  • tests/utils/walletConfig.test.js (1 hunks)
  • types/frontTypes.d.ts (1 hunks)
  • utils/connectors.ts (0 hunks)
  • utils/walletConfig.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • tests/utils/connectors.test.js
  • utils/connectors.ts
✅ Files skipped from review due to trivial changes (1)
  • components/UI/navbar.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
  • app/not-connected/page.tsx
  • app/provider.tsx
  • types/frontTypes.d.ts
🔇 Additional comments (8)
components/UI/iconsComponents/icons/walletIcons.tsx (2)

4-4: LGTM! Import aligns with centralization goal.

The import of getWalletInfo from @utils/walletConfig aligns with the PR objective of centralizing wallet configurations.

Let's verify the path resolution and implementation:

✅ Verification successful

Import and implementation verified successfully

The import of getWalletInfo from @utils/walletConfig is correctly implemented and used in the WalletIcons component. The function is properly defined in walletConfig.ts and returns wallet information including icons and names. The component uses this centralized configuration to render wallet icons dynamically, aligning with the PR's goal of configuration centralization.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the module path resolution and implementation
fd -e ts -e tsx -g "*walletConfig*" 

# Check the getWalletInfo implementation
ast-grep --pattern 'export const getWalletInfo = $_' -A 10

Length of output: 856


Script:

#!/bin/bash
# Let's verify the usage of getWalletInfo in walletIcons.tsx
ast-grep --pattern 'const WalletIcons = $_' -A 10 components/UI/iconsComponents/icons/walletIcons.tsx

# Check if there are any other components using getWalletInfo
rg "getWalletInfo" --type ts --type tsx

Length of output: 171


Script:

#!/bin/bash
# Let's try with just the file extension without type specification
rg "getWalletInfo"

# And check the content of both files to understand the implementation
cat components/UI/iconsComponents/icons/walletIcons.tsx
cat utils/walletConfig.ts

Length of output: 34425


11-18: Verify complete wallet coverage and styling compatibility.

Since we're moving from inline SVGs to dynamic images, let's ensure:

  1. All wallet types have corresponding icons
  2. The CSS styles in styles.button_icon work consistently with image elements

Let's verify the implementation:

✅ Verification successful

Let me gather more information about the wallet configuration and CSS styles.


Let me check the wallet configuration and implementation to ensure complete coverage.


Let me check one final thing to verify the wallet configuration data.


Implementation verified - icon handling and styling are properly configured

The verification shows:

  1. The button_icon CSS class is properly defined with appropriate width and margin properties that work for both SVG and image elements
  2. Wallet configuration is complete with icons defined for each wallet type (e.g., Argent X shown in the output)
  3. The getWalletInfo function correctly retrieves wallet data including icons
  4. The component properly handles cases where icons might be missing with the null fallback
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for all wallet definitions and their icon properties
ast-grep --pattern 'export const walletConfig = {
  $$$
}'

# Verify the CSS class definition
rg "button_icon" -g "*.css" -g "*.scss"

Length of output: 150


Script:

#!/bin/bash
# Check the content of the CSS class
cat styles/components/icons.module.css

# Look for getWalletInfo implementation and wallet types
ast-grep --pattern 'function getWalletInfo($_) {
  $$$
}'

# Search for wallet type definitions or enums
rg -A 5 "type.*Wallet" 

Length of output: 2774


Script:

#!/bin/bash
# Check wallet configuration and INSTALLABLE_WALLETS
rg "INSTALLABLE_WALLETS.*=" -A 5

# Look for walletConfig implementation
ast-grep --pattern 'export const walletConfig = {
  $_: {
    $$$
  }
}'

# Check getWalletInfo implementation
rg "getWalletInfo" -A 5

Length of output: 2426


Script:

#!/bin/bash
# Look for wallets array definition
rg "const wallets.*=" -A 15

# Check if there are any other wallet icon implementations
rg -g "!*.test.*" -g "!*.spec.*" "wallet.*icon" -A 2

Length of output: 3061

tests/utils/walletConfig.test.js (4)

7-16: LGTM! Well-structured mock implementation.

The MockConnector class provides a clean and minimal implementation necessary for testing wallet connector functionality.


65-87: LGTM! Comprehensive icon retrieval tests.

Test cases cover all necessary scenarios including successful cases, fallbacks, and edge cases.


89-110: LGTM! Well-structured name retrieval tests.

Test cases effectively validate the centralized wallet naming configuration.


120-122: Improve test cleanup to avoid performance impact.

As previously noted, using the delete operator can impact performance. Consider using undefined assignment instead.

  afterEach(() => {
-   global.navigator = undefined;
+   Object.defineProperty(global, 'navigator', {
+     value: undefined,
+     configurable: true
+   });
  });
utils/walletConfig.ts (2)

1-18: LGTM! Clean imports and type definitions

The imports are well-organized and the type definitions are properly structured with clear interfaces.


20-92: LGTM! Well-structured wallet configurations

The wallet configurations are comprehensive and include all necessary metadata for each supported wallet.

@Abeeujah Abeeujah requested a review from fricoben November 25, 2024 15:37
Copy link
Contributor

@fricoben fricoben left a comment

Choose a reason for hiding this comment

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

lgtm

@fricoben fricoben merged commit 6cbc0f1 into lfglabs-dev:testnet Nov 26, 2024
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
❌ Change request Change requested from reviewer
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Simplify our wallet management system by creating a centralized configuration
2 participants