8000 feat: refactor and add more networks to the token details page swap w… by cowdan · Pull Request #5900 · cowprotocol/cowswap · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: refactor and add more n 8000 etworks to the token details page swap w… #5900

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

Merged
merged 6 commits into from
Jun 30, 2025

Conversation

cowdan
Copy link
Contributor
@cowdan cowdan commented Jun 27, 2025

…idget

Summary

Fixes #5892

  • refactor component, consolidate logic
  • add missing networks

To Test

  • navigate to [/tokens](https://cowfi-mqb5k0j8h-cowswap.vercel.app/tokens)
  • select a token from the list, for example Aave
  • select "Buy" or "Sell" from the widget tab
  • select the network
  • click "Swap Aave"
  • a new tab should open, pointing to CowSwap pre-populated with the token pair selected (one is the token from the token detail page, the other is the wrapped native currency of the selected chain)

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Expanded network support in the swap widget, allowing users to select from multiple networks with dynamic options and icons.
    • Default buy and sell tokens are now set per network for a smoother user experience.
  • Improvements

    • Enhanced UI consistency with optimized image handling.
    • Improved input validation for swap amounts.
    • More intuitive and modular tab navigation within the swap widget.

@cowdan cowdan marked this pull request as draft June 27, 2025 13:59
Copy link
vercel bot commented Jun 27, 2025

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

Name Status Preview Updated (UTC)
cowfi ✅ Ready (Inspect) Visit Preview Jun 30, 2025 1:28pm
explorer-dev ✅ Ready (Inspect) Visit Preview Jun 30, 2025 1:28pm
swap-dev ✅ Ready (Inspect) Visit Preview Jun 30, 2025 1:28pm
3 Skipped Deployments
Name Status Preview Updated (UTC)
cosmos ⬜️ Ignored (Inspect) Visit Preview Jun 30, 2025 1:28pm
sdk-tools ⬜️ Ignored (Inspect) Visit Preview Jun 30, 2025 1:28pm
widget-configurator ⬜️ Ignored (Inspect) Visit Preview Jun 30, 2025 1:28pm

Copy link
Contributor
coderabbitai bot commented Jun 27, 2025

"""

Walkthrough

The SwapWidget component was refactored for improved type safety, modularity, and UI consistency. Network and token mappings were centralized, reusable logic was extracted, and support for multiple networks was expanded. The network constants file now includes chain IDs and default tokens for each network, enhancing configuration and maintainability.

Changes

File(s) Change Summary
apps/cow-fi/components/SwapWidget.tsx Refactored SwapWidget: improved type safety, modularized logic, unified image handling, supported more networks, and extracted reusable functions and subcomponents.
apps/cow-fi/const/networkMap.ts Added mappings for network chain IDs and default buy/sell tokens keyed by network type.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SwapWidget
    participant NetworkMap

    User->>SwapWidget: Selects network or tab, enters amount
    SwapWidget->>NetworkMap: Fetches network ID and default tokens
    SwapWidget->>SwapWidget: Determines buy/sell tokens via getBuyAndSellTokens
    SwapWidget->>SwapWidget: Generates swap URL via getSwapUrl
    SwapWidget->>User: Renders updated UI with correct token and network info
Loading

Assessment against linked issues

Objective Addressed Explanation
Add other networks to the dropdown in the trade widget (#5892)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected.

Possibly related PRs

Suggested reviewers

  • shoom3301
  • elena-zh

Poem

🐇
In the meadow of code, networks now bloom,
With tokens and tabs in a modular room.
Images optimized, logic set free,
Swapping made simple as hopping can be!
From Base to xDai, the bridges unite—
This rabbit approves: the future is bright!
🥕
"""

Warning

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

🔧 ESLint

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

yarn install v1.22.22
[1/4] Resolving packages...
(node:25908) [DEP0169] DeprecationWarning: url.parse() behavior is not standardized and prone to errors that have security implications. Use the WHATWG URL API instead. CVEs are not issued for url.parse() vulnerabilities.
(Use node --trace-deprecation ... to show where the warning was created)
[2/4] Fetching packages...
error nx@21.0.3: The engine "node" is incompatible with this module. Expected version "^20.19.0 || ^22.12.0". Got "24.3.0"
error Found incompatible module.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1ff2d8a and 116924d.

📒 Files selected for processing (1)
  • apps/cow-fi/components/SwapWidget.tsx (3 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: shoom3301
PR: cowprotocol/cowswap#5443
File: apps/cowswap-frontend/src/modules/swap/containers/ConfirmSwapModalSetup/index.tsx:71-71
Timestamp: 2025-02-20T15:59:33.749Z
Learning: The swap module in apps/cowswap-frontend/src/modules/swap/ is marked for deletion in PR #5444 as part of the swap widget unification effort.
Learnt from: cowdan
PR: cowprotocol/cowswap#5715
File: libs/common-const/src/tokens.ts:539-555
Timestamp: 2025-05-26T12:39:29.009Z
Learning: The team accepts using NATIVE_CURRENCY_ADDRESS as a temporary placeholder for COW token contract addresses on new networks (Polygon, Avalanche) until actual COW contracts are deployed.
apps/cow-fi/components/SwapWidget.tsx (9)
Learnt from: shoom3301
PR: cowprotocol/cowswap#5443
File: apps/cowswap-frontend/src/modules/swap/containers/ConfirmSwapModalSetup/index.tsx:71-71
Timestamp: 2025-02-20T15:59:33.749Z
Learning: The swap module in apps/cowswap-frontend/src/modules/swap/ is marked for deletion in PR #5444 as part of the swap widget unification effort.
Learnt from: fairlighteth
PR: cowprotocol/cowswap#5768
File: apps/cow-fi/components/LearnPageComponent.tsx:184-185
Timestamp: 2025-05-28T16:50:12.273Z
Learning: In apps/cow-fi/components/LearnPageComponent.tsx, the user prefers to keep the inconsistent link behavior where featured articles always open in new tabs (target="_blank") while media coverage links conditionally open in new tabs based on the linkExternal flag. This inconsistency should not be flagged as an issue in future reviews.
Learnt from: cowdan
PR: cowprotocol/cowswap#5715
File: libs/common-const/src/tokens.ts:539-555
Timestamp: 2025-05-26T12:39:29.009Z
Learning: The team accepts using NATIVE_CURRENCY_ADDRESS as a temporary placeholder for COW token contract addresses on new networks (Polygon, Avalanche) until actual COW contracts are deployed.
Learnt from: fairlighteth
PR: cowprotocol/cowswap#5782
File: apps/cow-fi/app/(learn)/learn/topics/page.tsx:1-1
Timestamp: 2025-06-05T08:31:01.284Z
Learning: Next.js App Router official documentation states that Client Components marked with 'use client' should NOT be declared as async functions, as this can lead to infinite loops or application hangs. The recommended pattern for async operations in Client Components is to use useEffect hooks. Server Components (without 'use client') can be async, which might be a source of confusion.
Learnt from: alfetopito
PR: cowprotocol/cowswap#5830
File: apps/cowswap-frontend/src/modules/trade/containers/TradeWidget/index.tsx:1-2
Timestamp: 2025-06-16T15:58:00.268Z
Learning: JSX can be imported as a named export from React in modern React versions (React 17+). The import `import { JSX } from 'react'` is valid and does not cause compilation errors.
Learnt from: alfetopito
PR: cowprotocol/cowswap#5831
File: apps/cowswap-frontend/src/modules/application/containers/AppMenu/index.tsx:7-9
Timestamp: 2025-06-16T16:01:46.729Z
Learning: React Router v7 restructured packages - NavLink and other core routing components should be imported from 'react-router' (not 'react-router-dom'). In v7, 'react-router-dom' mainly re-exports for backward compatibility, while 'react-router' is the new preferred import path for most components.
Learnt from: alfetopito
PR: cowprotocol/cowswap#5831
File: apps/cowswap-frontend/src/modules/application/containers/AppMenu/index.tsx:7-9
Timestamp: 2025-06-16T16:01:46.729Z
Learning: In React Router v6+, NavLink can be imported directly from 'react-router' package, not just 'react-router-dom'. The package structure has evolved and the import from 'react-router' is valid for the latest versions.
Learnt from: fairlighteth
PR: cowprotocol/cowswap#5780
File: CONTRIBUTING.md:121-121
Timestamp: 2025-06-02T12:52:34.606Z
Learning: React 19.0.0 was released on December 5, 2024, introducing new features like Actions, Server Components, and hooks such as useActionState and useOptimistic.
Learnt from: fairlighteth
PR: cowprotocol/cowswap#5782
File: apps/cow-fi/app/(learn)/learn/topics/page.tsx:1-1
Timestamp: 2025-06-05T08:31:01.284Z
Learning: Next.js App Router supports async client components with the 'use client' directive. Unlike traditional React, where client components must be synchronous, Next.js App Router allows client components to be async functions. The async operations execute on the client side after hydration, enabling components that use client-side hooks to also perform data fetching. This pattern is commonly used when components need both interactive client-side features and async data operations.
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Cypress
  • GitHub Check: Setup
🔇 Additional comments (11)
apps/cow-fi/components/SwapWidget.tsx (11)

1-1: Excellent import improvements for modern React and Next.js.

The addition of JSX import and Next.js Image component import aligns with current best practices and the refactoring goals.

Also applies to: 5-5


13-20: Great centralization of network constants.

Moving network mappings to a centralized constants file improves maintainability and type safety. The comprehensive import of all network-related maps provides a solid foundation for the widget functionality.


205-208: Improved type safety with explicit type unions and constants.

The explicit Tab type definition and default constants provide better type safety and clearer intent compared to string literals.


209-225: Well-implemented token mapping logic.

The getBuyAndSellTokens function properly extracts the buy/sell token determination logic and leverages the centralized token maps. The logic correctly handles both Buy and Sell scenarios.


227-238: Clean component extraction for tabs.

The Tabs component extraction improves modularity and readability. The component is properly typed and handles the active state correctly.


240-256: Reusable dropdown option component.

The DropdownNetworkOption component is well-structured with proper typing and uses the Next.js Image component for optimized rendering.


258-271: Comprehensive network support in dropdown.

The getDropdownBody function now supports all available networks (Ethereum, Base, Arbitrum, Polygon, Avalanche, xDai) with proper conditional rendering based on contract address availability.


273-284: Logical network prioritization.

The getNetworkFromPlatforms function implements a sensible priority order for network selection, defaulting to Ethereum when no platforms are available.


287-288: Proper state typing implementation.

The network state is now correctly typed as Network instead of string, eliminating the need for type casting elsewhere in the component. This addresses the previous feedback perfectly.


300-300: Consistent use of extracted utility functions.

The component now properly utilizes the extracted utility functions (getNetworkFromPlatforms, getBuyAndSellTokens) and centralized mappings, maintaining type safety throughout.

Also applies to: 318-318, 321-321, 329-331


338-339: Optimized image rendering with Next.js.

The migration from <img> tags to Next.js <Image> components provides automatic optimization, lazy loading, and better performance.

Also applies to: 349-349

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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: 1

🧹 Nitpick comments (1)
apps/cow-fi/components/SwapWidget.tsx (1)

239-294: Consider extracting image dimensions to reduce duplication.

The function works correctly, but the hardcoded width and height values are repeated multiple times.

Consider extracting the dimensions:

 const getDropdownBody = (platforms: Platforms, handleSelect: (network: string) => void): JSX.Element => {
   const { ethereum, xdai, base, 'arbitrum-one': arbitrum, avalanche, 'polygon-pos': polygon } = platforms
-  const width = 20
-  const height = 20
+  const IMAGE_SIZE = { width: 20, height: 20 }
 
   return (
     <DropdownBody>
       {ethereum?.contractAddress && (
         <DropdownOption  => handleSelect('ethereum')}>
-          <Image src={NETWORK_IMAGE_MAP.ethereum} alt={NETWORK_MAP.ethereum} width={width} height={height} />
+          <Image src={NETWORK_IMAGE_MAP.ethereum} alt={NETWORK_MAP.ethereum} {...IMAGE_SIZE} />
           {NETWORK_MAP.ethereum}
         </DropdownOption>
       )}
       {/* Apply to other Image components */}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 195ef8f and 8ba9154.

📒 Files selected for processing (2)
  • apps/cow-fi/components/SwapWidget.tsx (3 hunks)
  • apps/cow-fi/const/networkMap.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: shoom3301
PR: cowprotocol/cowswap#5443
File: apps/cowswap-frontend/src/modules/swap/containers/ConfirmSwapModalSetup/index.tsx:71-71
Timestamp: 2025-02-20T15:59:33.749Z
Learning: The swap module in apps/cowswap-frontend/src/modules/swap/ is marked for deletion in PR #5444 as part of the swap widget unification effort.
Learnt from: cowdan
PR: cowprotocol/cowswap#5715
File: libs/common-const/src/tokens.ts:539-555
Timestamp: 2025-05-26T12:39:29.009Z
Learning: The team accepts using NATIVE_CURRENCY_ADDRESS as a temporary placeholder for COW token contract addresses on new networks (Polygon, Avalanche) until actual COW contracts are deployed.
apps/cow-fi/const/networkMap.ts (1)
Learnt from: cowdan
PR: cowprotocol/cowswap#5715
File: libs/common-const/src/tokens.ts:539-555
Timestamp: 2025-05-26T12:39:29.009Z
Learning: The team accepts using NATIVE_CURRENCY_ADDRESS as a temporary placeholder for COW token contract addresses on new networks (Polygon, Avalanche) until actual COW contracts are deployed.
apps/cow-fi/components/SwapWidget.tsx (9)
Learnt from: shoom3301
PR: cowprotocol/cowswap#5443
File: apps/cowswap-frontend/src/modules/swap/containers/ConfirmSwapModalSetup/index.tsx:71-71
Timestamp: 2025-02-20T15:59:33.749Z
Learning: The swap module in apps/cowswap-frontend/src/modules/swap/ is marked for deletion in PR #5444 as part of the swap widget unification effort.
Learnt from: fairlighteth
PR: cowprotocol/cowswap#5768
File: apps/cow-fi/components/LearnPageComponent.tsx:184-185
Timestamp: 2025-05-28T16:50:12.273Z
Learning: In apps/cow-fi/components/LearnPageComponent.tsx, the user prefers to keep the inconsistent link behavior where featured articles always open in new tabs (target="_blank") while media coverage links conditionally open in new tabs based on the linkExternal flag. This inconsistency should not be flagged as an issue in future reviews.
Learnt from: alfetopito
PR: cowprotocol/cowswap#5830
File: apps/cowswap-frontend/src/modules/trade/containers/TradeWidget/index.tsx:1-2
Timestamp: 2025-06-16T15:58:00.268Z
Learning: JSX can be imported as a named export from React in modern React versions (React 17+). The import `import { JSX } from 'react'` is valid and does not cause compilation errors.
Learnt from: alfetopito
PR: cowprotocol/cowswap#5831
File: apps/cowswap-frontend/src/modules/application/containers/AppMenu/index.tsx:7-9
Timestamp: 2025-06-16T16:01:46.729Z
Learning: React Router v7 restructured packages - NavLink and other core routing components should be imported from 'react-router' (not 'react-router-dom'). In v7, 'react-router-dom' mainly re-exports for backward compatibility, while 'react-router' is the new preferred import path for most components.
Learnt from: alfetopito
PR: cowprotocol/cowswap#5831
File: apps/cowswap-frontend/src/modules/application/containers/AppMenu/index.tsx:7-9
Timestamp: 2025-06-16T16:01:46.729Z
Learning: In React Router v6+, NavLink can be imported directly from 'react-router' package, not just 'react-router-dom'. The package structure has evolved and the import from 'react-router' is valid for the latest versions.
Learnt from: fairlighteth
PR: cowprotocol/cowswap#5782
File: apps/cow-fi/app/(learn)/learn/topics/page.tsx:1-1
Timestamp: 2025-06-05T08:31:01.284Z
Learning: Next.js App Router official documentation states that Client Components marked with 'use client' should NOT be declared as async functions, as this can lead to infinite loops or application hangs. The recommended pattern for async operations in Client Components is to use useEffect hooks. Server Components (without 'use client') can be async, which might be a source of confusion.
Learnt from: fairlighteth
PR: cowprotocol/cowswap#5780
File: CONTRIBUTING.md:121-121
Timestamp: 2025-06-02T12:52:34.606Z
Learning: React 19.0.0 was released on December 5, 2024, introducing new features like Actions, Server Components, and hooks such as useActionState and useOptimistic.
Learnt from: fairlighteth
PR: cowprotocol/cowswap#5782
File: apps/cow-fi/app/(learn)/learn/topics/page.tsx:1-1
Timestamp: 2025-06-05T08:31:01.284Z
Learning: Next.js App Router supports async client components with the 'use client' directive. Unlike traditional React, where client components must be synchronous, Next.js App Router allows client components to be async functions. The async operations execute on the client side after hydration, enabling components that use client-side hooks to also perform data fetching. This pattern is commonly used when components need both interactive client-side features and async data operations.
Learnt from: cowdan
PR: cowprotocol/cowswap#5715
File: libs/common-const/src/tokens.ts:539-555
Timestamp: 2025-05-26T12:39:29.009Z
Learning: The team accepts using NATIVE_CURRENCY_ADDRESS as a temporary placeholder for COW token contract addresses on new networks (Polygon, Avalanche) until actual COW contracts are deployed.
🔇 Additional comments (9)
apps/cow-fi/const/networkMap.ts (2)

10-17: LGTM: Chain IDs are correct.

The network chain ID mappings are accurate and properly typed.


37-53: LGTM: Default token mappings are appropriate.

The default sell and buy token mappings use wrapped native currencies for each network, which is the standard approach. The use of WPOL for Polygon correctly reflects the recent MATIC to POL rebrand.

apps/cow-fi/components/SwapWidget.tsx (7)

1-1: LGTM: Import improvements enhance maintainability.

The addition of JSX import (valid in React 17+), Next.js Image for optimization, and centralized network constants improves code organization and performance.

Also applies to: 5-5, 13-20


205-207: LGTM: Improved type safety with union types.

The explicit typing of Tab as a union type and default constants improve type safety and code clarity.


226-237: LGTM: Clean modularization of tab rendering.

The Tabs component is well-structured with proper typing and clear separation of concerns.


320-331: LGTM: Proper input validation for amount handling.

The input validation correctly prevents negative values and handles numeric conversion appropriately.


333-344: LGTM: Proper swap URL generation.

The URL generation correctly uses the centralized network mappings and includes all necessary parameters for the swap interface.


355-356: LGTM: Performance improvement with Next.js Image components.

The switch from <img> tags to Next.js <Image> components provides better performance through automatic optimization, and using centralized mappings improves maintainability.

Also applies to: 366-366


209-224: ```shell
#!/bin/bash

Locate getBuyAndSellTokens usage and inspect URL construction in SwapWidget.tsx

Find where the utility is invoked

rg -n "getBuyAndSellTokens" apps/cow-fi/components/SwapWidget.tsx

Dump lines around the invocation to see how sellToken/buyToken are embedded in the URL

sed -n '180,260p' apps/cow-fi/components/SwapWidget.tsx

Check for literal swap URL patterns in this file

rg -n "https://swap.cow.fi" apps/cow-fi/components/SwapWidget.tsx


</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

const [network, setNetwork] = useState<string | null>(null)
return (
<DropdownBody>
{ethereum?.contractAddress && (
Copy link
Collaborator

Choose a reason for hiding this comment

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

function DropdownNetworkOption({ network }: { network: Network }) {
  return (
    <DropdownOption  => handleSelect(network)}>
          <Image src={NETWORK_IMAGE_MAP[network]} alt={NETWORK_MAP[network]} width={width} height={height} />
          {NETWORK_MAP[network]}
        </DropdownOption>
  )
}

{ ethereum?.contractAddress && <DropdownNetworkOption network="ethereum" /> }
{ base?.contractAddress && <DropdownNetworkOption network="base" /> }
...

else if (arbitrum?.contractAddress) setNetwork('arbitrum-one')
else if (polygon?.contractAddress) setNetwork('polygon-pos')
else if (avalanche?.contractAddress) setNetwork('avalanche')
else if (xdai?.contractAddress) setNetwork('xdai')
Copy link
Collaborator

Choose a reason for hiding this comment

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

function getNetworkFromPlatforms(platforms): Network {
  const { ethereum, xdai, base, 'arbitrum-one': arbitrum, avalanche, 'polygon-pos': polygon } = platforms
  
  if (ethereum?.contractAddress) return 'ethereum'
  if (base?.contractAddress) return 'base'
  if (arbitrum?.contractAddress) return 'arbitrum-one'
  ...
}

useEffect(() => {
  setNetwork(getNetworkFromPlatforms(platforms))
}, [platforms])

Copy link
Collaborator
@shoom3301 shoom3301 left a comment

Choose a reason for hiding this comment

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

Looks good, just needs some refacting to get rid of code duplcations

Copy link
Contributor
@elena-zh elena-zh left a comment

Choose a reason for hiding this comment

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

Hey @cowdan , works great, thank you.
FYI: I've link the original task that is fixed by this PR
image

setNetwork(network)
setIsOpen(false)
}

function getNetworkFromPlatforms(platforms: Platforms): Network {
Copy link
Collaborator

Choose a reason for hiding this comment

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

The function should be outside of the component body

@alfetopito alfetopito merged commit 14952b3 into develop Jun 30, 2025
14 of 15 checks passed
@alfetopito alfetopito deleted the feat/refactor-token-detail-swap-widget branch June 30, 2025 14:02
@github-actions github-actions bot locked and limited conversation to collaborators Jun 30, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add chains into trade widget on Tokens page
4 participants
0