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

token: add icons and verified badge #23

Merged
merged 13 commits into from
Oct 11, 2024
Merged

token: add icons and verified badge #23

merged 13 commits into from
Oct 11, 2024

Conversation

temptemp3
Copy link
Contributor

@temptemp3 temptemp3 commented Oct 11, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced TokenCard component with new icons and tooltips for better user interaction.
    • Introduced a badge to indicate token verification status.
    • Added external links for token transactions based on token ID.
    • Improved conditional rendering for the "Create Pool" button based on token type.
    • Streamlined Pool component logic for better pool management.
    • Updated Navbar component by removing the settings menu for a cleaner interface.
    • Improved layout responsiveness in TokenList and PoolList components.
    • Added responsive styling capabilities to various components using Material-UI's Box and Grid.
    • Introduced exact swap methods in the Swap component for enhanced token swapping functionality.
    • Enhanced TokenInput component with improved token display logic and styling.
    • Updated styling in the Swap component for better visual presentation.
    • Added new styled components and improved layout in various components for better user experience.
  • Bug Fixes

    • Adjusted display logic for token ID to show displayTokenId instead of contractId when applicable.

Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

Walkthrough

The changes involve multiple components across the application, including the Navbar, Pool, PoolCard, PoolList, Token, TokenCard, TokenList, and the Default layout. Key modifications include the removal of the SettingMenu from the Navbar, simplification of logic in the Pool component, and significant updates to the PoolCard and TokenCard for enhanced UI and functionality. Material-UI components are increasingly utilized for better layout and responsiveness. Additionally, the Default layout now has a modified container width.

Changes

File Path Change Summary
src/components/Navbar/index.tsx - Commented out the rendering of <SettingMenu />, removing it from the account button group.
src/components/Pool/index.tsx - Removed commented-out code for uniqPools.
- Cleared specific pool IDs from badPools.
- Adjusted filteredPools and filteredPositions computations.
src/components/PoolCard/index.tsx - Removed imports related to Redux actions.
- Simplified token data fetching logic.
- Replaced div elements with Box components.
- Introduced conditional rendering for token icons and badges.
src/components/PoolList/index.tsx - Updated Material-UI import to include Grid.
- Changed HeadingRow and Columns to use Box.
- Removed width property from PopularPoolsRoot.
src/components/Token/index.tsx - Added commented-out CSS code to TokenRoot.
- Retained core functionality and data fetching logic.
src/components/TokenCard/index.tsx - Added imports for Tooltip, OpenInNewIcon, and VerifiedUserIcon.
- Removed spec object.
- Introduced new styled component TokenIcon.
- Updated rendering logic for token icons and badges.
- Added external link for token transactions.
src/components/TokenList/index.tsx - Changed Columns from styled.div to styled(Box).
- Updated styling for responsive display.
src/layouts/Default.tsx - Added maxWidth="lg" prop to the Container component.

Possibly related PRs

  • add HLogo #9: The changes in this PR also modify the Navbar component in src/components/Navbar/index.tsx, specifically altering the rendering logic, which is directly related to the changes made in the main PR.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d25c55e and 1e9411a.

📒 Files selected for processing (1)
  • src/components/TokenCard/index.tsx (4 hunks)
🧰 Additional context used
🔇 Additional comments (5)
src/components/TokenCard/index.tsx (5)

15-15: Add imports for Material UI components

The added imports for Fade, Skeleton, and Tooltip from @mui/material enhance the UI components and functionalities within the TokenCard component.


23-24: Import new icons for external links and verification badges

The imported icons OpenInNewIcon and VerifiedUserIcon from @mui/icons-material will be used to indicate external links and token verification status, improving the visual cues in the UI.


245-249: Create TokenIcon styled component

The TokenIcon styled component is correctly defined to standardize the styling of token icons across the application.


412-416: Construct external link based on token properties

The externalLink is appropriately constructed using the tokenId or contractId, directing users to the correct explorer page based on whether the token is an asset or application.


542-547: Verify the necessity and correct usage of getToken in onClick handler

The getToken function is being called and awaited inside the onClick handler. Please verify if this call is necessary and if getToken is correctly used in this context. If getToken is a Redux action, it should be dispatched using dispatch.

To confirm the usage of getToken, you can run the following script:

If getToken is an action creator, you should dispatch it like this:

-onClick={async () => {
-  await getToken(token.contractId);
-  navigate(
-    `/pool/create?tokBId=0&tokAId=${token?.contractId}`
-  );
-}}
+const dispatch = useDispatch();
+onClick={async () => {
+  await dispatch(getToken(token.contractId));
+  navigate(
+    `/pool/create?tokBId=0&tokAId=${token?.contractId}`
+  );
+}}

If the call to getToken is unnecessary, consider removing it to simplify the code.

✅ Verification successful

Verification of getToken Usage Confirmed

The getToken function is a standalone asynchronous function exported from src/store/tokenSlice.ts. It is not a Redux action creator and does not require dispatching. Therefore, its usage within the onClick handler is appropriate.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if getToken is a Redux action creator or a selector.

# Test: Search for the definition of getToken in the codebase.
rg --type typescript 'export (const|function) getToken' src/store/

Length of output: 103


Script:

#!/bin/bash
# Description: Corrected search for getToken definition in the codebase.

# Test: Search for the definition of getToken in the codebase using the correct file type.
rg --type ts 'export (const|function) getToken' src/store/

Length of output: 204

src/components/TokenCard/index.tsx Show resolved Hide resolved
src/components/TokenCard/index.tsx Outdated Show resolved Hide resolved
src/components/TokenCard/index.tsx Outdated Show resolved Hide resolved
src/components/TokenCard/index.tsx Outdated Show resolved Hide resolved
temptemp3 and others added 5 commits October 10, 2024 23:57
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 6

🧹 Outside diff range and nitpick comments (10)
src/components/PoolList/index.tsx (2)

11-11: Consider removing unused imports.

The import statement includes Fade and Stack from @mui/material, but these components are not used in the visible code. Consider removing them to keep the imports clean and avoid potential bundle size increases.


253-274: Consider removing or implementing commented-out Grid layout

There's a significant block of commented-out code introducing a Grid-based layout. If this represents a future direction for the component, consider creating a separate task or issue to track this refactoring. If it's no longer relevant, it would be best to remove it to keep the code clean.

src/components/Pool/index.tsx (2)

Line range hint 1-338: Overall structure looks good, consider extracting some logic.

The overall structure of the Pool component is well-organized and follows good React practices. The use of hooks for state management and side effects is appropriate, and the memoization of filtered pools and positions is a good optimization.

However, the component is quite large and handles multiple responsibilities. Consider extracting some of the logic into custom hooks or separate components to improve maintainability. For example, you could create a custom hook for fetching and managing pool data, and separate components for the "Your Liquidity" and "Popular Pools" views.

Here's a suggestion for extracting the pool data fetching logic into a custom hook:

// usePoolData.ts
import { useState, useEffect } from 'react';
import axios from 'axios';
import { IndexerPoolI } from '../../types';

export const usePoolData = () => {
  const [pools, setPools] = useState<IndexerPoolI[]>([]);

  const fetchPools = () =>
    axios
      .get(`https://mainnet-idx.nautilus.sh/nft-indexer/v1/dex/pools`)
      .then(({ data }) => {
        setPools(
          data.pools.map((p: IndexerPoolI) => ({
            ...p,
            tvl: formatter.format(Number(p.tvl)),
            vol: formatter.format(Number(p.volA) + Number(p.volB)),
          }))
        );
      });

  useEffect(() => {
    fetchPools();
  }, []);

  return { pools, fetchPools };
};

// In Pool component
const { pools, fetchPools } = usePoolData();

This refactoring would help to separate concerns and make the main component more focused on rendering and user interactions.


Line range hint 280-338: Consider unifying the pagination logic.

The current pagination implementation uses separate page states (page and page2) for different views, which could lead to confusion and potential bugs. Consider unifying the pagination logic to make it more maintainable and less error-prone.

Here's a suggestion for a more unified approach:

  1. Create a single usePagination hook that can be used for both views:
const usePagination = (items, pageSize) => {
  const [currentPage, setCurrentPage] = useState(1);
  const totalPages = Math.ceil(items.length / pageSize);
  const paginatedItems = items.slice(0, currentPage * pageSize);

  const loadMore = () => setCurrentPage(prev => Math.min(prev + 1, totalPages));
  const reset = () => setCurrentPage(1);

  return { paginatedItems, loadMore, reset, hasMore: currentPage < totalPages };
};
  1. Use this hook for both pools and positions:
const { 
  paginatedItems: paginatedPools, 
  loadMore: loadMorePools, 
  reset: resetPools,
  hasMore: hasMorePools 
} = usePagination(filteredPools, pageSize);

const { 
  paginatedItems: paginatedPositions, 
  loadMore: loadMorePositions, 
  reset: resetPositions,
  hasMore: hasMorePositions 
} = usePagination(filteredPositions, pageSize);
  1. Update the JSX to use these new functions and values:
{active === 2 && activeAccount ? (
  <>
    <PoolPosition
      positions={paginatedPositions}
      // ... other props ...
    />
    {hasMorePositions ? (
      <ViewMoreButton onClick={loadMorePositions}>
        {/* ... */}
      </ViewMoreButton>
    ) : (
      <GoToTop onClick={resetPositions} />
    )}
  </>
) : null}

{active === 1 ? (
  <>
    <PoolList
      pools={paginatedPools}
      // ... other props ...
    />
    {hasMorePools ? (
      <ViewMoreButton onClick={loadMorePools}>
        {/* ... */}
      </ViewMoreButton>
    ) : (
      <GoToTop onClick={resetPools} />
    )}
  </>
) : null}

This approach simplifies the pagination logic, makes it more reusable, and reduces the chance of inconsistencies between different views.

src/components/TokenList/index.tsx (5)

628-629: Improved responsiveness with Material-UI Box component.

The change from styled.div to styled(Box) and the addition of responsive styling using the sx prop is a good improvement. It enhances the component's flexibility and responsiveness.

Consider extracting the responsive styles into a separate const for better readability:

const columnsResponsiveStyles = { display: { xs: "none", md: "block" } };

// Then use it like this:
<Columns sx={columnsResponsiveStyles}>

This separation of concerns can make the code more maintainable, especially if you plan to add more responsive styles in the future.


Line range hint 4-4: TODO comment: Add tests

There's a TODO comment indicating that tests need to be added. It's important to ensure proper test coverage for the component.

Would you like assistance in generating unit tests for this component? I can help create a basic test suite to get you started.


Line range hint 515-534: Commented-out code for AddTokenButton and CreateTokenButton

There are sections of commented-out code for AddTokenButton and CreateTokenButton. If these features are planned for future implementation, consider using a task management system to track them instead of leaving commented code in the file. If they're no longer needed, it would be best to remove them entirely to keep the codebase clean.


Line range hint 1-638: Mixing styled-components and Material-UI

The component uses a mix of styled-components and Material-UI components. While this is not inherently problematic, it's worth considering standardizing on one approach for consistency. If you're moving towards Material-UI, consider gradually migrating the styled-components to their Material-UI equivalents or using the Material-UI styling solution throughout.


Line range hint 1-638: Consider refactoring for improved maintainability

The TokenList component and this file as a whole are quite large. Consider refactoring to improve maintainability:

  1. Extract smaller components (e.g., ColumnHeaders, TokenListHeader) into separate files.
  2. Move styled components to a separate file (e.g., TokenList.styles.ts).
  3. Consider using a custom hook for state management and data fetching logic.

These changes would make the code more modular, easier to test, and simpler to maintain in the long run.

src/components/PoolCard/index.tsx (1)

461-466: Rename isWVOIf function for clarity

The function name isWVOIf is not descriptive and might lead to confusion. Renaming it to isVOI or isWVOI improves readability and conveys its purpose more clearly.

Apply this diff to rename the function:

- const isWVOIf = (token: any) => {
+ const isVOI = (token: any) => {
    if (token?.contractId === "0") {
      return true;
    }
    return false;
  };

And update its usages accordingly:

- const tokAIcon = isWVOIf(tokA) ? (
+ const tokAIcon = isVOI(tokA) ? (
- const tokBIcon = isWVOIf(tokB) ? (
+ const tokBIcon = isVOI(tokB) ? (
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1e9411a and 0fbc470.

📒 Files selected for processing (8)
  • src/components/Navbar/index.tsx (1 hunks)
  • src/components/Pool/index.tsx (2 hunks)
  • src/components/PoolCard/index.tsx (12 hunks)
  • src/components/PoolList/index.tsx (6 hunks)
  • src/components/Token/index.tsx (1 hunks)
  • src/components/TokenCard/index.tsx (9 hunks)
  • src/components/TokenList/index.tsx (3 hunks)
  • src/layouts/Default.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/components/Navbar/index.tsx
  • src/components/Token/index.tsx
🧰 Additional context used
🪛 Biome
src/components/PoolCard/index.tsx

[error] 472-472: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


[error] 489-489: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


[error] 505-505: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


[error] 516-516: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)

🔇 Additional comments (8)
src/layouts/Default.tsx (1)

15-15: LGTM! Consider verifying layout on various screen sizes.

The addition of maxWidth="lg" to the Container component is a good improvement. It will likely make better use of available screen space on larger displays, which could be beneficial for accommodating new icons and badges mentioned in the PR title.

To ensure the layout change doesn't negatively impact the user experience, please verify the appearance on various screen sizes, particularly:

  1. Mobile devices (small screens)
  2. Tablets (medium screens)
  3. Desktops (large screens)
  4. Extra large displays

You may want to use browser developer tools or a responsive design testing tool to quickly check these different viewport sizes.

src/components/PoolList/index.tsx (3)

48-52: Improved component flexibility with Material-UI Box

The changes to use Material-UI's Box component for HeadingRow, Columns, and Heading are good improvements. They provide more flexibility for styling and layout. The addition of responsive styling for the Heading component is particularly beneficial for adapting to different screen sizes.

Also applies to: 67-72, 76-82


292-292: Improved layout and responsiveness

The addition of padding to HeadingRow and the responsive styling for Heading using the sx prop are good improvements. These changes enhance the layout and ensure better adaptability across different screen sizes.

Also applies to: 294-309


Line range hint 1-324: Overall improvement in component structure and styling

The changes in this file primarily focus on enhancing the PoolList component's structure and styling using Material-UI components. These modifications improve the component's flexibility and responsiveness without altering its core functionality.

Key improvements include:

  1. Adoption of Material-UI's Box component for better styling flexibility.
  2. Enhanced responsiveness through the use of sx props and media queries.
  3. Improved layout with additional padding and structural changes.

While these changes are positive, there are opportunities for further refinement:

  1. Cleaning up unused imports.
  2. Addressing the commented-out Grid-based layout.

Overall, these changes represent a step forward in the component's design and maintainability.

src/components/Pool/index.tsx (3)

23-25: Clarify the reason for commenting out the padding.

The padding for the PoolRoot component has been commented out. This change might affect the layout of the component. Could you please explain the rationale behind this modification? If it's intentional, consider removing the commented code instead of leaving it in place.


Line range hint 1-338: Summary of Pool component review

Overall, the Pool component is well-structured and functional. However, there are a few areas that could be improved:

  1. Clarify the reason for commenting out the padding in the PoolRoot styled component.
  2. Verify the impact of removing the badPools filtering and ensure it doesn't introduce any unintended consequences.
  3. Consider extracting some logic into custom hooks or separate components to improve maintainability, especially for data fetching and management.
  4. Unify and simplify the pagination logic to make it more consistent and less error-prone across different views.

Addressing these points will enhance the component's maintainability, readability, and overall code quality. Great job on the implementation so far!


Line range hint 169-173: Verify the impact of removing badPools filtering.

The badPools array is now empty, and the filtering logic for uniqPools has been simplified. This change might affect which pools are displayed to the user. Please confirm if this is intentional and if there are any potential side effects we should be aware of.

To check the impact of this change, you can run the following script:

This script will help identify any other places in the codebase where badPools might be used or if there are any hardcoded pool IDs that might need attention.

src/components/TokenList/index.tsx (1)

12-12: New import added for Material-UI components.

The addition of Box and Fade from '@mui/material' suggests a move towards using more Material-UI components. This is generally a good practice for consistency and leveraging the Material-UI ecosystem.

src/components/TokenCard/index.tsx Outdated Show resolved Hide resolved
src/components/TokenCard/index.tsx Show resolved Hide resolved
src/components/PoolCard/index.tsx Show resolved Hide resolved
src/components/PoolCard/index.tsx Outdated Show resolved Hide resolved
src/components/PoolCard/index.tsx Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 1

🧹 Outside diff range and nitpick comments (4)
src/components/TokenCard/index.tsx (4)

Line range hint 142-149: Use camelCase for SVG attribute names in JSX

In JSX, SVG attribute names should be written in camelCase. Attributes like fill-rule, clip-rule, fill-opacity, stroke-width, stroke-linecap, and stroke-linejoin should be renamed to fillRule, clipRule, fillOpacity, strokeWidth, strokeLinecap, and strokeLinejoin respectively.

Apply this diff to correct the attribute names in the CryptoIconPlaceholder component:

 <path
-  fill-rule="evenodd"
-  clip-rule="evenodd"
+  fillRule="evenodd"
+  clipRule="evenodd"
   d="M12.6187 7.38128C12.9604 7.72299..."
   fill="#F6F6F8"
 />
 <path
-  fill-opacity="0.01"
+  fillOpacity="0.01"
   d="M4 16C4 12.2725..."
   fill="white"
 />

Repeat these changes in the PlaceHolderIcon, InfoCircleIcon, and PairIconPlaceholder components to ensure all SVG attributes comply with JSX conventions.

Also applies to: 158-165, 169-176, 188-195


Line range hint 405-408: Include missing dependencies in useMemo hook

The useMemo hook depends on token.pools and token.contractId, but they are not included in the dependency array. This can lead to stale or incorrect data if token changes.

Update the dependency array to include token.pools and token.contractId:

 const tokenPools = useMemo(() => {
   if (!pools) return [];
   return token.pools.length > 0
     ? token.pools
     : pools.filter((p) => {
         return !!p && [p.tokA, p.tokB].includes(token.contractId);
       });
-}, [pools]);
+}, [pools, token.pools, token.contractId]);

Line range hint 404-404: Remove console.log statement from production code

There's a console.log statement used for debugging purposes. It's best practice to remove such statements to clean up the console output in production.

Apply this diff to remove the console.log:

 const TokenCard: FC<TokenCardProps> = ({ token }) => {
   const navigate = useNavigate();
   const pools = useSelector((state: RootState) => state.pools.pools);
-  console.log({ pools, token });
   /* Theme */

14-15: Remove unused imports to clean up the code

The following imports appear to be unused in the codebase:

  • UnknownAction from @reduxjs/toolkit (line 14)
  • Skeleton from @mui/material (line 15)
  • display, minWidth from @mui/system (line 25)

Apply this diff to remove the unused imports:

 import styled from "@emotion/styled";
 import React, { FC, useEffect, useMemo, useState } from "react";
-import { RootState } from "../../store/store";
-import { useDispatch, useSelector } from "react-redux";
+import { useSelector } from "react-redux";
 import { ARC200TokenI, PoolI } from "../../types";
 import { Link, useNavigate } from "react-router-dom";
 import { tokenSymbol } from "../../utils/dex";
-import {
-  fetchToken,
-  getToken,
-  getTokens,
-  updateToken,
-} from "../../store/tokenSlice";
-import { UnknownAction } from "@reduxjs/toolkit";
 import { Box, Fade, Stack, Tooltip } from "@mui/material";
 import { CONTRACT, abi } from "ulujs";
 import { getAlgorandClients } from "../../wallets";
 import { TOKEN_WVOI1 } from "../../constants/tokens";
 import BigNumber from "bignumber.js";
 import { stringToColorCode } from "../../utils/string";
 import algosdk from "algosdk";
 import { toast } from "react-toastify";
-import OpenInNewIcon from "@mui/icons-material/OpenInNew";
-import VerifiedUserIcon from "@mui/icons-material/VerifiedUser";
-import { display, minWidth } from "@mui/system";

Ensure that any other unused imports are also removed for better code maintenance.

Also applies to: 25-25

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0fbc470 and c58e8a5.

📒 Files selected for processing (1)
  • src/components/TokenCard/index.tsx (9 hunks)
🧰 Additional context used

src/components/TokenCard/index.tsx Outdated Show resolved Hide resolved
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 (5)
src/components/TokenCard/index.tsx (4)

15-24: LGTM! UI enhancements with Material-UI components

The addition of Material-UI components and the new TokenIcon styled component improve the overall UI consistency and functionality. The changes to existing styled components to use Material-UI's Box component are also good for maintaining consistency with the Material-UI ecosystem.

Consider adding an alt prop to the TokenIcon styled component for better accessibility:

-const TokenIcon = styled.img`
+const TokenIcon = styled.img.attrs({
+  alt: (props: { alt?: string }) => props.alt || 'Token icon',
+})`
  height: 32px;
  width: 32px;
  border-radius: 50%;
`;

Also applies to: 248-252, 305-313, 328-332


415-418: Rename utility function for clarity

The function isWVOIf could be renamed to improve readability and consistency.

Consider renaming isWVOIf to isWVOI and updating its usage:

-const isWVOIf = (contractId: number) => {
+const isWVOI = (contractId: number) => {
   return [TOKEN_WVOI1].includes(contractId);
 };
-const isWVOI = isWVOIf(token.contractId);
+const isWVOIToken = isWVOI(token.contractId);

This change makes the function name more descriptive and consistent with its usage.


Line range hint 461-597: Optimize rendering logic and improve responsiveness

The rendering logic has been significantly improved, but there are opportunities for further optimization and better responsiveness.

Consider the following improvements:

  1. Use Material-UI's Grid component for better responsiveness:
<Grid container spacing={2}>
  <Grid item xs={12} sm={6} md={4}>
    {/* Col1 content */}
  </Grid>
  <Grid item xs={12} sm={6} md={2}>
    {/* Col3 content */}
  </Grid>
  {/* ... other columns */}
</Grid>
  1. Use Material-UI's Hidden component instead of custom responsive styles:
<Hidden smDown>
  <Col3>
    {/* Content visible on sm and larger screens */}
  </Col3>
</Hidden>
  1. Simplify conditional rendering using early returns:
if (!tokenPools.length) {
  return (
    <Col5>
      {!isWVOI && (
        <StyledLink to="" style={{ width: "100%" }}>
          <AddButton onClick={handleCreatePool}>
            <ButtonLabelContainer>
              <AddButtonLabel>Create Pool</AddButtonLabel>
            </ButtonLabelContainer>
          </AddButton>
        </StyledLink>
      )}
    </Col5>
  );
}

// Rest of the rendering logic for when tokenPools.length > 0

These changes will make the component more maintainable and improve its responsiveness across different screen sizes.


Line range hint 401-629: Optimize component structure and performance

The TokenCard component has grown in complexity, which could lead to performance issues and maintenance difficulties.

Consider the following improvements:

  1. Break down the component into smaller, reusable sub-components:
const TokenInfo = ({ token, isWVOI, badge, icon }) => { /* ... */ };
const TokenStats = ({ token, tokenPools }) => { /* ... */ };
const TokenActions = ({ token, tokenPools, isWVOI }) => { /* ... */ };

const TokenCard = ({ token }) => {
  // ... existing logic ...
  return (
    <Fade in={true} timeout={1500}>
      <PoolCardRoot className={isDarkTheme ? "dark" : "light"}>
        <TokenInfo token={token} isWVOI={isWVOI} badge={badge} icon={icon} />
        <TokenStats token={token} tokenPools={tokenPools} />
        <TokenActions token={token} tokenPools={tokenPools} isWVOI={isWVOI} />
      </PoolCardRoot>
    </Fade>
  );
};
  1. Use React.memo to prevent unnecessary re-renders:
const TokenCard = React.memo(({ token }) => {
  // ... component logic ...
});
  1. Move complex calculations and data fetching to useMemo and useEffect hooks:
const tokenPools = useMemo(() => {
  // ... existing tokenPools logic ...
}, [pools, token.pools, token.contractId]);

useEffect(() => {
  // Fetch additional token data if needed
}, [token.contractId]);
  1. Consider using a reducer for complex state management:
const [state, dispatch] = useReducer(tokenCardReducer, initialState);

// In the component body
useEffect(() => {
  dispatch({ type: 'SET_TOKEN_DATA', payload: token });
}, [token]);

These changes will improve the component's maintainability, readability, and potentially its performance by optimizing renders and calculations.

src/components/PoolCard/index.tsx (1)

523-523: Remove debugging console.log statement

The console.log statement may have been left unintentionally. Debugging statements should be removed from production code to prevent cluttering the console output.

Apply this diff to remove the statement:

- console.log({ pool, balance, tokens, tokA, tokB });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c58e8a5 and 7f70825.

📒 Files selected for processing (2)
  • src/components/PoolCard/index.tsx (12 hunks)
  • src/components/TokenCard/index.tsx (8 hunks)
🧰 Additional context used
🪛 Biome
src/components/PoolCard/index.tsx

[error] 472-472: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


[error] 489-489: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


[error] 505-505: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


[error] 516-516: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)

🔇 Additional comments (1)
src/components/TokenCard/index.tsx (1)

Line range hint 1-629: Summary: Significant improvements with opportunities for refinement

The TokenCard component has undergone substantial changes that enhance its functionality and UI. The introduction of Material-UI components, improved conditional rendering, and better handling of different token types are notable improvements.

Key areas for further refinement include:

  1. Optimizing the component structure by breaking it down into smaller, reusable sub-components.
  2. Improving performance through the use of React.memo, useMemo, and useEffect hooks.
  3. Enhancing responsiveness with Material-UI's Grid and Hidden components.
  4. Ensuring consistent and secure handling of external links and navigation.
  5. Simplifying and optimizing conditional rendering logic.

Addressing these points will result in a more maintainable, performant, and robust component. Overall, the changes represent a positive step forward in the component's evolution.

src/components/TokenCard/index.tsx Show resolved Hide resolved
src/components/TokenCard/index.tsx Show resolved Hide resolved
src/components/PoolCard/index.tsx Show resolved Hide resolved
src/components/PoolCard/index.tsx Outdated Show resolved Hide resolved
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: 16

🧹 Outside diff range and nitpick comments (7)
src/components/TokenInput/index.tsx (1)

467-487: Address alignment issues in the token display layout

The Stack component is used with sx={{ alignItems: "end" }}, which may not correctly align the token label, ID, and badge. Consider adjusting the alignment properties to ensure proper layout across different screen sizes.

Adjust the Stack component to align items appropriately:

-<Stack sx={{ alignItems: "end" }} direction="row" spacing={1}>
+<Stack direction="row" spacing={1} alignItems="center">
src/components/Swap/index.tsx (6)

Line range hint 328-337: Consider removing commented-out code

There's a block of commented-out CSS code within the @media query:

/*
  &.light {
    border: 1px solid
      var(--Color-Neutral-Stroke-Primary-Static-Contrast, #7e7e9a);
    background: var(
      --Color-Canvas-Transparent-white-950,
      rgba(255, 255, 255, 0.95)
    );
  }
*/

If this code is no longer needed, consider removing it to improve code readability. Alternatively, if it's intended for future use, please add a comment explaining its purpose.


604-605: Remove unnecessary console.log statement

The console.log({ tokens2 }); statement seems to be a leftover from debugging:

console.log({ tokens2 });

Consider removing it to clean up the console output in production.


662-664: Simplify token filtering condition

The filtering condition in the token options can be simplified for better readability:

.filter(
  (t: ARC200TokenI) => t.tokenId !== token2?.tokenId && t.symbol !== "wVOI"
);

Ensure that token2 is properly checked before accessing its properties to avoid potential runtime errors.


712-713: Consider removing obsolete commented code

There's a commented-out line that may no longer be needed:

// res < 0.000001 ? [res2, 1, 1 / res2, true] : [1, 1 / res, res, true];

Removing unused code helps maintain code clarity.


Line range hint 1171-1182: Implement the TODO: Show toast notification for swap

There's a TODO comment indicating the need to show a toast notification when initiating a swap:

// TODO show toast

Implementing this will enhance user experience by providing immediate feedback during the swap process.

Would you like assistance in implementing the toast notification?


1261-1262: Remove unnecessary console.log statement

The console.log({ token, token2 }); statement appears to be for debugging purposes. Consider removing it to clean up console output.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7f70825 and 8427f4a.

📒 Files selected for processing (3)
  • src/components/PoolCard/index.tsx (12 hunks)
  • src/components/Swap/index.tsx (16 hunks)
  • src/components/TokenInput/index.tsx (6 hunks)
🧰 Additional context used
🪛 Biome
src/components/PoolCard/index.tsx

[error] 472-472: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


[error] 489-489: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


[error] 505-505: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)


[error] 516-516: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)

src/components/TokenInput/index.tsx

[error] 410-410: Comparing to itself is potentially pointless.

(lint/suspicious/noSelfCompare)

🔇 Additional comments (2)
src/components/Swap/index.tsx (2)

Line range hint 1305-1335: Ensure tokInfo props receive correct data

When passing tokInfo to TokenInput, verify that tokAInfo and tokBInfo contain the expected token information. This ensures that the component displays accurate data.


99-134: Ensure the correctness of added methods in the spec object

The methods Trader_exactSwapAForB and Trader_exactSwapBForA have been added to the spec object. Please verify that their argument types and return types match the backend smart contract implementations to ensure correct functionality.

Run the following script to check for consistency between the method definitions and their usage:

src/components/TokenInput/index.tsx Show resolved Hide resolved
src/components/TokenInput/index.tsx Show resolved Hide resolved
src/components/TokenInput/index.tsx Show resolved Hide resolved
src/components/TokenInput/index.tsx Show resolved Hide resolved
src/components/TokenInput/index.tsx Show resolved Hide resolved
src/components/Swap/index.tsx Show resolved Hide resolved
src/components/Swap/index.tsx Show resolved Hide resolved
src/components/Swap/index.tsx Show resolved Hide resolved
src/components/Swap/index.tsx Show resolved Hide resolved
src/components/Swap/index.tsx Outdated Show resolved Hide resolved
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: 2

🧹 Outside diff range and nitpick comments (5)
src/components/Swap/index.tsx (5)

317-317: Specify targeted properties in CSS transitions

Using transition: all 0.5s; can negatively impact performance by triggering transitions on all properties. Consider specifying only the necessary properties to improve performance.


Line range hint 328-337: Remove commented-out CSS code to enhance readability

The commented-out CSS block from lines 328 to 337 may no longer be needed. Removing unused code helps maintain code clarity.


604-604: Remove unnecessary console.log statement

The console.log({ tokens2 }); appears to be left from debugging and can clutter console output. Consider removing it before deploying to production.


712-713: Clean up commented-out code

There's a commented-out line of code that may not be needed:

// res < 0.000001 ? [res2, 1, 1 / res2, true] : [1, 1 / res, res, true];

Removing unused code enhances readability.


719-721: Review dependencies in useMemo hook

The useMemo hook includes token2 in its dependency array, but token2 isn't used inside the hook. Consider removing it from the dependencies.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ccf2b21 and 12b88bd.

📒 Files selected for processing (1)
  • src/components/Swap/index.tsx (16 hunks)
🧰 Additional context used
🔇 Additional comments (7)
src/components/Swap/index.tsx (7)

99-134: New methods in the spec object are correctly defined

The addition of Trader_exactSwapAForB and Trader_exactSwapBForA methods to the spec object enhances the swapping functionality and appears to be correctly implemented.


325-325: Review duplicate transition property in media query

The transition: all 1s; inside the media query overrides the earlier transition: all 0.5s;. Verify if the different durations are intentional for different screen sizes.


374-379: Adjust the CSS border property in SummaryContainer

The border property lacks a width and style definition:

border: #41137e;

To ensure proper rendering, specify the border width and style:

-  border: #41137e;
+  border: 1px solid #41137e;

838-855: Use BigNumber instead of Number.MAX_SAFE_INTEGER

Number.MAX_SAFE_INTEGER may not suffice for uint256 values. Replace it with BigNumber to accurately represent large numbers:

- ci.Trader_exactSwapBForA(1, Number.MAX_SAFE_INTEGER, toAmountBI).then(
+ const maxUint256 = new BigNumber(2).pow(256).minus(1);
+ ci.Trader_exactSwapBForA(1, maxUint256, toAmountBI).then(

Ensure that the method accepts a BigNumber instance.


866-883: Use BigNumber instead of Number.MAX_SAFE_INTEGER

Similarly, replace Number.MAX_SAFE_INTEGER with BigNumber in ci.Trader_exactSwapAForB to handle large uint256 values:

- ci.Trader_exactSwapAForB(1, Number.MAX_SAFE_INTEGER, toAmountBI).then(
+ const maxUint256 = new BigNumber(2).pow(256).minus(1);
+ ci.Trader_exactSwapAForB(1, maxUint256, toAmountBI).then(

1268-1287: Simplify token ID comparisons

When comparing token IDs, converting numbers to strings is unnecessary. Compare them directly for clarity:

- t.contractId === token.tokenId || `${t.tokenId}` === `${token.tokenId}`
+ t.contractId === token.tokenId || t.tokenId === token.tokenId

Apply the same change for tokBInfo.


1351-1356: Clarify rate display logic

There may be inconsistencies in how lhs and rate are used for rate calculations:

{lhs === 1 ? 1 : lhs?.toFixed(6)} {tokenSymbol(token)} ={" "}
{lhs > 1 ? 1 : rate?.toFixed(6)} {tokenSymbol(token2)}

Review the conditions to ensure accurate exchange rate representation, and consider simplifying the logic.

src/components/Swap/index.tsx Show resolved Hide resolved
src/components/Swap/index.tsx Show resolved Hide resolved
@temptemp3 temptemp3 merged commit 6174f0e into beta Oct 11, 2024
1 check passed
@temptemp3 temptemp3 deleted the update-2 branch October 11, 2024 20:22
This was referenced Oct 11, 2024
prince-hope1975 pushed a commit to prince-hope1975/humble-interface that referenced this pull request Nov 1, 2024
* token: add icons and verified badge

* update pool and token page

* hide setting menu

* Update src/components/TokenCard/index.tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update src/components/TokenCard/index.tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update src/components/TokenCard/index.tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update src/components/TokenCard/index.tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix style

* fix toAmount recalc

* fix rate

* add todos

* fix style

* cleanup style

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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.

1 participant