Skip to content

[SDK] Add Bridge.tokens() function to retrieve supported tokens #7240

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

Conversation

joaquim-verges
Copy link
Member

@joaquim-verges joaquim-verges commented May 31, 2025


PR-Codex overview

This PR introduces the Bridge.tokens() function to retrieve and filter supported Universal Bridge tokens, enhancing the ability to fetch token data by various parameters such as chain ID, token address, symbol, and name.

Detailed summary

  • Added tokens export in packages/thirdweb/src/bridge/index.ts.
  • Implemented getTokenPrice function in packages/thirdweb/src/pay/convert/get-token.ts.
  • Created tests for tokens in packages/thirdweb/src/bridge/Token.test.ts.
  • Enhanced convertFiatToCrypto and convertCryptoToFiat functions to use getTokenPrice.
  • Developed tokens function in packages/thirdweb/src/bridge/Token.ts with filtering capabilities.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features

    • Added the ability to retrieve supported bridge tokens with advanced filtering options such as chain, address, symbol, and name, including pagination support.
  • Bug Fixes

    • Improved the accuracy and reliability of crypto-to-fiat and fiat-to-crypto conversions by updating the token price fetching mechanism.
  • Tests

    • Introduced comprehensive tests to ensure correct behavior of token retrieval and filtering features.
  • Refactor

    • Simplified and optimized internal logic for fetching token prices, reducing complexity and improving maintainability.

Copy link

vercel bot commented May 31, 2025

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

Name Status Preview Comments Updated (UTC)
docs-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 31, 2025 9:14am
login ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 31, 2025 9:14am
thirdweb_playground ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 31, 2025 9:14am
thirdweb-www ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 31, 2025 9:14am
wallet-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 31, 2025 9:14am

Copy link

changeset-bot bot commented May 31, 2025

🦋 Changeset detected

Latest commit: cac3039

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
thirdweb Patch
@thirdweb-dev/wagmi-adapter Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented May 31, 2025

Walkthrough

A new tokens function is added to the thirdweb package, enabling retrieval and filtering of tokens supported by the Universal Bridge service. This function is exported and documented, with comprehensive tests included. Related price conversion utilities are refactored to use a new getTokenPrice helper, which fetches token prices with caching.

Changes

File(s) Change Summary
.changeset/bridge-tokens-function.md Documents the introduction of the Bridge.tokens() function, its filtering, and pagination capabilities.
packages/thirdweb/src/bridge/Token.ts Adds the tokens async function for fetching and filtering bridge-supported tokens. Defines related types.
packages/thirdweb/src/bridge/Token.test.ts Introduces a new test suite for the tokens function, covering filtering, pagination, and structure checks.
packages/thirdweb/src/bridge/index.ts Exports the new tokens function from the bridge module.
packages/thirdweb/src/pay/convert/cryptoToFiat.ts
fiatToCrypto.ts
Refactors price fetching logic to use the new getTokenPrice helper instead of the previous cached approach.
packages/thirdweb/src/pay/convert/get-token.ts Adds the getTokenPrice function, which retrieves and caches a token's USD price using the new tokens API.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant ThirdwebClient
    participant BridgeAPI

    App->>ThirdwebClient: tokens({filters, pagination, client})
    ThirdwebClient->>BridgeAPI: GET /bridge/tokens?filters...
    BridgeAPI-->>ThirdwebClient: [token objects]
    ThirdwebClient-->>App: [token objects]
Loading
sequenceDiagram
    participant App
    participant ThirdwebClient
    participant getTokenPrice
    participant BridgeAPI

    App->>ThirdwebClient: convertCryptoToFiat/convertFiatToCrypto(...)
    ThirdwebClient->>getTokenPrice: getTokenPrice(client, tokenAddress, chainId)
    getTokenPrice->>BridgeAPI: GET /bridge/tokens?tokenAddress&chainId
    BridgeAPI-->>getTokenPrice: [token object with priceUsd]
    getTokenPrice-->>ThirdwebClient: priceUsd
    ThirdwebClient-->>App: Conversion result
Loading

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • TEAM-0000: Entity not found: Issue - Could not find referenced Issue.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.

@github-actions github-actions bot added packages SDK Involves changes to the thirdweb SDK labels May 31, 2025
Copy link
Member Author


How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • merge-queue - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

This stack of pull requests is managed by Graphite. Learn more about stacking.

@joaquim-verges joaquim-verges changed the title [Bridge] Add tokens() function to retrieve supported tokens [SDK] Add Bridge.tokens() function to retrieve supported tokens May 31, 2025
@joaquim-verges joaquim-verges marked this pull request as ready for review May 31, 2025 09:06
@joaquim-verges joaquim-verges requested review from a team as code owners May 31, 2025 09:06
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 (3)
.changeset/bridge-tokens-function.md (1)

7-7: Minor documentation enhancement suggestion.

The documentation is clear and accurate. For slightly improved readability, consider adding a determiner:

-New function allows fetching and filtering tokens supported by the Universal Bridge service.
+This new function allows fetching and filtering tokens supported by the Universal Bridge service.

However, the current text is perfectly acceptable.

packages/thirdweb/src/bridge/Token.test.ts (2)

5-90: Excellent test coverage! Consider adding edge case tests.

The test suite is comprehensive and well-structured. The tests cover the main functionality effectively with good assertions.

Suggestions for additional test coverage:

  1. Edge cases: Consider adding tests for empty results, invalid parameters, or error conditions.

  2. Symbol filtering behavior: The current test uses toContain("ETH") which suggests substring matching. If this is the intended behavior, consider adding a test case that explicitly validates this:

it("should support substring matching for symbol filter", async () => {
  const result = await tokens({
    client: TEST_CLIENT,
    symbol: "USD", // Should match USDC, USDT, etc.
  });
  
  for (const token of result) {
    expect(token.symbol).toContain("USD");
  }
});
  1. Offset parameter: If the tokens function supports offset for pagination, consider adding a test for that as well.

17-35: Consider simplifying the structure validation.

The nested conditional check could be simplified:

// Basic structure validation
if (result.length > 0) {
  const token = result[0];
  expect(token).toBeDefined();
  expect(token).toHaveProperty("chainId");
  expect(token).toHaveProperty("address");
  expect(token).toHaveProperty("decimals");
  expect(token).toHaveProperty("symbol");
  expect(token).toHaveProperty("name");
  expect(token).toHaveProperty("priceUsd");

-  if (token) {
    expect(typeof token.chainId).toBe("number");
    expect(typeof token.address).toBe("string");
    expect(typeof token.decimals).toBe("number");
    expect(typeof token.symbol).toBe("string");
    expect(typeof token.name).toBe("string");
    expect(typeof token.priceUsd).toBe("number");
-  }
}

The inner if (token) check is redundant since we already confirmed the token exists and is defined.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4e93539 and cac3039.

📒 Files selected for processing (7)
  • .changeset/bridge-tokens-function.md (1 hunks)
  • packages/thirdweb/src/bridge/Token.test.ts (1 hunks)
  • packages/thirdweb/src/bridge/Token.ts (1 hunks)
  • packages/thirdweb/src/bridge/index.ts (1 hunks)
  • packages/thirdweb/src/pay/convert/cryptoToFiat.ts (3 hunks)
  • packages/thirdweb/src/pay/convert/fiatToCrypto.ts (3 hunks)
  • packages/thirdweb/src/pay/convert/get-token.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/thirdweb/src/pay/convert/fiatToCrypto.ts (2)
packages/thirdweb/src/pay/convert/get-token.ts (1)
  • getTokenPrice (5-24)
packages/engine/src/client/client.gen.ts (1)
  • client (24-28)
packages/thirdweb/src/pay/convert/cryptoToFiat.ts (2)
packages/thirdweb/src/pay/convert/get-token.ts (1)
  • getTokenPrice (5-24)
packages/engine/src/client/client.gen.ts (1)
  • client (24-28)
🪛 LanguageTool
.changeset/bridge-tokens-function.md

[uncategorized] ~6-~6: A determiner appears to be missing. Consider inserting it.
Context: ...ieve supported Universal Bridge tokens New function allows fetching and filtering ...

(AI_EN_LECTOR_MISSING_DETERMINER)

🪛 Gitleaks (8.26.0)
packages/thirdweb/src/bridge/Token.ts

79-79: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Size
  • GitHub Check: Build Packages
  • GitHub Check: Unit Tests
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (12)
packages/thirdweb/src/bridge/index.ts (1)

9-9: LGTM! Export follows established conventions.

The export statement correctly follows the same pattern as other bridge exports and is appropriately placed among similar single-function exports.

packages/thirdweb/src/pay/convert/fiatToCrypto.ts (3)

8-8: LGTM: Clean import of new helper function.

The switch to using the dedicated getTokenPrice helper improves code organization and reusability.


63-63: Good: Removed unused parameter from destructuring.

Removing the unused from parameter cleans up the code since it's not used in the function logic.


93-99: LGTM: Simplified token price fetching with improved error handling.

The refactoring to use getTokenPrice simplifies the logic while maintaining the same functionality. The error condition properly handles both null/undefined and zero price scenarios.

packages/thirdweb/src/pay/convert/cryptoToFiat.ts (3)

8-8: LGTM: Consistent use of the getTokenPrice helper.

Good to see consistent refactoring approach across both conversion functions.


62-62: Good: Removed unused parameter.

Cleaning up the unused to parameter improves code clarity.


95-101: LGTM: Simplified price fetching and calculation.

The refactoring maintains the same functionality while using the centralized getTokenPrice helper. The multiplication logic for the final result is correct.

packages/thirdweb/src/bridge/Token.ts (5)

1-6: LGTM: Clean imports and dependencies.

All necessary imports are properly organized and relevant to the functionality.


7-117: Excellent: Comprehensive documentation with practical examples.

The JSDoc documentation is exceptionally thorough with multiple usage examples covering:

  • Basic usage
  • Filtering by various parameters (chainId, symbol, name, tokenAddress)
  • Pagination with limit/offset
  • Expected response structure

This level of documentation significantly improves developer experience.

🧰 Tools
🪛 Gitleaks (8.26.0)

79-79: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


118-143: LGTM: Robust parameter handling and URL construction.

The function properly handles optional parameters with explicit null/undefined checks, which is important for query parameter construction. The URL building logic correctly adds parameters only when they have valid values.


144-157: LGTM: Comprehensive error handling and response processing.

The error handling is well-structured:

  • Proper HTTP status checking
  • Structured error parsing with fallbacks
  • ApiError with relevant context (code, message, correlationId, statusCode)
  • Clean response data extraction

159-184: LGTM: Well-structured TypeScript namespace declarations.

The namespace provides clear type definitions for both input options and result types, improving type safety and developer experience.

Copy link

codecov bot commented May 31, 2025

Codecov Report

Attention: Patch coverage is 74.32432% with 19 lines in your changes missing coverage. Please review.

Project coverage is 55.61%. Comparing base (4e93539) to head (cac3039).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
packages/thirdweb/src/bridge/Token.ts 61.53% 15 Missing ⚠️
packages/thirdweb/src/pay/convert/cryptoToFiat.ts 66.66% 2 Missing ⚠️
packages/thirdweb/src/pay/convert/fiatToCrypto.ts 66.66% 2 Missing ⚠️

❌ Your patch status has failed because the patch coverage (74.32%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7240      +/-   ##
==========================================
- Coverage   55.61%   55.61%   -0.01%     
==========================================
  Files         908      910       +2     
  Lines       58583    58597      +14     
  Branches     4133     4137       +4     
==========================================
+ Hits        32583    32589       +6     
- Misses      25894    25903       +9     
+ Partials      106      105       -1     
Flag Coverage Δ
packages 55.61% <74.32%> (-0.01%) ⬇️
Files with missing lines Coverage Δ
packages/thirdweb/src/bridge/index.ts 100.00% <100.00%> (ø)
packages/thirdweb/src/pay/convert/get-token.ts 100.00% <100.00%> (ø)
packages/thirdweb/src/pay/convert/cryptoToFiat.ts 90.47% <66.66%> (+2.59%) ⬆️
packages/thirdweb/src/pay/convert/fiatToCrypto.ts 90.00% <66.66%> (+2.50%) ⬆️
packages/thirdweb/src/bridge/Token.ts 61.53% <61.53%> (ø)

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Contributor

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 62.24 KB (+0.16% 🔺) 1.3 s (+0.16% 🔺) 172 ms (+121.69% 🔺) 1.5 s
thirdweb (cjs) 345.34 KB (+0.15% 🔺) 7 s (+0.15% 🔺) 642 ms (+6.4% 🔺) 7.6 s
thirdweb (minimal + tree-shaking) 5.7 KB (0%) 114 ms (0%) 95 ms (+1515.53% 🔺) 209 ms
thirdweb/chains (tree-shaking) 531 B (0%) 11 ms (0%) 50 ms (+2697.72% 🔺) 60 ms
thirdweb/react (minimal + tree-shaking) 19.52 KB (0%) 391 ms (0%) 114 ms (+789.64% 🔺) 505 ms

@joaquim-verges joaquim-verges merged commit ad8cc9a into main May 31, 2025
26 of 27 checks passed
@joaquim-verges joaquim-verges deleted the _Bridge_Add_tokens_function_to_retrieve_supported_tokens branch May 31, 2025 09:29
@joaquim-verges joaquim-verges mentioned this pull request May 31, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
packages SDK Involves changes to the thirdweb SDK
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant