Skip to content

Comments

fix/sending-tokens-issue#258

Merged
RanaBug merged 1 commit intostagingfrom
fix/sending-tokens-issue
Mar 17, 2025
Merged

fix/sending-tokens-issue#258
RanaBug merged 1 commit intostagingfrom
fix/sending-tokens-issue

Conversation

@RanaBug
Copy link
Collaborator

@RanaBug RanaBug commented Mar 14, 2025

Description

  • Fix sending native/gas token issue since we changed the token list

How Has This Been Tested?

  • Existing Unit Tests and Manual Testing

Screenshots (if appropriate):

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Summary by CodeRabbit

  • New Features

    • Enhanced token data integration by dynamically including native token details across supported networks.
    • Improved token query flexibility to ensure robust retrieval of token information based on user selection.
  • Refactor

    • Simplified balance validation logic within the user interface for clearer native asset checks.
    • Streamlined query construction and token selection processes, reducing complexity and optimizing performance.

@RanaBug RanaBug requested a review from IAmKio March 14, 2025 17:36
@RanaBug RanaBug self-assigned this Mar 14, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 14, 2025

Walkthrough

This pull request simplifies native token handling across the project by removing the dependency on the nativeTokensByChain mapping. Balance validation logic in several components now checks only for a null token or a zero address. The token-atlas API endpoints have been updated to allow optional parameters and build query strings conditionally. Additionally, a new utility function is used in the token-atlas index to detect native tokens based on chain ID, and the tokens data loader has been modified to include native token information by iterating over compatible chains.

Changes

File(s) Change Summary
src/apps/.../EnterAmount.tsx, src/components/.../AccountModal.tsx, src/components/.../AssetSelect/index.tsx Removed nativeTokensByChain import and simplified native token checks by validating only for null tokens or zero addresses (with minor reordering in dependency arrays).
src/apps/.../api/token.ts Updated query endpoints: made id optional in both endpoints and required symbol for getTokenGraph, with improved conditional query string construction.
src/apps/.../index.tsx Introduced native token detection using getNativeAssetForChainId to create a formatted token object and conditionally modify API query parameters based on token identity.
src/services/tokensData.ts Enhanced loadTokensData to include native tokens by iterating over CompatibleChains and appending a native token option to the tokens data array.
src/utils/blockchain.ts Removed the nativeTokensByChain constant, eliminating the predefined blockchain-to-token mapping.

Sequence Diagram(s)

sequenceDiagram
  participant U as User
  participant TA as Token Atlas Component
  participant G as getNativeAssetForChainId
  participant Q as Query Hooks

  U->>TA: Select a token
  TA->>G: Retrieve native token by chain ID
  G-->>TA: Return native token info
  TA->>TA: Compare selected token with native token
  alt Token is native
    TA->>Q: Query API with id & asset as undefined
  else Token is not native
    TA->>Q: Query API with complete token details
  end
Loading

Possibly related PRs

Suggested reviewers

  • IAmKio

Poem

I'm a bunny with a skip so light,
Hopping through code both day and night.
Native checks now smooth and clear,
No tangled chains to bring me fear.
With every line, my joy takes flight!
🐇✨

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ 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.
    • 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 generate docstrings to generate docstrings for 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.

@cloudflare-workers-and-pages
Copy link

Deploying x with  Cloudflare Pages  Cloudflare Pages

Latest commit: ffd0bdb
Status: ✅  Deploy successful!
Preview URL: https://8c85ed34.x-e62.pages.dev
Branch Preview URL: https://fix-sending-tokens-issue.x-e62.pages.dev

View logs

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a61fe36 and ffd0bdb.

⛔ Files ignored due to path filters (1)
  • src/apps/pillarx-app/components/PointsTile/test/__snapshots__/PointsTile.test.tsx.snap is excluded by !**/*.snap
📒 Files selected for processing (7)
  • src/apps/the-exchange/components/EnterAmount/EnterAmount.tsx (1 hunks)
  • src/apps/token-atlas/api/token.ts (2 hunks)
  • src/apps/token-atlas/index.tsx (3 hunks)
  • src/components/BottomMenuModal/AccountModal.tsx (2 hunks)
  • src/components/Form/AssetSelect/index.tsx (2 hunks)
  • src/services/tokensData.ts (2 hunks)
  • src/utils/blockchain.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/utils/blockchain.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: unit-tests
  • GitHub Check: lint
  • GitHub Check: build
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (19)
src/components/BottomMenuModal/AccountModal.tsx (2)

88-92: Simplification of native token detection logic

The code has been simplified to use a more direct approach for detecting native tokens, checking if the asset's contract address equals the balance token or if the balance token is null and the asset's contract is a zero address, removing the dependency on the nativeTokensByChain mapping.


107-107: Reordered useMemo dependencies

The dependency array in the useMemo hook has been reordered to place addressesEqual before isZeroAddress. While this change won't affect functionality, maintaining consistent ordering of dependencies is good practice.

src/apps/the-exchange/components/EnterAmount/EnterAmount.tsx (2)

175-175: Simplified native balance detection

The isNativeBalance condition has been simplified to check only if the balance token is null or a zero address, removing the dependency on the nativeTokensByChain mapping.


178-178: Updated native token validation in return statement

The return statement has been adjusted to check if the balance is a native balance and the asset address is a zero address, providing a more direct approach to determining valid asset addresses.

src/components/Form/AssetSelect/index.tsx (4)

25-25: Removed nativeTokensByChain import

The nativeTokensByChain import has been removed from the import statement, consistent with the approach in other files to reduce dependency on predefined native token lists.


147-149: Simplified native balance detection

The isNativeBalance condition has been simplified to check only if the balance token is null or a zero address, removing the dependency on the nativeTokensByChain mapping.


150-153: Simplified native asset detection

The isNativeAsset condition has been simplified to check if the asset contract is falsy or a zero address, making the code more direct and easier to understand.


154-159: Combined asset-balance matching logic

The return statement has been restructured to combine all checks into a single, more readable condition:

  1. Check if the balance is native AND the asset is native, OR
  2. Check if both the balance token and asset contract exist AND they are equal

This approach is clearer and more maintainable than the previous implementation.

src/services/tokensData.ts (3)

4-7: Good additions for native token handling

The added imports for CompatibleChains and getNativeAssetForChainId are necessary for the new functionality to add native tokens to the token list.


62-75: Native token integration looks good

This is a well-structured implementation to add native tokens to the token list. The code iterates through the compatible chains, gets the native asset for each chain ID, and correctly formats it to match the Token type structure.

A couple notes:

  1. It's used within the existing check for empty tokensData, which prevents duplicate additions on subsequent calls
  2. The chainIdToChainNameTokensData function appropriately maps chain IDs to the expected naming format

70-70:

Details

✅ Verification successful

Verify chain name mapping for all supported native tokens

Make sure that all chain IDs in CompatibleChains are properly handled by the chainIdToChainNameTokensData function.


🏁 Script executed:

#!/bin/bash
# Check if all chain IDs in CompatibleChains are handled in the chainIdToChainNameTokensData function

# First, find all chain IDs in CompatibleChains
echo "Getting all chain IDs from CompatibleChains..."
CHAIN_IDS=$(rg -A 30 "export const CompatibleChains" src/utils/blockchain.ts | rg "chainId:" | sed -E 's/.*chainId: ([0-9]+).*/\1/')

echo "Found chain IDs: $CHAIN_IDS"

# Then, check if they're all handled in the chainIdToChainNameTokensData function
echo "Checking if all chain IDs are handled in chainIdToChainNameTokensData function..."
for id in $CHAIN_IDS; do
  if ! rg "case $id:" src/services/tokensData.ts > /dev/null; then
    echo "WARNING: Chain ID $id from CompatibleChains is not explicitly handled in chainIdToChainNameTokensData"
  else
    echo "Chain ID $id is handled in chainIdToChainNameTokensData"
  fi
done

Length of output: 3991


Mapping Verification Confirmed: Numeric Chain IDs Are Correctly Handled

The verification shows that the expected numeric chain IDs (1, 137, 8453, and 100) from CompatibleChains are all explicitly mapped in the chainIdToChainNameTokensData function. Note that the additional non-numeric warnings were artifacts from the extraction process and do not indicate actual missing mappings.

  • Verified chain IDs: 1, 137, 8453, 100.
  • Ensure that as new numeric chain IDs are added to CompatibleChains, the function is updated accordingly.
src/apps/token-atlas/index.tsx (5)

23-24: Good addition of the native asset utility

Adding the import for getNativeAssetForChainId is appropriate for the native token detection implementation.


65-72: Well-structured token formatting

This formatting of the selected token into a consistent structure that can be compared with the native token is clean and straightforward.


74-79: Effective native token detection logic

The approach to determine if the selected token is a native token by comparing name, symbol, and address is thorough. This will correctly identify native tokens like ETH, MATIC, etc.


87-90: Good conditional query parameter handling

Setting the id and asset parameters to undefined for native tokens ensures that the API won't attempt to fetch data that doesn't exist for native tokens.


99-104: Consistent parameter handling across queries

The same conditional approach for id and asset parameters is correctly applied to the token graph query as well, maintaining consistency.

src/apps/token-atlas/api/token.ts (3)

32-32: Good update to parameter types

Making the id parameter optional is necessary to support the changes in index.tsx where these parameters are conditionally set to undefined for native tokens.


35-35: Improved conditional query string construction

The updated query string construction correctly handles optional parameters, only including them when they are provided. This implementation is more flexible and robust.


52-55: Consistent parameter type updates

Making the id parameter optional and the symbol parameter required aligns with how these parameters are being used in the application.

query: ({ id, asset, symbol, from, to }) => {
const toParam = to !== undefined ? `&to=${from * 1000}` : '';
return `?id=${id}&asset=${asset}&from=${from * 1000}${toParam}&${chainIdsQuery}&testnets=${String(isTestnet)}`;
return `${id ? `id=${id}` : ''}${asset ? `&asset=${asset}` : ''}&symbol=${symbol}&from=${from * 1000}${toParam}&${chainIdsQuery}&testnets=${String(isTestnet)}`;
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify the query string construction for all cases

Let's verify that the query string construction works correctly for all combinations of parameters:


🏁 Script executed:

#!/bin/bash
# Test the query string construction for the getTokenGraph endpoint

echo "Testing query string construction for various parameter combinations"

# Define a simple function to simulate the getTokenGraph query construction
cat << 'EOF' > /tmp/test_query.js
function buildQuery(id, asset, symbol, from, to) {
  const toParam = to !== undefined ? `&to=${from * 1000}` : '';
  return `${id ? `id=${id}` : ''}${asset ? `&asset=${asset}` : ''}&symbol=${symbol}&from=${from * 1000}${toParam}&chainIds=123&testnets=false`;
}

// Test cases
console.log("Case 1 - All parameters defined:");
console.log(buildQuery(123, "ETH", "ETH", 1000, 2000));

console.log("\nCase 2 - id undefined:");
console.log(buildQuery(undefined, "ETH", "ETH", 1000, 2000));

console.log("\nCase 3 - asset undefined:");
console.log(buildQuery(123, undefined, "ETH", 1000, 2000));

console.log("\nCase 4 - both id and asset undefined:");
console.log(buildQuery(undefined, undefined, "ETH", 1000, 2000));

console.log("\nCase 5 - to undefined:");
console.log(buildQuery(123, "ETH", "ETH", 1000, undefined));
EOF

# Run the test script
node /tmp/test_query.js

Length of output: 682


Fix the "to" parameter calculation in the query string construction

The test output confirms that when the to parameter is provided, the query string incorrectly computes its value using from * 1000 instead of to * 1000. For example, in Case 1 the output is:

id=123&asset=ETH&symbol=ETH&from=1000000&to=1000000&chainIds=123&testnets=false

but the expectation is for the to value to be converted using the to parameter (i.e., 2000 * 1000 = 2000000). Please adjust the logic accordingly.

  • File: src/apps/token-atlas/api/token.ts (around line 61)
  • Suggested change:
    Replace the current implementation:
    const toParam = to !== undefined ? `&to=${from * 1000}` : '';
    with:
    const toParam = to !== undefined ? `&to=${to * 1000}` : '';

Comment on lines +59 to +61
query: ({ id, asset, symbol, from, to }) => {
const toParam = to !== undefined ? `&to=${from * 1000}` : '';
return `?id=${id}&asset=${asset}&from=${from * 1000}${toParam}&${chainIdsQuery}&testnets=${String(isTestnet)}`;
return `${id ? `id=${id}` : ''}${asset ? `&asset=${asset}` : ''}&symbol=${symbol}&from=${from * 1000}${toParam}&${chainIdsQuery}&testnets=${String(isTestnet)}`;
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

Enhanced query string formatting

The updated query string construction for the token graph endpoint follows the same pattern as the token info endpoint, ensuring consistency across the API.

However, there's a potential issue with the query string when both id and asset are undefined - the string would start with an & character.

- return `${id ? `id=${id}` : ''}${asset ? `&asset=${asset}` : ''}&symbol=${symbol}&from=${from * 1000}${toParam}&${chainIdsQuery}&testnets=${String(isTestnet)}`;
+ // Build parameters array and filter out empty ones
+ const params = [
+   id ? `id=${id}` : '',
+   asset ? `asset=${asset}` : '',
+   `symbol=${symbol}`,
+   `from=${from * 1000}`,
+   toParam.startsWith('&') ? toParam.substring(1) : toParam,
+   chainIdsQuery,
+   `testnets=${String(isTestnet)}`
+ ].filter(param => param !== '');
+ 
+ // Join with & and return
+ return params.join('&');
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
query: ({ id, asset, symbol, from, to }) => {
const toParam = to !== undefined ? `&to=${from * 1000}` : '';
return `?id=${id}&asset=${asset}&from=${from * 1000}${toParam}&${chainIdsQuery}&testnets=${String(isTestnet)}`;
return `${id ? `id=${id}` : ''}${asset ? `&asset=${asset}` : ''}&symbol=${symbol}&from=${from * 1000}${toParam}&${chainIdsQuery}&testnets=${String(isTestnet)}`;
query: ({ id, asset, symbol, from, to }) => {
const toParam = to !== undefined ? `&to=${from * 1000}` : '';
// Build parameters array and filter out empty ones
const params = [
id ? `id=${id}` : '',
asset ? `asset=${asset}` : '',
`symbol=${symbol}`,
`from=${from * 1000}`,
toParam.startsWith('&') ? toParam.substring(1) : toParam,
chainIdsQuery,
`testnets=${String(isTestnet)}`
].filter(param => param !== '');
// Join with & and return
return params.join('&');
}

Copy link
Collaborator

@IAmKio IAmKio left a comment

Choose a reason for hiding this comment

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

LGTM

@RanaBug RanaBug merged commit a34157f into staging Mar 17, 2025
7 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Mar 17, 2025
3 tasks
@coderabbitai coderabbitai bot mentioned this pull request May 29, 2025
3 tasks
@coderabbitai coderabbitai bot mentioned this pull request Sep 8, 2025
3 tasks
@coderabbitai coderabbitai bot mentioned this pull request Oct 7, 2025
3 tasks
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