Skip to content

Conversation

@jnsdls
Copy link
Member

@jnsdls jnsdls commented Oct 16, 2025

TL;DR

Added functionality to fetch native currency metadata from the chain API when not available locally.

What changed?

Enhanced the getCurrencyMetadata function to fetch native currency information from the chain API when the local chain definition doesn't include native currency details. This ensures that even for chains without predefined native currency information, the system can still retrieve the correct metadata instead of defaulting to "Ether".

How to test?

  1. Test with a chain that doesn't have native currency defined in the local chain definition
  2. Verify that the function correctly fetches the native currency metadata from the chain API
  3. Confirm that it gracefully falls back to default values if the API request fails

Why make this change?

Some chains may not have their native currency information defined in the local chain definitions. This change improves the reliability of currency metadata retrieval by attempting to fetch this information from the chain API when needed, providing more accurate currency information across a wider range of chains.

Summary by CodeRabbit

  • Bug Fixes

    • Standardized native currency defaults (name, symbol, decimals) and added a fallback to fetch chain metadata when native currency info is missing, ensuring consistent currency display across networks.
  • Tests

    • Added tests validating native-token metadata handling and partial chain definitions.
    • Marked several flaky integration tests as skipped (annotated with FIXME) to stabilize CI.
  • Chores

    • Added a release metadata entry marking a patch update.

PR-Codex overview

This PR focuses on improving the handling of native currency metadata in the thirdweb library and temporarily skipping failing tests to stabilize the codebase.

Detailed summary

  • Added a mechanism to fetch native currency metadata from the chain API if not defined.
  • Marked several tests as skipped due to consistent failures.
  • Introduced new tests for validating native token behavior.
  • Updated the getCurrencyMetadata function to utilize the new fetching logic.

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

@vercel
Copy link

vercel bot commented Oct 16, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
docs-v2 Ready Ready Preview Comment Oct 16, 2025 7:14pm
nebula Ready Ready Preview Comment Oct 16, 2025 7:14pm
thirdweb_playground Ready Ready Preview Comment Oct 16, 2025 7:14pm
thirdweb-www Error Error Oct 16, 2025 7:14pm
wallet-ui Ready Ready Preview Comment Oct 16, 2025 7:14pm

@changeset-bot
Copy link

changeset-bot bot commented Oct 16, 2025

🦋 Changeset detected

Latest commit: b7eb23e

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

This PR includes changesets to release 4 packages
Name Type
thirdweb Patch
@thirdweb-dev/nebula Patch
@thirdweb-dev/wagmi-adapter Patch
wagmi-inapp 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

@github-actions github-actions bot added packages SDK Involves changes to the thirdweb SDK labels Oct 16, 2025
@jnsdls jnsdls marked this pull request as ready for review October 16, 2025 17:05
@jnsdls jnsdls requested review from a team as code owners October 16, 2025 17:05
Copy link
Member Author

jnsdls commented Oct 16, 2025


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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 16, 2025

Walkthrough

Adds a changeset entry; enhances getCurrencyMetadata to validate native currency with a zod schema, dynamically fetch chain metadata when chain.nativeCurrency is missing (falling back to defaults on failure), and exports a new GetCurrencyMetadataResult type. Also adds tests for native metadata and marks several flaky tests as skipped.

Changes

Cohort / File(s) Summary
Release metadata
​.changeset/forty-donuts-happen.md
Adds a changeset entry documenting a patch for the thirdweb package and noting behavior to fetch native currency from the chain API if needed.
Native currency metadata resolution
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
Adds a zod schema (NATIVE_CURRENCY_SCHEMA) for native currency, parses chain.nativeCurrency with it, dynamically imports and calls getChainMetadata when chain.nativeCurrency is missing, falls back to default native currency on fetch failure, preserves non-native token logic, and exports GetCurrencyMetadataResult type.
getCurrencyMetadata tests (added)
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.test.ts
Adds tests verifying native-token metadata resolution using a manually defined chain and handling of partial chain definitions where only some nativeCurrency fields are provided.
Skipped / flaky tests
packages/thirdweb/src/extensions/erc7702/account/sessionkey.test.ts, packages/thirdweb/src/wallets/in-app/web/lib/in-app-integration.test.ts, packages/thirdweb/src/wallets/smart/smart-wallet-integration-v07.test.ts, packages/thirdweb/src/wallets/smart/smart-wallet-integration.test.ts
Several previously active tests were changed to skipped (it.skip) and annotated with FIXME comments to disable flaky/failing tests while keeping them in the codebase.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant getCurrencyMetadata
    participant ChainDef as "Chain Definition"
    participant ChainAPI as "getChainMetadata"
    participant Response

    Caller->>getCurrencyMetadata: Request token metadata (address, chain, options)
    getCurrencyMetadata->>ChainDef: Is address native? check chain.nativeCurrency
    alt chain.nativeCurrency exists
        ChainDef-->>getCurrencyMetadata: Return nativeCurrency
        getCurrencyMetadata->>Response: Parse via NATIVE_CURRENCY_SCHEMA -> return
    else chain.nativeCurrency missing
        rect rgb(235,245,255)
            note right of getCurrencyMetadata: Dynamic import + fetch chain metadata
            getCurrencyMetadata->>ChainAPI: getChainMetadata(chainId)
            alt fetch succeeds
                ChainAPI-->>getCurrencyMetadata: Return chain metadata (includes nativeCurrency)
                getCurrencyMetadata->>Response: Parse chain.nativeCurrency via schema -> return
            else fetch fails
                ChainAPI-->>getCurrencyMetadata: Error
                getCurrencyMetadata->>Response: Use default native currency (Ether, ETH, 18)
            end
        end
    end
    Response-->>Caller: Final metadata (apply option overrides)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The pull request description diverges from the repository template by omitting the required formatted PR title header, the branch or issue tag section, and a “Notes for the reviewer” section. It uses custom headings like “TL;DR” and “What changed?” instead of the prescribed structure and does not include the template’s comment block or exact “## How to test” heading level. These omissions and non-standard headings indicate the template has not been followed. Please update the description to follow the repository template by adding the formatted PR title line, branch or issue tag, and a dedicated “Notes for the reviewer” section, and adjust the headings to match the exact template structure. Ensure the “How to test” section uses the prescribed heading and integrate any TL;DR content within the template layout.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title clearly and concisely summarizes the primary enhancement of the pull request, which is fetching native currency metadata from the chain API when it is not defined locally. It directly refers to the main change without extraneous details or vague language. The phrasing is specific enough for a reviewer skimming the history to understand the key update. Therefore, it meets the repository’s title guidelines.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch Fetch_native_currency_from_chain_API_when_required

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 16, 2025

Walkthrough

A patch release adds fallback logic to fetch native currency metadata from a chain API when predefined chain definitions lack this information, with a changeset documenting the update.

Changes

Cohort / File(s) Summary
Changeset
\.changeset/forty-donuts-happen\.md
Documents patch release for thirdweb package to fetch native currency from chain API if required
Native Currency Metadata
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata\.ts
Added import of getChainMetadata and implemented fallback logic: when contract address is native and chain lacks nativeCurrency, attempts to fetch metadata via chain API before falling back to default (decimals: 18, name: "Ether")

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant getCurrencyMetadata
    participant getChainMetadata
    participant API

    Caller->>getCurrencyMetadata: getCurrencyMetadata(address, options)
    
    alt address is native
        getCurrencyMetadata->>getCurrencyMetadata: check if chain.nativeCurrency exists
        
        alt nativeCurrency defined
            getCurrencyMetadata-->>Caller: return predefined metadata
        else nativeCurrency not defined
            getCurrencyMetadata->>getChainMetadata: fetch chain metadata
            getChainMetadata->>API: query chain data
            
            alt API call succeeds
                API-->>getChainMetadata: return chain data
                getChainMetadata-->>getCurrencyMetadata: return nativeCurrency
                getCurrencyMetadata-->>Caller: return fetched metadata
            else API call fails
                API-->>getChainMetadata: error
                getChainMetadata-->>getCurrencyMetadata: fallback
                getCurrencyMetadata-->>Caller: return default (18 decimals, "Ether")
            end
        end
    else address is not native
        getCurrencyMetadata-->>Caller: return standard ERC20 metadata
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description does not adhere to the repository’s required template because it omits the commented template header with title and issue tag instructions and lacks a dedicated "## Notes for the reviewer" section despite including a "How to test" section. Without these sections, reviewers may miss important context or guidance. The existing TL;DR, What changed?, and Why make this change? headings do not match the prescribed template structure. Please include the commented template header at the top of the description, add the Linear issue tag or branch name in the designated section, and insert a "## Notes for the reviewer" section above the "## How to test" section to match the required PR description format.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly reflects the primary change by indicating that the PR adds the ability to fetch native currency from the chain API as needed, accurately summarizing the main enhancement without extraneous information.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch Fetch_native_currency_from_chain_API_when_required

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c934102 and f5ec5f2.

📒 Files selected for processing (2)
  • .changeset/forty-donuts-happen.md (1 hunks)
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
.changeset/*.md

📄 CodeRabbit inference engine (AGENTS.md)

.changeset/*.md: Each change in packages/* must include a changeset for the appropriate package
Version bump rules: patch for non‑API changes; minor for new/modified public API

Files:

  • .changeset/forty-donuts-happen.md
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose

**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
packages/thirdweb/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

packages/thirdweb/**/*.{ts,tsx}: Every public symbol must have comprehensive TSDoc with at least one compiling @example and a custom tag (@beta, @internal, @experimental, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Lazy‑load heavy dependencies inside async paths (e.g., const { jsPDF } = await import("jspdf"))

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Size
  • GitHub Check: Unit Tests
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Lint Packages
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
.changeset/forty-donuts-happen.md (1)

1-5: LGTM!

The changeset correctly documents a patch-level release for an internal enhancement that doesn't modify the public API.

packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (2)

1-1: LGTM!

The import is correctly added to support the new fallback logic.


34-43: No change needed—getChainMetadata guarantees a complete nativeCurrency. ChainMetadata.nativeCurrency is non-optional with required name, symbol, and decimals, so the defaults fallback isn’t necessary.


Comment @coderabbitai help to get the list of available commands and usage tips.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (1)

17-28: Update TSDoc to document API fallback behavior.

Per coding guidelines: "Every public symbol must have comprehensive TSDoc." The function description should mention the new fallback behavior where chain metadata is fetched from the API when chain.nativeCurrency is unavailable.

Based on coding guidelines

Apply this diff to update the documentation:

 /**
- * Retrieves the metadata of a currency.
+ * Retrieves the metadata of a currency. For native tokens, attempts to fetch
+ * chain metadata from the API if the chain definition lacks native currency information.
  * @param options - The options for the transaction.
  * @returns A promise that resolves to an object containing the currency metadata.
  * @extension ERC20
🧹 Nitpick comments (2)
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (2)

1-1: Consider lazy loading the import.

Per coding guidelines: "Load heavy dependencies inside async paths to keep initial bundle lean." If getChainMetadata involves significant dependencies or network calls, consider lazy-importing it within the conditional block.

Example refactor if lazy loading is beneficial:

-import { getChainMetadata } from "../../../chains/utils.js";
 import { isNativeTokenAddress } from "../../../constants/addresses.js";

Then inside the function:

     if (!options.contract.chain.nativeCurrency) {
       try {
+        const { getChainMetadata } = await import("../../../chains/utils.js");
         const chain = await getChainMetadata(options.contract.chain);

36-42: Consider adding observability for API failures.

The catch block silently swallows errors, which aids graceful degradation but may hide legitimate issues (network failures, API changes, etc.). Consider adding structured logging to track when the API fallback is used and when it fails.

Example:

       } catch {
         // no-op, fall through to the default values below
+        // Optional: Add logging if observability framework is available
+        // console.debug("Failed to fetch chain metadata, using defaults");
       }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c934102 and f5ec5f2.

📒 Files selected for processing (2)
  • .changeset/forty-donuts-happen.md (1 hunks)
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
.changeset/*.md

📄 CodeRabbit inference engine (AGENTS.md)

.changeset/*.md: Each change in packages/* must include a changeset for the appropriate package
Version bump rules: patch for non‑API changes; minor for new/modified public API

Files:

  • .changeset/forty-donuts-happen.md
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose

**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
packages/thirdweb/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

packages/thirdweb/**/*.{ts,tsx}: Every public symbol must have comprehensive TSDoc with at least one compiling @example and a custom tag (@beta, @internal, @experimental, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Lazy‑load heavy dependencies inside async paths (e.g., const { jsPDF } = await import("jspdf"))

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Size
  • GitHub Check: Unit Tests
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Lint Packages
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
.changeset/forty-donuts-happen.md (1)

1-5: LGTM! Correct patch bump for behavioral change.

The changeset correctly identifies this as a patch bump since the change modifies internal behavior without altering the public API signature.

packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (1)

37-39: Type compatibility verified. ChainMetadata.nativeCurrency has { name: string; symbol: string; decimals: number }, matching GetCurrencyMetadataResult exactly.

@github-actions
Copy link
Contributor

github-actions bot commented Oct 16, 2025

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 64.51 KB (0%) 1.3 s (0%) 360 ms (+151.42% 🔺) 1.7 s
thirdweb (cjs) 365.68 KB (0%) 7.4 s (0%) 1.4 s (+9.33% 🔺) 8.7 s
thirdweb (minimal + tree-shaking) 5.73 KB (0%) 115 ms (0%) 170 ms (+2289.44% 🔺) 285 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 150 ms (+3928.7% 🔺) 161 ms
thirdweb/react (minimal + tree-shaking) 19.13 KB (0%) 383 ms (0%) 134 ms (+2111.61% 🔺) 516 ms

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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e939be5 and 380408e.

📒 Files selected for processing (2)
  • .changeset/forty-donuts-happen.md (1 hunks)
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/forty-donuts-happen.md
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose

**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
packages/thirdweb/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

packages/thirdweb/**/*.{ts,tsx}: Every public symbol must have comprehensive TSDoc with at least one compiling @example and a custom tag (@beta, @internal, @experimental, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Lazy‑load heavy dependencies inside async paths (e.g., const { jsPDF } = await import("jspdf"))

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Size
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Build Packages
  • GitHub Check: Lint Packages
  • GitHub Check: Unit Tests
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (2)

1-1: LGTM!

The Zod import is correctly added to support schema validation for native currency metadata.


8-12: Schema structure is correct.

The native currency schema with default values is well-defined and aligns with the PR objectives. The field-level defaults will be applied when an object is provided but individual fields are missing.

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

🧹 Nitpick comments (2)
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (2)

46-58: Good implementation; consider adding observability.

The logic correctly implements the graceful fallback behavior:

  1. Attempts to fetch from API when native currency is missing
  2. Falls back to default values on failure
  3. The schema's .default() ensures safe parsing of undefined

This implementation addresses the previous review concerns about early returns and undefined parsing.

Recommended improvement: Add error logging in the catch block for better debugging and observability:

     } catch {
       // no-op, fall through to the default values below
     }
+    } catch (error) {
+      // Log the error for debugging but fall through to defaults
+      if (process.env.NODE_ENV === 'development') {
+        console.warn('Failed to fetch native currency from API:', error);
+      }
+    }

Optional improvement: Update the TSDoc to mention the new API fetch behavior:

 /**
  * Retrieves the metadata of a currency.
+ * For native tokens, attempts to fetch metadata from the chain API if not available in local definitions.
  * @param options - The options for the transaction.
  * @returns A promise that resolves to an object containing the currency metadata.

1-1: Replace default zod import with named import
Use import { z } from "zod"; instead of import z from "zod" to align with the majority of the codebase.

-import z from "zod";
+import { z } from "zod";
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 380408e and 88c9939.

📒 Files selected for processing (2)
  • .changeset/forty-donuts-happen.md (1 hunks)
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/forty-donuts-happen.md
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose

**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
packages/thirdweb/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

packages/thirdweb/**/*.{ts,tsx}: Every public symbol must have comprehensive TSDoc with at least one compiling @example and a custom tag (@beta, @internal, @experimental, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Lazy‑load heavy dependencies inside async paths (e.g., const { jsPDF } = await import("jspdf"))

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
🧠 Learnings (1)
📚 Learning: 2025-06-26T19:46:04.024Z
Learnt from: gregfromstl
PR: thirdweb-dev/js#7450
File: packages/thirdweb/src/bridge/Webhook.ts:57-81
Timestamp: 2025-06-26T19:46:04.024Z
Learning: In the onramp webhook schema (`packages/thirdweb/src/bridge/Webhook.ts`), the `currencyAmount` field is intentionally typed as `z.number()` while other amount fields use `z.string()` because `currencyAmount` represents fiat currency amounts in decimals (like $10.50), whereas other amount fields represent token amounts in wei (very large integers that benefit from bigint representation). The different naming convention (`currencyAmount` vs `amount`) reflects this intentional distinction.

Applied to files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Size
  • GitHub Check: Unit Tests
  • GitHub Check: Build Packages
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (1)

8-18: LGTM! Schema design correctly addresses previous concerns.

The dual-default pattern is well-designed:

  • Field-level defaults (lines 10-12) apply when an object is passed with missing fields
  • Schema-level default (lines 14-18) handles the case when undefined is parsed

This addresses the previous review concern about parsing undefined throwing an error. The schema-level .default() ensures graceful fallback to default values.

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

🧹 Nitpick comments (3)
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (3)

8-18: Handle both null and undefined for graceful fallback.

The schema's .default() only applies when the value is strictly undefined. If chain.nativeCurrency or the API response is explicitly null, parsing will throw instead of falling back to defaults. This breaks the graceful fallback behavior described in the PR objectives.

Apply this diff to handle both null and undefined:

 const NATIVE_CURRENCY_SCHEMA = z
   .object({
     name: z.string().default("Ether"),
     symbol: z.string().default("ETH"),
     decimals: z.number().default(18),
   })
+  .nullish()
   .default({
     name: "Ether",
     symbol: "ETH",
     decimals: 18,
   });

With .nullish(), the schema will treat both null and undefined the same way and apply the default values, ensuring truly graceful fallback.


8-18: Consider extracting default values to avoid duplication.

The default values ("Ether", "ETH", 18) are specified twice: once at the field level and once at the schema level. While this is functionally correct, extracting them into a constant would reduce duplication and improve maintainability.

Here's an optional refactor to eliminate duplication:

+const DEFAULT_NATIVE_CURRENCY = {
+  name: "Ether",
+  symbol: "ETH",
+  decimals: 18,
+};
+
 const NATIVE_CURRENCY_SCHEMA = z
   .object({
-    name: z.string().default("Ether"),
-    symbol: z.string().default("ETH"),
-    decimals: z.number().default(18),
+    name: z.string().default(DEFAULT_NATIVE_CURRENCY.name),
+    symbol: z.string().default(DEFAULT_NATIVE_CURRENCY.symbol),
+    decimals: z.number().default(DEFAULT_NATIVE_CURRENCY.decimals),
   })
-  .default({
-    name: "Ether",
-    symbol: "ETH",
-    decimals: 18,
-  });
+  .default(DEFAULT_NATIVE_CURRENCY);

53-55: Consider logging errors in the catch block for debugging.

The empty catch block silently suppresses errors from the API fetch. While the graceful fallback is correct, logging these errors (e.g., to console.warn or a telemetry service) would help with debugging in production when the API is failing or returning unexpected data.

Optional enhancement:

     } catch (error) {
-      // no-op, fall through to the default values below
+      // API fetch failed, fall through to the default values below
+      // In production, consider logging: console.warn("Failed to fetch native currency from API", error);
     }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 88c9939 and f4b4803.

📒 Files selected for processing (2)
  • .changeset/forty-donuts-happen.md (1 hunks)
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .changeset/forty-donuts-happen.md
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose

**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
packages/thirdweb/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

packages/thirdweb/**/*.{ts,tsx}: Every public symbol must have comprehensive TSDoc with at least one compiling @example and a custom tag (@beta, @internal, @experimental, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Lazy‑load heavy dependencies inside async paths (e.g., const { jsPDF } = await import("jspdf"))

Files:

  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Size
  • GitHub Check: Unit Tests
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Lint Packages
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (1)

46-58: Excellent use of dynamic imports and graceful fallback.

The implementation correctly:

  • Lazy-loads getChainMetadata only when needed, reducing initial bundle size (per coding guidelines)
  • Falls back to defaults when the API fetch fails
  • Uses the zod schema to ensure type safety and provide defaults

The logic flow handles the key scenarios appropriately:

  1. When nativeCurrency is missing locally → fetch from API
  2. When API fetch fails → fall through to parse local definition with defaults
  3. When nativeCurrency exists locally → parse and validate it

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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f4b4803 and b7eb23e.

📒 Files selected for processing (7)
  • .changeset/forty-donuts-happen.md (1 hunks)
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.test.ts (2 hunks)
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (2 hunks)
  • packages/thirdweb/src/extensions/erc7702/account/sessionkey.test.ts (2 hunks)
  • packages/thirdweb/src/wallets/in-app/web/lib/in-app-integration.test.ts (1 hunks)
  • packages/thirdweb/src/wallets/smart/smart-wallet-integration-v07.test.ts (1 hunks)
  • packages/thirdweb/src/wallets/smart/smart-wallet-integration.test.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/thirdweb/src/wallets/smart/smart-wallet-integration.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • .changeset/forty-donuts-happen.md
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose

**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size

Files:

  • packages/thirdweb/src/extensions/erc7702/account/sessionkey.test.ts
  • packages/thirdweb/src/wallets/smart/smart-wallet-integration-v07.test.ts
  • packages/thirdweb/src/wallets/in-app/web/lib/in-app-integration.test.ts
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.test.ts
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.{ts,tsx}: Place tests alongside code: foo.tsfoo.test.ts
Use real function invocations with stub data in tests; avoid brittle mocks
Use Mock Service Worker (MSW) for fetch/HTTP call interception in tests
Keep tests deterministic and side-effect free
Use FORKED_ETHEREUM_CHAIN for mainnet interactions and ANVIL_CHAIN for isolated tests

**/*.test.{ts,tsx}: Co‑locate tests as foo.test.ts(x) next to the implementation
Use real function invocations with stub data; avoid brittle mocks
Use MSW to intercept HTTP calls for network interactions; mock only hard‑to‑reproduce scenarios
Keep tests deterministic and side‑effect free; use Vitest

Files:

  • packages/thirdweb/src/extensions/erc7702/account/sessionkey.test.ts
  • packages/thirdweb/src/wallets/smart/smart-wallet-integration-v07.test.ts
  • packages/thirdweb/src/wallets/in-app/web/lib/in-app-integration.test.ts
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

Files:

  • packages/thirdweb/src/extensions/erc7702/account/sessionkey.test.ts
  • packages/thirdweb/src/wallets/smart/smart-wallet-integration-v07.test.ts
  • packages/thirdweb/src/wallets/in-app/web/lib/in-app-integration.test.ts
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.test.ts
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
packages/thirdweb/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

packages/thirdweb/**/*.{ts,tsx}: Every public symbol must have comprehensive TSDoc with at least one compiling @example and a custom tag (@beta, @internal, @experimental, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Lazy‑load heavy dependencies inside async paths (e.g., const { jsPDF } = await import("jspdf"))

Files:

  • packages/thirdweb/src/extensions/erc7702/account/sessionkey.test.ts
  • packages/thirdweb/src/wallets/smart/smart-wallet-integration-v07.test.ts
  • packages/thirdweb/src/wallets/in-app/web/lib/in-app-integration.test.ts
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.test.ts
  • packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts
packages/thirdweb/src/wallets/**

📄 CodeRabbit inference engine (CLAUDE.md)

packages/thirdweb/src/wallets/**: Unified Wallet and Account interfaces in wallet architecture
Support for in-app wallets (social/email login)
Smart wallets with account abstraction
EIP-1193, EIP-5792, EIP-7702 standard support in wallet modules

Files:

  • packages/thirdweb/src/wallets/smart/smart-wallet-integration-v07.test.ts
  • packages/thirdweb/src/wallets/in-app/web/lib/in-app-integration.test.ts
🧠 Learnings (1)
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to test/src/test-wallets.ts : Predefined test accounts are in `test/src/test-wallets.ts`

Applied to files:

  • packages/thirdweb/src/wallets/in-app/web/lib/in-app-integration.test.ts
🧬 Code graph analysis (1)
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.test.ts (1)
packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (1)
  • getCurrencyMetadata (41-84)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Size
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Unit Tests
  • GitHub Check: Lint Packages
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (8)
packages/thirdweb/src/wallets/smart/smart-wallet-integration-v07.test.ts (1)

304-305: LGTM - Appropriate handling of flaky test.

Marking the consistently failing parallel transaction test as skipped is a reasonable approach while the root cause is investigated. The FIXME comment ensures this is tracked for resolution.

packages/thirdweb/src/wallets/in-app/web/lib/in-app-integration.test.ts (1)

44-45: LGTM - Consistent approach to flaky tests.

Disabling the failing sponsor-gas test follows the same pattern applied across other test files in this PR. The FIXME comment appropriately flags this for future attention.

packages/thirdweb/src/extensions/erc7702/account/sessionkey.test.ts (1)

63-64: LGTM - Consistent handling of failing tests.

Both session key tests are appropriately marked as skipped with FIXME comments, maintaining code for future resolution while preventing CI failures.

Also applies to: 82-83

packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts (3)

8-18: LGTM - Well-structured schema with proper defaults.

The zod schema correctly handles both undefined input (via object-level default) and partial objects (via field-level defaults), ensuring graceful fallback behavior.


53-64: LGTM - Appropriate lazy loading and merge strategy.

The dynamic import keeps the bundle lean, and the merge order correctly prioritizes local overrides over API-fetched values. The silent catch is acceptable here since it falls through to schema defaults.


66-66: LGTM - Correct fallback behavior.

The schema parse at this line correctly applies defaults when nativeCurrency is undefined or partial, thanks to the object-level and field-level defaults defined in NATIVE_CURRENCY_SCHEMA.

packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.test.ts (2)

25-38: Consider mocking the API call for determinism.

This test calls getChainMetadata internally, which likely hits an external API. If the API is unavailable or returns different data in the future, the test becomes flaky—a pattern already evident in other tests being skipped in this PR.

Per coding guidelines: "Use MSW to intercept HTTP calls for network interactions" and "Keep tests deterministic and side-effect free." Consider mocking the API response to ensure test stability.

As per coding guidelines


40-58: Good coverage of partial override behavior, but same API dependency.

This test effectively validates the merge logic where local partial data takes precedence over API-fetched values. However, it shares the same external API dependency concern as the previous test.

Consider mocking for consistency with the deterministic testing principle.

As per coding guidelines

Comment on lines +47 to +52
if (
!options.contract.chain.nativeCurrency ||
!options.contract.chain.nativeCurrency.name ||
!options.contract.chain.nativeCurrency.symbol ||
!options.contract.chain.nativeCurrency.decimals
) {
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 16, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Potential edge case: Zero decimals incorrectly triggers API fetch.

The condition !options.contract.chain.nativeCurrency.decimals evaluates to true for both undefined and 0. While most tokens have non-zero decimals, ERC20 technically allows 0 decimals. If a chain's native currency legitimately has 0 decimals and it's specified in the chain definition, this condition would incorrectly attempt to fetch from the API.

Consider using explicit undefined checks:

 if (
   !options.contract.chain.nativeCurrency ||
-  !options.contract.chain.nativeCurrency.name ||
-  !options.contract.chain.nativeCurrency.symbol ||
-  !options.contract.chain.nativeCurrency.decimals
+  options.contract.chain.nativeCurrency.name === undefined ||
+  options.contract.chain.nativeCurrency.symbol === undefined ||
+  options.contract.chain.nativeCurrency.decimals === undefined
 )
📝 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
if (
!options.contract.chain.nativeCurrency ||
!options.contract.chain.nativeCurrency.name ||
!options.contract.chain.nativeCurrency.symbol ||
!options.contract.chain.nativeCurrency.decimals
) {
if (
!options.contract.chain.nativeCurrency ||
options.contract.chain.nativeCurrency.name === undefined ||
options.contract.chain.nativeCurrency.symbol === undefined ||
options.contract.chain.nativeCurrency.decimals === undefined
) {
🤖 Prompt for AI Agents
In packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts around
lines 47 to 52, the current falsy checks treat 0 decimals as missing and will
trigger an unnecessary API fetch; change the condition to check decimals
explicitly (e.g., options.contract.chain.nativeCurrency.decimals === undefined)
while keeping the existing checks for name and symbol (or similarly use explicit
undefined/null checks if desired) so that a legitimate 0 value for decimals is
accepted and no API call is made.

Copy link
Member Author

Choose a reason for hiding this comment

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

zero decimal can never happen, if we see that we SHOULD fetch

Copy link
Contributor

Choose a reason for hiding this comment

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

@jnsdls, thank you for the clarification! I understand now that zero decimals is not a valid value for native currency in this system, and encountering it should indeed trigger a fetch from the API. The current implementation is correct for your use case.

ʕ •ᴥ•ʔ 📚


✏️ Learnings added
Learnt from: jnsdls
PR: thirdweb-dev/js#8267
File: packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts:47-52
Timestamp: 2025-10-16T19:00:34.682Z
Learning: In the thirdweb SDK's getCurrencyMetadata function (packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts), zero decimals is not a valid value for native currency. If `options.contract.chain.nativeCurrency.decimals` is 0, it should be treated as missing/invalid data and trigger an API fetch to get the correct native currency metadata.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@codecov
Copy link

codecov bot commented Oct 16, 2025

Codecov Report

❌ Patch coverage is 93.10345% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 54.89%. Comparing base (2779afc) to head (b7eb23e).
⚠️ Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
...b/src/extensions/erc20/read/getCurrencyMetadata.ts 93.10% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8267      +/-   ##
==========================================
- Coverage   55.01%   54.89%   -0.13%     
==========================================
  Files         919      919              
  Lines       60588    60613      +25     
  Branches     4126     4115      -11     
==========================================
- Hits        33334    33273      -61     
- Misses      27150    27239      +89     
+ Partials      104      101       -3     
Flag Coverage Δ
packages 54.89% <93.10%> (-0.13%) ⬇️
Files with missing lines Coverage Δ
...b/src/extensions/erc20/read/getCurrencyMetadata.ts 96.22% <93.10%> (-3.78%) ⬇️

... and 8 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.

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.

2 participants