8000 fix(bridge): do not crash calculating usd price in unsupported chain by shoom3301 · Pull Request #5849 · cowprotocol/cowswap · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

fix(bridge): do not crash calculating usd price in unsupported chain #5849

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 19, 2025

Conversation

shoom3301
Copy link
Collaborator
@shoom3301 shoom3301 commented Jun 18, 2025

Summary

Fixes https://www.notion.so/cownation/Crash-when-destination-token-on-optimism-2148da5f04ca80d89a49faef54abe124?pvs=25

To Test

See https://www.notion.so/cownation/Crash-when-destination-token-on-optimism-2148da5f04ca80d89a49faef54abe124?pvs=25

Summary by CodeRabbit

  • New Features

    • Added support for USDC on the Optimism network.
  • Bug Fixes

    • Improved price calculation logic to prevent errors when USDC token data is missing for a specific network.
  • Chores

    • Updated token definitions and standardized references for better consistency across supported networks.
    • Enhanced network support data fetching with improved type annotations.

@shoom3301 shoom3301 self-assigned this Jun 18, 2025
Copy link
vercel bot commented Jun 18, 2025

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

Name Status Preview Updated (UTC)
cowfi ✅ Ready (Inspect) Visit Preview Jun 19, 2025 5:45am
explorer-dev ✅ Ready (Inspect) Visit Preview Jun 19, 2025 5:45am
swap-dev ✅ Ready (Inspect) Visit Preview Jun 19, 2025 5:45am
3 Skipped Deployments
Name Status Preview Updated (UTC)
cosmos ⬜️ Ignored (Inspect) Visit Preview Jun 19, 2025 5:45am
sdk-tools ⬜️ Ignored (Inspect) Visit Preview Jun 19, 2025 5:45am
widget-configurator ⬜️ Ignored (Inspect) Visit Preview Jun 19, 2025 5:45am

Copy link
Contributor
coderabbitai bot commented Jun 18, 2025

Walkthrough

The changes introduce a new USDC token for the Optimism chain, update type definitions to include additional chain IDs, and remove an unused token shorthand mapping. A guard clause is added to the USD token price calculation to handle missing USDC tokens more safely. The return type of a hook fetching bridge-supported networks was explicitly annotated.

Changes

File(s) Change Summary
libs/common-const/src/tokens.ts Added USDC token for Optimism, updated imports and type definitions for chain IDs, removed TOKEN_SHORTHANDS, updated STABLECOINS.
apps/cowswap-frontend/src/modules/usdAmount/state/usdTokenPricesAtom.ts Added guard clause in calculatePrice to return null if USDC token for the chain is missing.
apps/cowswap-frontend/src/entities/bridgeProvider/useBridgeSupportedNetworks.ts Added explicit return type annotation to useBridgeSupportedNetworks function and updated related imports.

Suggested reviewers

  • alfetopito

Poem

In the garden of tokens, a new one appears,
Optimism's USDC hops in with cheers!
Guarded calculations keep bugs at bay,
Shorthands have vanished, they've hopped away.
Chains and coins now neatly aligned—
The codebase grows strong, robustly designed!
🐇✨

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:14985) [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.2.0"
error Found incompatible module.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

✨ 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.
  • @co 8000 derabbitai 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)
libs/common-const/src/tokens.ts (1)

416-424: Use checksum-cased address for the new Optimism USDC token

All other addresses in this file are EIP-55 checksum-cased, while the newly added Optimism address is all lowercase.
Keeping a consistent casing style avoids accidental double entries and prevents UX discrepancies when addresses are copy-pasted elsewhere.

-  '0x0b2c639c533813f4aa9d7837caf62653d097ff85',
+  '0x0B2C639c533813F4Aa9D7837cAF62653D097fF85',
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f49e48d and 91cd9fa.

📒 Files selected for processing (2)
  • apps/cowswap-frontend/src/modules/usdAmount/state/usdTokenPricesAtom.ts (1 hunks)
  • libs/common-const/src/tokens.ts (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Setup
  • GitHub Check: Cypress
🔇 Additional comments (2)
libs/common-const/src/tokens.ts (2)

436-445: Index type still narrows to SupportedChainId in downstream code

USDC is correctly widened to
Record<SupportedChainId | AdditionalTargetChainId, TokenWithLogo> here, but downstream look-ups (see usdTokenPricesAtom.ts) still cast currency.chainId to SupportedChainId.
This loses type-safety for Optimism and any future additional chains.

Minimal fix in the consumer:

-const usdcToken = USDC[currency.chainId as SupportedChainId]
+const usdcToken = USDC[currency.chainId as keyof typeof USDC]

(see separate comment in usdTokenPricesAtom.ts)

#!/bin/bash
# Find remaining sites that still cast to SupportedChainId
rg --context 2 -e 'as SupportedChainId' --type ts

1-1: Removed TOKEN_SHORTHANDS: ensure no remaining references

TOKEN_SHORTHANDS was deleted in this diff. If any module still imports or accesses it, the build will break.

#!/bin/bash
# Search for stale imports / usages
rg -n "TOKEN_SHORTHANDS"

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)
libs/common-const/src/tokens.ts (1)

416-424: Use checksummed address for USDC_OPTIMISM

All other token declarations follow the EIP-55 checksum format; the Optimism address is all lower-case.
This breaks strict–equality look-ups and makes human review harder.

-  '0x0b2c639c533813f4aa9d7837caf62653d097ff85',
+  '0x0B2C639c533813F4Aa9D7837Caf62653D097Ff85',
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f49e48d and 91cd9fa.

📒 Files selected for processing (2)
  • apps/cowswap-frontend/src/modules/usdAmount/state/usdTokenPricesAtom.ts (1 hunks)
  • libs/common-const/src/tokens.ts (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
libs/common-const/src/tokens.ts (3)
libs/common-const/src/types.ts (1)
  • TokenWithLogo (6-32)
libs/widget-lib/src/types.ts (1)
  • SupportedChainId (4-4)
libs/common-const/src/nativeAndWrappedTokens.ts (1)
  • WETH_MAINNET (132-132)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cypress
🔇 Additional comments (1)
libs/common-const/src/tokens.ts (1)

436-445: Update downstream look-ups now that USDC accepts AdditionalTargetChainId

The widened record is great, but be sure every consumer stops asserting SupportedChainId only (see usdTokenPricesAtom.ts).
A quick repo scan for USDC[.* as SupportedChainId will surface the remaining call-sites.

#!/bin/bash
# Find unsafe casts that may now hide unsupported-chain bugs
rg -n $'USDC\\[.* as SupportedChainId' | head -n 20

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.

The app is no longer crashed when pick a token on Optimism

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 comments (1)
apps/cowswap-frontend/src/entities/bridgeProvider/useBridgeSupportedNetworks.ts (1)

10-12: Key may change every render – could cause unnecessary revalidations

bridgeProvider is an object reference that is likely recreated on each context update.
Including the plain object in the SWR key can trigger an unexpected re-fetch loop when its reference identity changes even though the underlying network set is unchanged.

Consider using a stable identifier (e.g. bridgeProvider.id or the provider’s chainId array) as part of the key, or stringify:

-  return useSWR([bridgeProvider, 'useBridgeSupportedNetworks'], ([bridgeProvider]) => {
+  return useSWR(
+    [bridgeProvider?.id, 'useBridgeSupportedNetworks'], // stable key
+    () => bridgeProvider?.getNetworks()
+  )

This keeps revalidation predictable and prevents needless network calls.

🧹 Nitpick comments (2)
apps/cowswap-frontend/src/entities/bridgeProvider/useBridgeSupportedNetworks.ts (2)

3-3: Import SWRResponse as a type-only import

Tree-shaking and build-time performance benefit slightly if SWRResponse is imported with the TypeScript type modifier.

-import useSWR, { SWRResponse } from 'swr'
+import useSWR from 'swr'
+import type { SWRResponse } from 'swr'

7-7: Specify the error type in SWRResponse for stronger type safety

SWRResponse<Data = any, Error = any> defaults the error parameter to any, losing useful information.
If bridgeProvider.getNetworks() rejects with a known error type (e.g. Error), declare it explicitly:

-export function useBridgeSupportedNetworks(): SWRResponse<ChainInfo[]> {
+export function useBridgeSupportedNetworks(): SWRResponse<ChainInfo[], Error> {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 91cd9fa and e5dd055.

📒 Files selected for processing (2)
  • apps/cowswap-frontend/src/entities/bridgeProvider/useBridgeSupportedNetworks.ts (1 hunks)
  • libs/common-const/src/tokens.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/common-const/src/tokens.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Cypress
  • GitHub Check: Setup

@shoom3301 shoom3301 merged commit 9992365 into develop Jun 19, 2025
14 of 15 checks passed
@shoom3301 shoom3301 deleted the fix/bridging-optimism branch June 19, 2025 06:14
@github-actions github-actions bot locked and limited conversation to collaborators Jun 19, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
0