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

Mattupham/fe 725 porfolio v3 variants detected popup #3871

Open
wants to merge 17 commits into
base: stage
Choose a base branch
from

Conversation

mattupham
Copy link
Contributor

@mattupham mattupham commented Oct 7, 2024

What is the purpose of the change:

  • we need to prompt a user to convert their alloyed asset variants if their portfolio includes alloyed assets

Linear Task

https://linear.app/osmosis/issue/FE-725/porfolio-v3-variants-detected-popup

Brief Changelog

  • Add variant detection logic
  • Add toast for Alloyed Assets variants
  • Add local storage logic to show / not show alloyed assets variants
  • Add query for alloyed assets variants
  • i18n, integrate feature flag
  • add static icons for assets + asset variants to sprite
  • only show on desktop

Testing and Verifying

add jest test cases for

  • has asset variants
  • does not have asset variants
  • has no assets

screenshot
Screenshot 2024-10-07 at 2 16 33 PM

example on any page

variants.detected.logic.mov

local storage persistence example

variants.detected.logic.local.storage.mov

Copy link

vercel bot commented Oct 7, 2024

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

Name Status Preview Comments Updated (UTC)
osmosis-frontend ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 7, 2024 11:23pm
4 Skipped Deployments
Name Status Preview Comments Updated (UTC)
osmosis-frontend-datadog ⬜️ Ignored (Inspect) Visit Preview Oct 7, 2024 11:23pm
osmosis-frontend-dev ⬜️ Ignored (Inspect) Visit Preview Oct 7, 2024 11:23pm
osmosis-frontend-edgenet ⬜️ Ignored (Inspect) Oct 7, 2024 11:23pm
osmosis-testnet ⬜️ Ignored (Inspect) Visit Preview Oct 7, 2024 11:23pm

...toastOptions,
toastId: ToastType.ALLOYED_ASSETS, // prevents duplicate toasts by using an explicit toast id
autoClose: false, // prevents Alloyed Assets toast from closing automatically - https://fkhadra.github.io/react-toastify/autoClose/
closeButton: false,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

some custom toast options to match figma designs + behavior

Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

Walkthrough

The pull request introduces enhancements to asset management functionality across multiple files. It adds new functions for checking asset variants, a custom React hook for managing user notifications regarding these assets, and updates the toast notification system to include a new toast type. The changes affect core logic, UI components, and testing files, reflecting a comprehensive update to asset variant handling and user interaction.

Changes

File Change Summary
packages/server/src/queries/complex/portfolio/allocation.ts - Added checkHasAssetVariants function and hasVariants property in GetAllocationResponse.
- Updated imports to include Asset type.
packages/trpc/src/portfolio.ts - Added getHasAssetVariants method in portfolioRouter, including input validation and async query.
- Updated imports to include the new method.
packages/web/components/alert/toast.tsx - Introduced new toast type ToastType.ALLOYED_ASSETS.
- Added AlloyedAssetsToast component with local storage management for visibility.
- Updated displayToast function to handle the new toast type.
packages/web/hooks/use-has-asset-variants.tsx - Introduced useHasAssetVariants hook for managing asset variant notifications.
packages/server/src/queries/complex/portfolio/__tests__/allocation.spec.ts - Expanded test suite with new tests for checkHasAssetVariants.

Possibly related PRs

Suggested reviewers

  • yury-dubinin
  • MaxMillington
  • JoseRFelix

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

🧹 Outside diff range and nitpick comments (13)
packages/web/components/alert/types.ts (1)

15-19: LGTM! Enum updates improve type safety and add new functionality.

The changes to the ToastType enum are well-implemented:

  1. Explicit string assignments for existing members enhance code clarity and reduce the risk of typos.
  2. The addition of ALLOYED_ASSETS aligns with the PR objective of detecting portfolio variants.

Consider using a more descriptive name for ALLOYED_ASSETS if appropriate, such as VARIANT_ASSETS_DETECTED or PORTFOLIO_VARIANTS_FOUND, to make its purpose clearer to other developers.

packages/web/components/alert/page-navigation-toast.tsx (1)

7-24: LGTM with suggestions: Toast configuration is comprehensive.

The toast configuration and content are well-structured and provide a good user experience. The use of custom styling classes allows for consistent theming. However, consider the following improvements:

  1. Move hardcoded values to constants for better maintainability:
const TOAST_AUTO_CLOSE_MS = 3000;
const TOAST_BG_CLASS = 'bg-osmoverse-700';

// In the toast configuration
autoClose: TOAST_AUTO_CLOSE_MS,
className: TOAST_BG_CLASS,
  1. Consider extracting the JSX content into a separate component for better readability and reusability:
const PageNavigationToastContent: React.FC<{ pageName: string }> = ({ pageName }) => (
  <div className="flex items-center gap-3">
    <Icon id="arrow-right" width={24} height={24} />
    <div>
      <h6 className="text-lg font-semibold">New Page</h6>
      <p className="text-sm text-osmoverse-200">You are now on: {pageName}</p>
    </div>
  </div>
);

// In the toast function
toast(<PageNavigationToastContent pageName={pageName} />, { ... });

These changes would enhance the maintainability and readability of the code.

packages/trpc/src/portfolio.ts (1)

41-53: LGTM: New method getHasAssetVariants added correctly.

The new getHasAssetVariants method has been implemented correctly, following the established patterns in the router. It properly uses publicProcedure, validates input with a zod schema, and utilizes the context to access assetLists.

Consider adding a brief comment above the method to explain its purpose and what "asset variants" refers to in this context. This would improve code readability and maintainability.

packages/server/src/queries/complex/portfolio/__tests__/allocation.spec.ts (2)

192-346: LGTM: Asset constants are well-defined, but consider reducing redundancy.

The new asset constants (ASSET_OSMO, ASSET_SAIL, and ASSET_ETH_AXL) are well-structured and provide comprehensive information. However, there's some redundancy in the data, particularly in the logoURIs and price objects.

Consider creating helper functions or using object composition to reduce redundancy and improve maintainability. For example:

const createLogoURIs = (png: string, svg?: string) => ({ png, ...(svg && { svg }) });
const createPrice = (poolId: string, denom: string) => ({ poolId, denom });

const ASSET_OSMO: Asset = {
  // ... other properties
  logoURIs: createLogoURIs(
    "https://raw.githubusercontent.com/cosmos/chain-registry/master/osmosis/images/osmo.png",
    "https://raw.githubusercontent.com/cosmos/chain-registry/master/osmosis/images/osmo.svg"
  ),
  price: createPrice("1464", "ibc/498A0751C798A0D9A389AA3691123DADA57DAA4FE165D5C75894505B876BA6E4"),
  // ... remaining properties
};

This approach would make the constants more concise and easier to maintain.


348-398: LGTM: Comprehensive test suite for asset variants, with room for improvement.

The new test suite for checking asset variants is well-structured and covers the main scenarios: presence of variants, absence of variants, and no assets. This provides good coverage for the checkHasAssetVariants function.

Consider the following improvements to enhance the test suite:

  1. Use a beforeEach block to set up common test data, reducing duplication:
describe("Has Asset Variants", () => {
  let baseAssets: Asset[];

  beforeEach(() => {
    baseAssets = [ASSET_OSMO, ASSET_SAIL];
  });

  // ... test cases
});
  1. Add edge cases, such as:

    • An asset with an empty variantGroupKey
    • Multiple assets with the same variantGroupKey
    • Assets with variantGroupKey that don't match any user assets
  2. Use test.each for parameterized testing of similar scenarios:

test.each([
  { desc: "with variants", userAssets: [...], expectedResult: true },
  { desc: "without variants", userAssets: [...], expectedResult: false },
  { desc: "no assets", userAssets: [], expectedResult: false },
])("should return $expectedResult $desc", ({ userAssets, expectedResult }) => {
  const result = checkHasAssetVariants(userAssets, baseAssets);
  expect(result).toBe(expectedResult);
});

These improvements would make the tests more robust, easier to maintain, and cover more scenarios.

packages/web/components/layouts/main.tsx (1)

Line range hint 1-95: Summary: New hook added, but usage unclear

The useHasAssetVariants hook has been added to the MainLayout component, suggesting new functionality related to asset variants. However, the hook's return value is not being used in the current implementation. Consider the following next steps:

  1. Implement the logic to use the hook's return value in the component.
  2. Add comments explaining the purpose of the hook if its effects are not visible in this file.
  3. If the implementation is incomplete, consider adding a TODO comment or creating a follow-up task.

To get a better understanding of the useHasAssetVariants hook and its intended usage, you may want to review its implementation:

#!/bin/bash
# Find and display the implementation of useHasAssetVariants
rg --type typescript -A 20 'export function useHasAssetVariants' packages/web/hooks
packages/server/src/queries/complex/portfolio/allocation.ts (2)

177-191: Consider adding unit tests for checkHasAssetVariants function.

Adding unit tests will help ensure that checkHasAssetVariants behaves correctly with various inputs, including edge cases where assets may or may not have variants.

Would you like assistance in creating unit tests for this function?


193-217: Consider adding unit tests for getHasAssetVariants function.

Unit tests will help verify that getHasAssetVariants correctly interacts with queryAllocation and handles different scenarios, including error cases.

Would you like assistance in creating unit tests or setting up mocks for queryAllocation?

packages/web/components/alert/toast.tsx (3)

244-259: Reminder: Implement the 'onConvert' Functionality

The onConvert function currently contains placeholder comments indicating that the modal linkage and conversion logic will be implemented in another PR. Ensure that this functionality is properly implemented to provide the intended user experience when the "Convert" button is clicked.

Let me know if you need assistance in implementing the modal interaction or if you'd like me to open a GitHub issue to track this task.


235-239: Code Simplification: Streamline State Update in 'onDismiss'

The state update in the onDismiss function can be simplified. Since setDoNotShowAgain is being set based on the isChecked state, you can directly pass isChecked to setDoNotShowAgain without the conditional statement.

Simplify the code as follows:

const onDismiss = () => {
- if (isChecked) {
-   setDoNotShowAgain(true);
- } else {
-   setDoNotShowAgain(false);
- }
+ setDoNotShowAgain(isChecked);
  closeToast();
};

227-230: Code Style Suggestion: Destructure Full Array from useLocalStorage

While currently only the setter function from useLocalStorage is used, consider destructuring both the value and setter for consistency and potential future use. This also improves code readability.

Adjust the destructuring as follows:

- const [, setDoNotShowAgain] = useLocalStorage(
+ const [doNotShowAgain, setDoNotShowAgain] = useLocalStorage(
    AlloyedAssetsToastDoNotShowKey,
    false
  );
packages/web/hooks/use-has-asset-variants.tsx (2)

31-31: Simplify the address parameter by removing the default empty string

Since enabled is true only when wallet?.address is defined, defaulting to an empty string is unnecessary. Passing wallet.address directly clarifies that an address is expected here.

Apply this change:

 {
-  address: wallet?.address ?? "",
+  address: wallet.address,
 },

12-54: Rename the hook to reflect its side-effect behavior

The hook useHasAssetVariants primarily triggers a toast notification and doesn't return any value. Renaming it to something like useDisplayAssetVariantToast would more accurately describe its purpose.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 774c013 and 8e0796a.

⛔ Files ignored due to path filters (18)
  • packages/web/localizations/de.json is excluded by !**/*.json
  • packages/web/localizations/en.json is excluded by !**/*.json
  • packages/web/localizations/es.json is excluded by !**/*.json
  • packages/web/localizations/fa.json is excluded by !**/*.json
  • packages/web/localizations/fr.json is excluded by !**/*.json
  • packages/web/localizations/gu.json is excluded by !**/*.json
  • packages/web/localizations/hi.json is excluded by !**/*.json
  • packages/web/localizations/ja.json is excluded by !**/*.json
  • packages/web/localizations/ko.json is excluded by !**/*.json
  • packages/web/localizations/pl.json is excluded by !**/*.json
  • packages/web/localizations/pt-br.json is excluded by !**/*.json
  • packages/web/localizations/ro.json is excluded by !**/*.json
  • packages/web/localizations/ru.json is excluded by !**/*.json
  • packages/web/localizations/tr.json is excluded by !**/*.json
  • packages/web/localizations/zh-cn.json is excluded by !**/*.json
  • packages/web/localizations/zh-hk.json is excluded by !**/*.json
  • packages/web/localizations/zh-tw.json is excluded by !**/*.json
  • packages/web/public/icons/sprite.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (9)
  • packages/server/src/queries/complex/portfolio/tests/allocation.spec.ts (2 hunks)
  • packages/server/src/queries/complex/portfolio/allocation.ts (2 hunks)
  • packages/trpc/src/portfolio.ts (2 hunks)
  • packages/web/components/alert/page-navigation-toast.tsx (1 hunks)
  • packages/web/components/alert/toast.tsx (3 hunks)
  • packages/web/components/alert/types.ts (1 hunks)
  • packages/web/components/layouts/main.tsx (2 hunks)
  • packages/web/hooks/index.ts (1 hunks)
  • packages/web/hooks/use-has-asset-variants.tsx (1 hunks)
🧰 Additional context used
🔇 Additional comments (11)
packages/web/components/alert/page-navigation-toast.tsx (2)

1-4: LGTM: Imports are appropriate and well-structured.

The imports are correctly set up for the functionality being implemented. The use of the ~ alias in the import path for Icon suggests a custom path configuration, which is a good practice for maintaining consistent imports across the project.


6-6: LGTM: Function declaration is clear and well-structured.

The showPageNavigationToast function is appropriately named, exported, and typed. It takes a pageName parameter of type string, which aligns well with its purpose of displaying a navigation toast.

packages/trpc/src/portfolio.ts (1)

2-2: LGTM: Import statement updated correctly.

The import statement has been properly updated to include getHasAssetVariants from the "@osmosis-labs/server" module. This change is consistent with the new method added to the router.

packages/server/src/queries/complex/portfolio/__tests__/allocation.spec.ts (2)

1-1: LGTM: New imports are appropriate for the added functionality.

The new imports for the Asset type and checkHasAssetVariants function are correctly added and necessary for the new tests and functionality introduced in this file.

Also applies to: 6-6


Line range hint 1-398: Overall, the changes are well-implemented with room for optimization.

The additions to this file, including new imports, asset constants, and a test suite for checking asset variants, are generally well-structured and provide good coverage for the new functionality. The test cases cover the main scenarios, which is commendable.

However, there are opportunities for improvement:

  1. Reducing redundancy in the asset constants
  2. Enhancing the test suite with more robust setup and additional edge cases
  3. Utilizing more advanced testing patterns for better maintainability

These optimizations would further improve the code quality and test coverage. Despite these suggestions, the current implementation is functional and provides a solid foundation for the new feature.

packages/web/components/layouts/main.tsx (3)

11-16: LGTM: New hook import added correctly

The useHasAssetVariants hook has been properly imported along with the existing hooks. This addition suggests new functionality related to asset variants in the component.


Line range hint 45-95: Verify completeness of useHasAssetVariants implementation

The useHasAssetVariants hook has been added, but there are no changes in the component's render logic to reflect its usage. Please confirm if the implementation is complete or if there are pending changes to utilize the hook's functionality in the UI.

To check for any usage of the hook's return value in the render logic, you can run:

#!/bin/bash
# Search for any usage of variables or functions that might come from useHasAssetVariants in the JSX
rg --type typescript -A 10 'useHasAssetVariants' packages/web/components/layouts/main.tsx | rg 'return'

42-43: Verify the usage of useHasAssetVariants hook

The useHasAssetVariants hook has been added, but its return value is not being used. Please confirm if this is intentional or if there's additional logic to be implemented using the hook's return value.

To check for any usage of the hook's return value, you can run:

packages/server/src/queries/complex/portfolio/allocation.ts (1)

177-191: ⚠️ Potential issue

Ensure variantGroupKey is defined to prevent potential runtime errors.

In the comparison matchingAsset.coinMinimalDenom !== matchingAsset.variantGroupKey, if variantGroupKey is undefined, the comparison may not behave as expected. Please verify that all assets have variantGroupKey defined or add a null check to handle undefined values.

Run the following script to check for assets without variantGroupKey:

packages/web/components/alert/toast.tsx (1)

72-84: Confirmation: Proper Implementation of 'ALLOYED_ASSETS' Toast Type

The addition of the ToastType.ALLOYED_ASSETS case in the displayToast function appears correct. The custom toast is configured to prevent duplicates and to stay open until manually closed, which aligns with the intended user experience.

packages/web/hooks/use-has-asset-variants.tsx (1)

36-39: Verify that the toast is displayed only once per session

Ensure that the toast notification doesn't appear multiple times unnecessarily. Since the toast is triggered on successful queries, additional checks might be needed to prevent repeated displays.

Consider verifying the toast behavior across different app states.

packages/web/hooks/index.ts Outdated Show resolved Hide resolved
packages/web/components/alert/toast.tsx Outdated Show resolved Hide resolved
packages/web/components/alert/toast.tsx Show resolved Hide resolved
packages/web/hooks/use-has-asset-variants.tsx Outdated Show resolved Hide resolved
};

const onConvert = () => {
// TODO: link to modal in other PR
Copy link
Contributor Author

Choose a reason for hiding this comment

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

will slot this in the other PR for asset conversion

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 (2)
packages/web/components/alert/toast.tsx (2)

72-84: LGTM: New toast type handled correctly

The implementation for ToastType.ALLOYED_ASSETS is well-structured and prevents duplicate toasts. The autoClose and closeButton settings are appropriate for the custom behavior of this toast type.

Consider extracting the toast options into a separate constant for better readability:

const ALLOYED_ASSETS_TOAST_OPTIONS = {
  toastId: ToastType.ALLOYED_ASSETS,
  autoClose: false,
  closeButton: false,
};

// Then in the switch case:
showToast(
  ({ closeToast }) => (
    <AlloyedAssetsToast {...alert} closeToast={closeToast} />
  ),
  {
    ...toastOptions,
    ...ALLOYED_ASSETS_TOAST_OPTIONS,
  }
);

This change would improve code organization and make it easier to maintain these options in the future.


224-259: LGTM: Well-structured AlloyedAssetsToast component

The AlloyedAssetsToast component is well-implemented, with proper state management using useLocalStorage and useState. The logic for handling the "do not show again" functionality is correct.

Regarding the TODO comment:

The onConvert function is currently a placeholder. Would you like assistance in creating a GitHub issue to track the implementation of the modal and the associated logic mentioned in the TODO comment?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8e0796a and 070cc05.

📒 Files selected for processing (4)
  • packages/server/src/queries/complex/portfolio/tests/allocation.spec.ts (2 hunks)
  • packages/web/components/alert/toast.tsx (3 hunks)
  • packages/web/hooks/index.ts (1 hunks)
  • packages/web/hooks/use-has-asset-variants.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/web/hooks/index.ts
  • packages/web/hooks/use-has-asset-variants.tsx
🧰 Additional context used
🔇 Additional comments (6)
packages/web/components/alert/toast.tsx (3)

2-2: LGTM: New imports added for enhanced functionality

The new imports (useState, useLocalStorage, Button, and Checkbox) are appropriate for the implementation of the AlloyedAssetsToast component and its associated functionality.

Also applies to: 9-9, 13-14


221-222: LGTM: Exported constant for local storage key

The addition of AlloyedAssetsToastDoNotShowKey as an exported constant is a good practice. It centralizes the management of the local storage key and allows for easy reuse across the application if needed.


Line range hint 1-331: Overall assessment: Well-implemented Alloyed Assets toast feature

The changes to packages/web/components/alert/toast.tsx effectively implement the new Alloyed Assets toast functionality. The code is well-structured, maintains consistency with existing patterns, and properly handles state management and user interactions. A few minor suggestions have been made for improvement, including:

  1. Extracting toast options into a separate constant for better readability.
  2. Addressing the TODO comment for the onConvert function.
  3. Correcting a potential typo in a class name.

These small adjustments will further enhance the quality and maintainability of the code. Great work overall!

packages/server/src/queries/complex/portfolio/__tests__/allocation.spec.ts (3)

1-1: LGTM: New imports and asset constants are well-defined and necessary.

The new imports for the Asset type and checkHasAssetVariants function are appropriate for the added functionality. The asset constants (ASSET_OSMO, ASSET_SAIL, ASSET_ETH_AXL) are well-structured and provide comprehensive information about each asset, which is crucial for the new tests.

Also applies to: 6-6, 192-346


348-397: LGTM: Comprehensive test suite for asset variant checking.

The new test suite "Has Asset Variants" is well-structured and covers the main scenarios for the checkHasAssetVariants function:

  1. When there are asset variants
  2. When there are no asset variants
  3. When the user has no assets

The tests make good use of the previously defined asset constants and have clear assertions that match the expected behavior.


Line range hint 1-398: Overall, the changes align well with the PR objectives.

The additions to this test file enhance the coverage for the allocation module, particularly in the area of asset variant detection. This aligns well with the PR objective of introducing variant detection logic. The new tests are well-structured, comprehensive, and consistent with the existing code style.

Some key points:

  1. New asset constants provide detailed information for testing.
  2. The checkHasAssetVariants function is thoroughly tested with various scenarios.
  3. The changes maintain the file's original structure while adding valuable new tests.

These enhancements will help ensure the reliability of the variant detection feature in the portfolio.

packages/web/components/alert/toast.tsx Outdated Show resolved Hide resolved
…et from Map, rename checkbox state for remind me later
@mattupham mattupham requested a review from a team October 7, 2024 21:34
!doNotShowAgain &&
Boolean(wallet?.isWalletConnected && wallet?.address);

api.local.portfolio.getHasAssetVariants.useQuery(
Copy link
Member

@jonator jonator Oct 7, 2024

Choose a reason for hiding this comment

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

From looking at implementation of useHasAssetVariants

What if we just run that function inside getAllocation and return the result as a flag in the response since we operate on that same data that we query elsewhere anyways? Then useHasAssetVariants here would call getAllocation looking for that hasAssetVariants: boolean flag instead when deciding to show the toast.

Pros:

  • Can remove a redundant tRPC procedure call (this one, getHasAssetVariants) in portfolioRouter
  • Prevent redundant API call to SQS for passthrough/portfolio-assets, reducing load on SQS services and avoiding an unnecessary query from the browser
  • If we check for convertible assets on every page anyways, we can reuse that allocation query data when they navigate to the portfolio page, increasing navigation performance

Cons:

  • May be hard to know that flag is there. In other words, the purpose of getAllocation has expanded a bit to involve alloyed assets logic

Overall, I think it's worth it, as we can delete a bunch of code. Which means less chance for error, and less to test.

Copy link
Contributor Author

@mattupham mattupham Oct 7, 2024

Choose a reason for hiding this comment

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

It's not necessarily redundant, I reused the underlyingqueryAllocation, but separated the procedures out since the processing / logic is different. It doesn't add that much code and we do the processing differently on the portfolio page per item

This setup shows a clear distinction with what data is being processed

Copy link
Member

@jonator jonator Oct 7, 2024

Choose a reason for hiding this comment

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

I'm seeing redundant calls to portfolio-assets from different initiator call stacks.

I think it could easily be avoided, and would save on bandwidth to SQS and improve browser performance:

Screenshot 2024-10-07 at 6 03 02 PM

Copy link
Member

Choose a reason for hiding this comment

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

@mattupham

Check this out
#3872

@mattupham mattupham requested a review from jonator October 7, 2024 21:51
jonator
jonator previously requested changes Oct 7, 2024
Copy link
Member

@jonator jonator left a comment

Choose a reason for hiding this comment

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

Noticed another issue

const enabled =
alloyedAssets &&
!doNotShowAgain &&
Boolean(wallet?.isWalletConnected && wallet?.address);
Copy link
Member

@jonator jonator Oct 7, 2024

Choose a reason for hiding this comment

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

It seems to enable we should also check for wallet.address !== "" as it seems the query is going through with an empty string "" before the wallet is loaded:
Screenshot 2024-10-07 at 5 58 20 PM

Copy link
Contributor Author

@mattupham mattupham Oct 7, 2024

Choose a reason for hiding this comment

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

I updated this with const { isLoading: isWalletLoading } = useWalletSelect(); and the check for the empty wallet address

!doNotShowAgain &&
Boolean(wallet?.isWalletConnected && wallet?.address);

api.local.portfolio.getHasAssetVariants.useQuery(
Copy link
Member

@jonator jonator Oct 7, 2024

Choose a reason for hiding this comment

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

I'm seeing redundant calls to portfolio-assets from different initiator call stacks.

I think it could easily be avoided, and would save on bandwidth to SQS and improve browser performance:

Screenshot 2024-10-07 at 6 03 02 PM

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 (1)
packages/web/components/alert/toast.tsx (1)

244-259: TODO: Implement onConvert functionality

The onConvert function currently contains only comments outlining the expected behavior. Ensure that this functionality is implemented in the upcoming PR mentioned in the TODO comment.

Would you like assistance in creating a GitHub issue to track the implementation of the onConvert function?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 070cc05 and bb4b8a1.

📒 Files selected for processing (3)
  • packages/server/src/queries/complex/portfolio/allocation.ts (2 hunks)
  • packages/web/components/alert/toast.tsx (3 hunks)
  • packages/web/hooks/use-has-asset-variants.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/web/hooks/use-has-asset-variants.tsx
🧰 Additional context used
🔇 Additional comments (9)
packages/server/src/queries/complex/portfolio/allocation.ts (3)

3-3: LGTM: Import statement added correctly.

The new import for Asset and AssetList from "@osmosis-labs/types" is necessary for the newly added functions and is placed appropriately with other imports.


177-193: LGTM: Efficient implementation of checkHasAssetVariants.

The function is well-implemented:

  1. It uses a Map for O(1) lookups, improving performance as suggested in a past review.
  2. The logic correctly checks if any user coin has variants.
  3. The implementation is concise and easy to understand.

Great job on incorporating the previous feedback!


176-219: Overall implementation aligns well with PR objectives.

The new functions checkHasAssetVariants and getHasAssetVariants are well-integrated into the existing codebase and effectively implement the variant detection logic as outlined in the PR objectives. The code is consistent with the existing style and enhances the functionality without disrupting existing features.

Great job on implementing this feature! Just ensure to address the error handling suggestion for queryAllocation to further improve the robustness of the implementation.

packages/web/components/alert/toast.tsx (6)

2-2: LGTM: Import statements updated correctly

The new import statements for useState, useLocalStorage, Button, and Checkbox are correctly added and necessary for the implementation of the new AlloyedAssetsToast component.

Also applies to: 9-9, 13-14


72-84: LGTM: New ALLOYED_ASSETS toast type handled correctly

The displayToast function has been updated to handle the new ToastType.ALLOYED_ASSETS case appropriately. The implementation uses a custom render function to pass down the closeToast functionality and sets specific options to prevent duplicate toasts and auto-closing. This approach is consistent with the handling of other toast types and suitable for the Alloyed Assets notification.


221-222: LGTM: Clear and well-named constant for local storage key

The AlloyedAssetsToastDoNotShowKey constant is appropriately named and exported. It provides a clear, reusable key for managing the visibility state of the Alloyed Assets toast in local storage.


305-315: LGTM: Checkbox accessibility improved

The checkbox and its label are now properly associated within a label element, which improves accessibility for screen readers and keyboard navigation. This is a good practice and addresses the previous accessibility concern.


321-321: ⚠️ Potential issue

Fix typo in className

There appears to be a typo in the className property. The class !text-wosmongton-200 is likely incorrect. Please verify and update it to the correct value, possibly !text-osmoverse-200 to match the naming convention used elsewhere.

Apply this diff to correct the class name:

- className="!border !border-osmoverse-alpha-700 !text-wosmongton-200"
+ className="!border !border-osmoverse-alpha-700 !text-osmoverse-200"

Likely invalid or redundant comment.


234-242: Verify the logic for setting doNotShowAgain

The current implementation of onDismiss sets doNotShowAgain to false when the user checks "remind me later", and to true when they don't. This seems counterintuitive. Please verify if this is the intended behavior or if it should be reversed.

@mattupham mattupham requested a review from jonator October 7, 2024 22:15
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 (1)
packages/trpc/src/portfolio.ts (1)

41-57: LGTM: New method getHasAssetVariants implemented correctly.

The new method is well-structured and consistent with other router methods. It includes proper input validation using zod and handles the empty address case efficiently. The use of context to pass assetLists is correct.

Consider adding an explicit return type to the query for improved type safety:

.query(async ({ input: { address }, ctx }): Promise<{ hasAssetVariants: boolean }> => {
  // ... existing implementation ...
})

This change would make the return type more explicit and consistent with TypeScript best practices.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bb4b8a1 and 2983ccc.

📒 Files selected for processing (2)
  • packages/trpc/src/portfolio.ts (2 hunks)
  • packages/web/hooks/use-has-asset-variants.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/web/hooks/use-has-asset-variants.tsx
🧰 Additional context used
🔇 Additional comments (2)
packages/trpc/src/portfolio.ts (2)

2-2: LGTM: Import statement updated correctly.

The import statement has been properly updated to include the getHasAssetVariants function from "@osmosis-labs/server". This change aligns with the new method added to the router.


Line range hint 1-57: Summary: Changes align well with PR objectives.

The modifications to this file successfully implement the variant detection logic as outlined in the PR objectives. The new getHasAssetVariants method is well-integrated into the existing portfolioRouter, following consistent patterns and best practices.

Key points:

  1. The import statement is correctly updated to include the new function.
  2. The new method is properly implemented with input validation and error handling.
  3. The changes maintain the existing code structure and style.

These changes contribute to the overall goal of prompting users to convert their alloyed asset variants if their portfolio includes such assets.

jonator and others added 2 commits October 7, 2024 16:04
* prevent redundant query

* prevent query before mount
const userBalanceDenoms =
categories["user-balances"]?.account_coins_result?.map(
(result) => result.coin.denom
) ?? [];

// check for alloyed asset variants
Copy link
Member

Choose a reason for hiding this comment

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

Giga Nit: variants include canonical assets such as USDC, not just alloys

Copy link
Contributor Author

Choose a reason for hiding this comment

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

ha updated that comment for clarity

Copy link
Member

@jonator jonator left a comment

Choose a reason for hiding this comment

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

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 (3)
packages/server/src/queries/complex/portfolio/allocation.ts (3)

24-25: LGTM: New property added to interface.

The addition of the hasVariants property to the GetAllocationResponse interface is appropriate and aligns with the PR objectives.

Consider updating the comment to be more specific:

/** Indicates whether there are asset variants (including alloys and canonical assets) that can be converted to canonical form. */

This change would make the comment more informative and align it with the implementation details.


191-207: LGTM: Efficient implementation of asset variant checking.

The checkHasAssetVariants function is well-implemented, using a Map for efficient asset lookups. This aligns with a previous review suggestion and provides good performance.

For improved readability, consider extracting the variant check logic into a separate function:

const isVariant = (asset: Asset | undefined) =>
  asset && asset.coinMinimalDenom !== asset.variantGroupKey;

return userCoinMinimalDenoms.some((coinMinimalDenom) => 
  isVariant(assetMap.get(coinMinimalDenom))
);

This change would make the main function body more concise and the logic more explicit.


Line range hint 145-189: Add error handling for queryAllocation.

While the changes effectively implement asset variant detection, the previously suggested error handling for queryAllocation is still missing. This could lead to unhandled promise rejections if the query fails.

Consider implementing error handling as suggested in a previous review:

export async function getAllocation({
  address,
  assetLists,
  allocationLimit = 5,
}: {
  address: string;
  assetLists: AssetList[];
  allocationLimit?: number;
}): Promise<GetAllocationResponse> {
  let data;
  try {
    data = await queryAllocation({
      address,
    });
  } catch (error) {
    console.error('Error querying allocation:', error);
    // Return a default or error response
    return {
      all: [],
      assets: [],
      available: [],
      totalCap: new PricePretty(DEFAULT_VS_CURRENCY, new Dec(0)),
      hasVariants: false,
    };
  }

  // Rest of the function remains the same
}

This change will improve the robustness of the function by gracefully handling potential errors from queryAllocation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2983ccc and 58aa1e9.

📒 Files selected for processing (2)
  • packages/server/src/queries/complex/portfolio/allocation.ts (3 hunks)
  • packages/web/hooks/use-has-asset-variants.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/web/hooks/use-has-asset-variants.tsx
🧰 Additional context used
🔇 Additional comments (1)
packages/server/src/queries/complex/portfolio/allocation.ts (1)

3-3: LGTM: Import statement updated correctly.

The addition of the Asset type to the import statement is appropriate and necessary for the new functionality introduced in this file.

Comment on lines +171 to +180
const userBalanceDenoms =
categories["user-balances"]?.account_coins_result?.map(
(result) => result.coin.denom
) ?? [];

// check for asset variants, alloys and canonical assets such as USDC
const hasVariants = checkHasAssetVariants(
userBalanceDenoms,
assetLists.flatMap((list) => list.assets)
);
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

LGTM: Asset variant detection logic added correctly.

The changes in the getAllocation function effectively implement the asset variant detection logic. The extraction of user balance denoms and the call to checkHasAssetVariants are implemented correctly.

Consider memoizing the result of assetLists.flatMap((list) => list.assets) if assetLists is not expected to change frequently. This could improve performance, especially for large asset lists:

const memoizedAssetListAssets = useMemo(() => assetLists.flatMap((list) => list.assets), [assetLists]);

// Then use memoizedAssetListAssets in the checkHasAssetVariants call

This optimization would be particularly beneficial if getAllocation is called multiple times with the same assetLists.

Also applies to: 187-187

Copy link
Member

@jonator jonator left a comment

Choose a reason for hiding this comment

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

I see now, to be done in future PR

// TODO: link to modal in other PR

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