fix/PRO-3190/hifi-endpoint-replacement#286
Conversation
|
Important Review skippedReview was skipped due to path filters ⛔ Files ignored due to path filters (2)
CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including You can disable this status message by setting the WalkthroughThis pull request refactors various components and tests across the PillarX and TokenAtlas codebases to improve robustness and maintainability. The changes focus on safer data access using optional chaining for blockchain-related properties, enhanced token navigation logic with utility functions, and streamlined API integration by replacing deprecated endpoints with new implementations. Additionally, test mock data has been updated with new price fields, and the TypeScript type definitions have been standardized to enforce consistent API response structures. Changes
Sequence Diagram(s)sequenceDiagram
participant U as User
participant IA as TokenAtlas Index
participant API as Search Query API
participant RS as Redux Store
U->>IA: Enter token search (asset, chain)
IA->>API: Execute useGetSearchTokensQuery
API-->>IA: Return search results (wrapped in result)
IA->>IA: Convert API response to token objects
IA->>RS: Dispatch selected token & update error state if needed
RS-->>IA: Updated token data state
Possibly related PRs
Suggested reviewers
Poem
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Deploying x with
|
| Latest commit: |
051284c
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://9a007b1b.x-e62.pages.dev |
| Branch Preview URL: | https://fix-pro-3190-hifi-endpoint-r.x-e62.pages.dev |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
src/apps/token-atlas/components/TokensSlider/TokensSlider.tsx (1)
57-68: Improved token filtering with blockchain compatibility check.The new implementation properly filters trending tokens to only include those with contracts on compatible chains, ensuring that users only see tokens they can actually interact with. The use of
chainNameFromViemToMobulastandardizes chain names between different systems.Consider adding a comment explaining the filtering logic in more detail, as it's a critical part of the user experience.
// look for trending tokens with compatible chains and reduce the list the 20 first trending tokens const trendingTokens = trendingTokensData?.result ?.filter((token) => + // Only show tokens that have at least one contract on a compatible chain token.contracts?.some((contract) => CompatibleChains.some( (chain) => chainNameFromViemToMobula(chain.chainName) === contract.blockchain ) ) ) .slice(0, 20) || [];src/apps/the-exchange/components/SwapReceiveCard/SwapReceiveCard.tsx (1)
70-81: Added specialized handling for native tokens.The updated logic now properly distinguishes between native tokens and contract tokens by checking if the token's symbol matches the asset parameter. This improved approach ensures that the correct token is selected when navigating from Token Atlas.
Consider adding error handling for the case when no results are found:
if (nativeToken.length > 0) { dispatch(setReceiveToken(nativeToken[0])); } else { + // Only dispatch if results exist + if (result.length > 0) { dispatch(setReceiveToken(result[0])); + } + // Consider logging or handling case when no tokens are found }src/apps/pillarx-app/components/TokensHorizontalTile/TokensHorizontalTile.tsx (1)
78-101: Handle potential undefined blockchain in query parameters.
IfcompatibleTokenContractis missing or undefined,${compatibleTokenContract?.blockchain}could becomeblockchain=undefinedin the route, which may lead to unintended behavior. Consider providing a fallback or skipping the param when undefined.- navigate( - `/token-atlas?${!isZeroAddress(compatibleTokenContract?.address || '') - ? \`&asset=\${compatibleTokenContract?.address}\` - : \`&asset=\${token.symbol}\`}&blockchain=\${compatibleTokenContract?.blockchain}` - ) + const blockchainParam = compatibleTokenContract?.blockchain + ? \`&blockchain=\${compatibleTokenContract.blockchain}\` + : ''; + navigate( + \`/token-atlas?\${!isZeroAddress(compatibleTokenContract?.address || '') + ? \`&asset=\${compatibleTokenContract?.address}\` + : \`&asset=\${token.symbol}\`}\${blockchainParam}\` + );
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
src/apps/pillarx-app/components/MediaGridCollection/tests/__snapshots__/DisplayCollectionImage.test.tsx.snapis excluded by!**/*.snapsrc/apps/pillarx-app/components/PointsTile/test/__snapshots__/PointsTile.test.tsx.snapis excluded by!**/*.snap
📒 Files selected for processing (16)
src/apps/pillarx-app/components/HorizontalToken/HorizontalToken.tsx(1 hunks)src/apps/pillarx-app/components/TokenInfoHorizontal/TokenInfoHorizontal.tsx(1 hunks)src/apps/pillarx-app/components/TokensHorizontalTile/TokensHorizontalTile.tsx(4 hunks)src/apps/pillarx-app/components/TokensHorizontalTile/test/TokensHorizontalTile.test.tsx(1 hunks)src/apps/pillarx-app/components/TokensVerticalList/TokensVerticalList.tsx(2 hunks)src/apps/pillarx-app/components/TokensVerticalList/test/TokensVerticalList.test.tsx(2 hunks)src/apps/pillarx-app/components/TokensVerticalTile/test/TokensVerticalTile.test.tsx(2 hunks)src/apps/the-exchange/components/SwapReceiveCard/SwapReceiveCard.tsx(1 hunks)src/apps/token-atlas/api/token.ts(3 hunks)src/apps/token-atlas/components/ChainCard/ChainCard.tsx(1 hunks)src/apps/token-atlas/components/TokenGraphColumn/TokenGraphColumn.tsx(6 hunks)src/apps/token-atlas/components/TokensSlider/TokensSlider.tsx(3 hunks)src/apps/token-atlas/components/TokensSlider/test/TokenSlider.test.tsx(2 hunks)src/apps/token-atlas/index.tsx(6 hunks)src/apps/token-atlas/reducer/tokenAtlasSlice.ts(4 hunks)src/types/api.ts(4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (6)
src/apps/pillarx-app/components/TokensVerticalList/TokensVerticalList.tsx (2)
src/utils/blockchain.ts (1)
CompatibleChains(260-289)src/services/tokensData.ts (1)
chainNameFromViemToMobula(66-84)
src/apps/token-atlas/components/TokenGraphColumn/TokenGraphColumn.tsx (3)
src/apps/token-atlas/hooks/useReducerHooks.tsx (1)
useAppSelector(6-6)src/services/tokensData.ts (1)
chainIdToChainNameTokensData(211-232)src/apps/simpleswap/components/NewCoinsDropdown/styles.ts (1)
Body(29-35)
src/apps/token-atlas/components/ChainCard/ChainCard.tsx (1)
src/apps/token-atlas/reducer/tokenAtlasSlice.ts (1)
setBlockchainList(107-112)
src/apps/pillarx-app/components/TokensHorizontalTile/TokensHorizontalTile.tsx (2)
src/utils/blockchain.ts (1)
CompatibleChains(260-289)src/services/tokensData.ts (1)
chainNameFromViemToMobula(66-84)
src/apps/token-atlas/components/TokensSlider/TokensSlider.tsx (3)
src/utils/blockchain.ts (1)
CompatibleChains(260-289)src/services/tokensData.ts (2)
chainNameFromViemToMobula(66-84)chainNameToChainIdTokensData(235-256)src/apps/token-atlas/types/types.tsx (1)
SelectedTokenType(14-22)
src/apps/token-atlas/api/token.ts (3)
src/types/api.ts (3)
TokenAtlasInfoApiResponse(214-218)BlockchainList(305-307)TrendingTokens(243-245)src/utils/blockchain.ts (1)
isTestnet(29-35)src/store.ts (1)
addMiddleware(48-58)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: build
- GitHub Check: Cloudflare Pages
🔇 Additional comments (51)
src/apps/pillarx-app/components/TokensHorizontalTile/test/TokensHorizontalTile.test.tsx (1)
24-24: Addition of price data to test mock is good.Adding the price property to the token mock data aligns with the PR objectives to replace endpoints related to token market data. This change ensures that the component can properly handle and display token pricing information.
src/apps/pillarx-app/components/TokensVerticalTile/test/TokensVerticalTile.test.tsx (1)
32-32: LGTM: Price properties added to mock tokens.The addition of price properties to both token objects in the mock data is consistent with the changes made in other test files. This ensures consistent test coverage for price-related functionality across components.
Also applies to: 44-44
src/apps/pillarx-app/components/TokensVerticalList/test/TokensVerticalList.test.tsx (1)
25-25: Price properties added to mock data as expected.Adding price properties to the token objects in this test file maintains consistency with the other test files, ensuring comprehensive test coverage for the token price display functionality across the application.
Also applies to: 37-37
src/apps/pillarx-app/components/HorizontalToken/HorizontalToken.tsx (1)
47-47: Improved robustness with optional chaining.The addition of optional chaining (
?.) when accessing the blockchain data properties is a good defensive programming practice. This change prevents potential runtime errors if the API response structure changes or if the data is temporarily unavailable.This change aligns with the PR objective of improving endpoint integration by making the code more resilient to variations in API response structures.
src/apps/pillarx-app/components/TokenInfoHorizontal/TokenInfoHorizontal.tsx (1)
41-43: Improved error handling with optional chainingThe addition of optional chaining (
?.result?.) when accessing the blockchain data makes the code more robust by safely handling potential undefined values in the nested structure of the API response. This change aligns with the endpoint replacement objectives mentioned in the PR.src/apps/token-atlas/components/ChainCard/ChainCard.tsx (2)
26-26: Improved error handling with optional chainingThe update to
blockchainListData?.result?.dataadds defensive programming with optional chaining operators, preventing potential runtime errors if the API response structure changes or is temporarily undefined.
34-36: Consistent data access pattern appliedThis change to use
blockchainListData?.result?.data.find()maintains consistency with the update on line 26, ensuring the same data access pattern is used throughout the component.src/apps/pillarx-app/components/TokensVerticalList/TokensVerticalList.tsx (4)
1-1: Added EtherSpot utility importThe import of
useEtherspotUtilsenables address validation capabilities that are utilized later in the component.
7-9: Added utility imports for blockchain data handlingThese imports bring in functionality needed for token contract validation and blockchain name mapping, supporting the enhanced token navigation logic.
21-21: Extracted address validation utilityThe extraction of
isZeroAddressfrom the Etherspot utilities hook provides a clean way to validate token contract addresses.
28-53: Enhanced token navigation logicThe improved implementation:
- Finds compatible token contracts by matching against supported blockchains
- Constructs navigation URLs with address validation
- Adds blockchain context to the navigation URL
This makes token navigation more reliable and contextual, supporting the endpoint replacement objectives of the PR.
src/apps/token-atlas/reducer/tokenAtlasSlice.ts (4)
35-35: Added token data error tracking stateThis new boolean property enhances error handling capabilities, allowing the application to track and respond to token data API errors.
58-58: Initialized token data error stateThe initial state is appropriately set to
false, assuming no errors by default.
125-127: Added reducer for token data error stateThis new reducer function allows components to update the error state when token data API requests fail, improving error handling throughout the application.
148-148: Exported token data error actionThe action is properly exported, making it available for use in components that need to update the error state.
src/apps/token-atlas/components/TokensSlider/test/TokenSlider.test.tsx (3)
27-27: Updated mock data structure to match new API schema.The property name has been changed from
datatoresultin themockTrendingTokensobject to align with the updated API response structure used throughout the application.
33-33: Updated blockchain names to realistic values.The mock blockchain names have been replaced with actual chain names ('Ethereum' and 'Polygon') instead of generic placeholders ('blockchain1' and 'blockchain2'), which improves test clarity and better represents real-world data.
Also applies to: 40-40
134-134: Updated expected chainId in token selection test.The expected chainId value is now correctly set to 1 (Ethereum) instead of undefined, which properly reflects the expected behavior when a token on the Ethereum chain is selected.
src/apps/token-atlas/components/TokensSlider/TokensSlider.tsx (2)
26-30: Added necessary utility imports for blockchain compatibility.The added imports provide essential functionality for blockchain name standardization and chain ID mapping, which enhances the component's ability to work with tokens across different blockchains.
110-123:Details
✅ Verification successful
Enhanced token selection logic with blockchain compatibility.
The implementation now correctly identifies a compatible token contract and determines the appropriate chainId using utility functions. This ensures that selected tokens are properly associated with the correct blockchain network.
Verify that
chainNameToChainIdTokensDatahandles all potential blockchain names properly:
🏁 Script executed:
#!/bin/bash # Check if any contract might have a blockchain name not handled by chainNameToChainIdTokensData rg -A 1 "chainNameToChainIdTokensData\(" src/ # Look at the implementation to verify all cases are covered cat src/services/tokensData.ts | grep -A 20 "chainNameToChainIdTokensData"Length of output: 5166
Re: Verified Enhanced Token Selection Logic in TokensSlider
The updated logic in TokensSlider now correctly identifies the compatible token contract and determines the proper chainId by utilizing the
chainNameToChainIdTokensDatautility. After reviewing its implementation insrc/services/tokensData.ts, we can confirm that the function covers all the standard blockchain names used throughout the codebase—namely, Ethereum, Polygon, Base, XDAI, BNB Smart Chain (BEP20), Optimistic, and Arbitrum—and appropriately defaults to 0 for any undefined or unrecognized values.
- Actionable Note: Ensure that if new blockchain names are introduced in future, the
chainNameToChainIdTokensDatautility is updated accordingly to avoid relying on the default fallback.src/apps/the-exchange/components/SwapReceiveCard/SwapReceiveCard.tsx (3)
51-51: Replaced contractAddress with chain parameter.Using the blockchain identifier directly improves clarity and aligns with the URL parameter structure from Token Atlas.
56-59: Simplified token search query parameters.The search input now properly focuses on the asset name/symbol, and the blockchain filter uses the chain parameter directly, which streamlines the API call logic.
82-82: Updated useEffect dependencies to match new implementation.The dependency array now correctly includes only
assetandsearchData, removing the unusedcontractAddressdependency. This prevents unnecessary effect re-runs.src/apps/token-atlas/components/TokenGraphColumn/TokenGraphColumn.tsx (4)
1-1: Added Etherspot utility for address validation.The
isZeroAddressutility fromuseEtherspotUtilsprovides a reliable way to determine if a token address is valid, which is crucial for creating correct navigation URLs.Also applies to: 51-51
66-68: Added error state selector for token data.Adding the
isTokenDataErroringselector from the Redux store provides a way to track and respond to token data retrieval errors, improving the user experience by enabling error state handling.
190-191: Enhanced navigation logic with address validation.The updated navigation URL construction now properly handles both contract tokens and native tokens by checking if the token address is a zero address. This ensures that the correct parameter (address or symbol) is used in the URL.
200-205: Added error feedback for failed token data retrieval.The new conditional rendering provides clear user feedback when token data cannot be retrieved, instructing users to try searching again. This improves the user experience by explicitly communicating when something goes wrong.
src/apps/pillarx-app/components/TokensHorizontalTile/TokensHorizontalTile.tsx (3)
1-1: Import usage is valid.
The newly importeduseEtherspotUtilsis correctly used later forisZeroAddress.
11-13: Imports successfully centralize complementary utilities.
FetchingchainNameFromViemToMobulaandCompatibleChainshere helps keep blockchain logic encapsulated in relevant utilities.
30-30: Destructured utility ensures safer address checks.
UsingisZeroAddressclarifies the token address validity check and reduces reliance on manual string comparisons.src/apps/token-atlas/index.tsx (11)
10-12: Newly introduced API imports.
Switching touseGetSearchTokensQueryanduseGetTokenMarketDataQueryaligns with the new API naming convention and usage. Ensure references to older hooks are fully removed.
20-20: Clearer state management for token data error.
AddingsetIsTokenDataErroringhelps distinguish token data error conditions, improving clarity in error handling flows.
30-34: Extended utility imports for chain conversions.
ImportingchainIdToChainNameTokensData,chainNameToChainIdTokensData, andconvertAPIResponseToTokensoffers explicit conversions, improving maintainability across multiple chain naming conventions.Also applies to: 39-39
136-137: Expose query error for robust error handling.
Renaming and storing the error astokenDataErrorclarifies its usage in subsequent error checks.
139-142: Conditional asset vs symbol usage for wrapped or native tokens.
The logic ensures the correct API call params based on whether the token is a wrapped or native asset. Double-check all edge cases, such as unexpected chain IDs or unusual wrapped tokens, to confirm robust coverage.
166-175: Conditional token search query.
Skipping the query if bothassetandchainare missing is a sensible approach. If relevant, verify that searching only by chain (no asset) or only by asset (no chain) behaves as intended.
179-180: Safeguard early return on missing search data.
Exiting early when!searchDataavoids errors in subsequent processing ofsearchData?.result.Also applies to: 181-185
186-205: Token selection logic for native or gas tokens.
This block gracefully handles scenarios where the user clicks on a purely symbolic chain asset, or on a standard contract-based token.
220-220: Dependence on query param changes.
Including[asset, searchData]in the effect ensures the token data updates once relevant queries return results for the provided search input.
232-234: Improved token data error visibility.
This set of conditions accurately sets or clears the token data state, ensuring that the UI consistently reflects data loading or error states.Also applies to: 238-239, 240-242, 244-244
257-257: Setting graph error states.
DispatchingsetIsGraphErroring(true)if the token market history pair fails is consistent with the parallel token error approach. The effect dependencies ensure automatic updates whenmarketHistoryPairor any of its statuses change.Also applies to: 260-260
src/types/api.ts (4)
172-172: Mandatorypriceimproves consistency.
Requiring theprice: number;field can help normalize consumption of token data. Confirm that all downstream code gracefully handles tokens which might have missing or zero prices in real scenarios.
214-218: Renamed property ensures consistent structure.
Replacingdatawithresult.dataclarifies the nested shape and enforces a standard pattern for the API responses, improving type safety.
243-245: Unified trending tokens structure.
ChangingTrendingTokensto aresultarray matches the new pattern, ensuring simpler usage across the codebase.
305-307: Consistent nesting for blockchain data.
Usingresult: { data: BlockchainData[] }centralizes the list in a standard property, preventing API shape confusion.src/apps/token-atlas/api/token.ts (6)
22-32: Migration to a retry-wrapped base query.
By introducingfetchBaseMobulawith{ maxRetries: 5 }, you’re improving resiliency in case of transient network errors.Also applies to: 36-36
72-102: NewtokenMarketDataAPI.
This endpoint’s POST request design appears consistent with the existing pattern for chaining query parameters. Validate the acceptance ofidor fallback usage if neitherassetnorsymbolis provided.
104-121: IntroducedblockchainsListAPI.
Fetching blockchains with'blockchains'path ensures an updated, standardized list. This is essential for consistent cross-chain references.
123-142:trendingTokensAPI standardizes trending endpoint.
Aligning trending token data with the newmetadata/trendingspath plus consistent query parameters fosters uniform usage across the app.
147-147: Registering new APIs in the store.
CallingaddMiddlewarefor new or refactored endpoints ensures Redux integration. Double-check that all old references have been removed to prevent collisions.Also applies to: 149-149
152-156: Appropriate hook exports for new endpoints.
ExportinguseGetTokenMarketDataQueryanduseGetBlockchainsListQuerykeeps the naming and usage pattern consistent with the RTK Query approach.
Description
How Has This Been Tested?
Screenshots (if appropriate):
Types of changes
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Refactor