Skip to content

Conversation

@MananTank
Copy link
Member

@MananTank MananTank commented Sep 24, 2025


PR-Codex overview

This PR focuses on enhancing the toUnits function in the units.ts file to handle scientific notation for token inputs and adds corresponding tests in units.test.ts.

Detailed summary

  • Updated the toUnits function to convert scientific notation strings to fixed decimal format.
  • Added a test case for the toUnits function to verify handling of negative and positive exponents in scientific notation.

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

Summary by CodeRabbit

  • New Features

    • Unit conversion now accepts scientific notation (positive and negative exponents), normalizing values to the configured decimal precision for consistent fixed-point results.
  • Tests

    • Added tests covering positive and negative exponent cases to validate parsing and conversion of scientific notation.

@changeset-bot
Copy link

changeset-bot bot commented Sep 24, 2025

⚠️ No Changeset found

Latest commit: 8f6363f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@MananTank MananTank marked this pull request as ready for review September 24, 2025 16:02
@MananTank MananTank requested review from a team as code owners September 24, 2025 16:02
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 24, 2025

Walkthrough

Adds parsing support in toUnits for scientific/exponential notation by normalizing inputs containing "e" to a fixed-point string via Number(value).toFixed(decimals). Adds tests covering negative and positive exponents to validate conversion to fixed-point unit strings.

Changes

Cohort / File(s) Summary
Core: toUnits implementation
packages/thirdweb/src/utils/units.ts
Adds a normalization branch for inputs containing scientific/exponential notation ("e"): converts the token via Number(value).toFixed(decimals) before continuing with existing integer/decimal parsing and conversion to units.
Tests: scientific/exponential cases
packages/thirdweb/src/utils/units.test.ts
Adds test cases for negative and positive exponential notation (examples: 1e-18, 1e-16, 1.23456789012345e-7, 1.234e3) to verify correct conversion to fixed-point unit representations.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller
  participant toUnits
  participant Normalizer
  participant Parser

  Caller->>toUnits: toUnits(value, decimals)
  toUnits->>Normalizer: inspect value for "e"
  alt contains "e"
    Note right of Normalizer: normalize exponential notation
    Normalizer->>Normalizer: Number(value) -> toFixed(decimals)
    Note right of Normalizer: fixed-point string (normalized)
  else no "e"
    Normalizer->>Normalizer: keep original token string
  end
  Normalizer-->>Parser: normalized string
  Parser->>Parser: split integer/decimals, pad/truncate, build units string
  Parser-->>Caller: return unit representation
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description leaves the provided template commented out without populating the formatted title or issue tag, and it omits required “Notes for the reviewer” and “How to test” sections, replacing them only with a PR-Codex overview. Please fill out the template by adding the formatted title or issue tag, a “## Notes for the reviewer” section with relevant context, and a “## How to test” section with clear instructions for verifying the change.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title clearly identifies the SDK component and the specific fix for handling scientific notation in the toUnits function, succinctly summarizing the main change.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 09-24-sdk_fix_tounits_throwing_error_for_values_in_scintific_notation

📜 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 2d51cba and 8f6363f.

📒 Files selected for processing (2)
  • packages/thirdweb/src/utils/units.test.ts (1 hunks)
  • packages/thirdweb/src/utils/units.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/thirdweb/src/utils/units.test.ts
🧰 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/utils/units.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/utils/units.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/utils/units.ts
🧠 Learnings (3)
📚 Learning: 2025-06-06T23:47:55.122Z
Learnt from: MananTank
PR: thirdweb-dev/js#7298
File: apps/dashboard/src/app/nebula-app/move-funds/move-funds.tsx:255-277
Timestamp: 2025-06-06T23:47:55.122Z
Learning: The `transfer` function from `thirdweb/extensions/erc20` accepts human-readable amounts via the `amount` property and automatically handles conversion to base units (wei) by fetching the token decimals internally. Manual conversion using `toWei()` is not required when using the `amount` property.

Applied to files:

  • packages/thirdweb/src/utils/units.ts
📚 Learning: 2025-05-20T19:03:35.954Z
Learnt from: MananTank
PR: thirdweb-dev/js#7081
File: apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/assets/create/create-token-page-impl.tsx:160-165
Timestamp: 2025-05-20T19:03:35.954Z
Learning: The `claimTo` function in Thirdweb's ERC20 extension does not require converting the quantity to the smallest units (using toUnits) as it handles unit conversion internally or works with the units as provided.

Applied to files:

  • packages/thirdweb/src/utils/units.ts
📚 Learning: 2025-06-13T21:59:58.910Z
Learnt from: MananTank
PR: thirdweb-dev/js#7332
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/nft/overview/nfts-grid.tsx:347-351
Timestamp: 2025-06-13T21:59:58.910Z
Learning: Intl.NumberFormat.prototype.format supports bigint values in modern JavaScript (ES2020+), so bigint values can be passed directly to formatter.format() without conversion to number.

Applied to files:

  • packages/thirdweb/src/utils/units.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: Build Packages
  • GitHub Check: Size
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Unit Tests
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/thirdweb/src/utils/units.ts (1)

75-78: Avoid Number(...).toFixed for scientific strings.

Parsing via Number(...).toFixed destroys precision for anything beyond IEEE‑754 range, throws when decimals > 100, and ignores uppercase E, so inputs like "1.234567890123456789e-7" or "1E-18" either produce the wrong bigint or blow up. Please normalize scientific notation purely with string math and cover both e/E.

Apply the following diff to replace the current logic:

-  if (tokens.includes("e")) {
-    tokens = Number(tokens).toFixed(decimals);
-  }
+  if (/[eE]/.test(tokens)) {
+    tokens = normalizeScientific(tokens);
+  }

Add this helper near the bottom of the file:

+/** @internal */
+function normalizeScientific(input: string): string {
+  const trimmed = input.trim();
+  const match =
+    /^([+-]?)(\d+(?:\.\d+)?|\.\d+)[eE]([+-]?\d+)$/.exec(trimmed);
+  if (!match) {
+    return input;
+  }
+
+  const [, sign, coefficient, exponentStr] = match;
+  const exponent = Number.parseInt(exponentStr, 10);
+  const [integerPart, fractionalPart = ""] = coefficient.split(".");
+  const digits = `${integerPart}${fractionalPart}`.replace(/^0+(?=\d)/, "") || "0";
+  const decimalIndex = integerPart.length + exponent;
+
+  if (decimalIndex <= 0) {
+    return `${sign}0.${"0".repeat(-decimalIndex)}${digits}`;
+  }
+
+  if (decimalIndex >= digits.length) {
+    return `${sign}${digits}${"0".repeat(decimalIndex - digits.length)}`;
+  }
+
+  return `${sign}${digits.slice(0, decimalIndex)}.${digits.slice(decimalIndex)}`;
+}

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.

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

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

MananTank commented Sep 24, 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.

@vercel
Copy link

vercel bot commented Sep 24, 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 Sep 24, 2025 11:47pm
nebula Ready Ready Preview Comment Sep 24, 2025 11:47pm
thirdweb_playground Ready Ready Preview Comment Sep 24, 2025 11:47pm
thirdweb-www Ready Ready Preview Comment Sep 24, 2025 11:47pm
wallet-ui Ready Ready Preview Comment Sep 24, 2025 11:47pm

@MananTank MananTank changed the title SDK: Fix toUnits throwing error for values in scintific notation SDK: Fix toUnits throwing error for values in scientific notation Sep 24, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/thirdweb/src/utils/units.test.ts (1)

203-214: Great coverage; add cases for uppercase 'E' and negatives.

Add a few more assertions to cover 'E' and negative scientific inputs.

Apply this diff to extend the test:

   it("scientific notation", () => {
     // negative exponents
     expect(toUnits("1e-18", 18)).toMatchInlineSnapshot("1n");
     expect(toUnits("1e-16", 18)).toMatchInlineSnapshot("100n");
     expect(toUnits("1.23456789012345e-7", 18)).toMatchInlineSnapshot(
       "123456789012n",
     );
+    // uppercase 'E' and negatives
+    expect(toUnits("1E-18", 18)).toMatchInlineSnapshot("1n");
+    expect(toUnits("-1e-18", 18)).toMatchInlineSnapshot("-1n");
     // positive exponents
     expect(toUnits("1.234e3", 18)).toMatchInlineSnapshot(
       "1234000000000000000000n",
     );
+    expect(toUnits("1.234E3", 18)).toMatchInlineSnapshot(
+      "1234000000000000000000n",
+    );
   });
📜 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 c26fc67 and e4c378f.

📒 Files selected for processing (2)
  • packages/thirdweb/src/utils/units.test.ts (1 hunks)
  • packages/thirdweb/src/utils/units.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{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/utils/units.test.ts
  • packages/thirdweb/src/utils/units.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/utils/units.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/utils/units.test.ts
  • packages/thirdweb/src/utils/units.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/utils/units.test.ts
  • packages/thirdweb/src/utils/units.ts
🧠 Learnings (3)
📚 Learning: 2025-06-06T23:47:55.122Z
Learnt from: MananTank
PR: thirdweb-dev/js#7298
File: apps/dashboard/src/app/nebula-app/move-funds/move-funds.tsx:255-277
Timestamp: 2025-06-06T23:47:55.122Z
Learning: The `transfer` function from `thirdweb/extensions/erc20` accepts human-readable amounts via the `amount` property and automatically handles conversion to base units (wei) by fetching the token decimals internally. Manual conversion using `toWei()` is not required when using the `amount` property.

Applied to files:

  • packages/thirdweb/src/utils/units.ts
📚 Learning: 2025-05-20T19:03:35.954Z
Learnt from: MananTank
PR: thirdweb-dev/js#7081
File: apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/assets/create/create-token-page-impl.tsx:160-165
Timestamp: 2025-05-20T19:03:35.954Z
Learning: The `claimTo` function in Thirdweb's ERC20 extension does not require converting the quantity to the smallest units (using toUnits) as it handles unit conversion internally or works with the units as provided.

Applied to files:

  • packages/thirdweb/src/utils/units.ts
📚 Learning: 2025-06-13T21:59:58.910Z
Learnt from: MananTank
PR: thirdweb-dev/js#7332
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/nft/overview/nfts-grid.tsx:347-351
Timestamp: 2025-06-13T21:59:58.910Z
Learning: Intl.NumberFormat.prototype.format supports bigint values in modern JavaScript (ES2020+), so bigint values can be passed directly to formatter.format() without conversion to number.

Applied to files:

  • packages/thirdweb/src/utils/units.ts
🧬 Code graph analysis (1)
packages/thirdweb/src/utils/units.test.ts (1)
packages/thirdweb/src/utils/units.ts (1)
  • toUnits (75-120)
⏰ 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, webpack)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Unit Tests
  • GitHub Check: Size
  • GitHub Check: Lint Packages
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript)

Comment on lines +76 to +79
if (tokens.includes("e")) {
tokens = Number(tokens).toFixed(decimals);
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid Number/toFixed for scientific notation; handle 'E' and prevent RangeError (>100 decimals).

Using Number(...).toFixed(decimals) can:

  • Lose precision for large/small magnitudes.
  • Throw RangeError when decimals > 100.
  • Miss inputs using uppercase 'E'.

Recommend parsing scientific notation purely with string ops and supporting both 'e'/'E'.

Apply this diff to replace the current block:

-  if (tokens.includes("e")) {
-    tokens = Number(tokens).toFixed(decimals);
-  }
+  if (/[eE]/.test(tokens)) {
+    tokens = normalizeScientific(tokens);
+  }

Add this helper (non-exported) elsewhere in the file:

// Normalizes scientific notation to a plain decimal string without using Number()
// Preserves sign and avoids precision/RangeError issues.
// @internal
function normalizeScientific(input: string): string {
  const str = input.trim();
  const match = /^([+-]?)(\d+(?:\.\d+)?|\.\d+)[eE]([+-]?\d+)$/.exec(str);
  if (!match) return input;
  const [, sign, coeff, expStr] = match;
  const exp = Number(expStr);

  const [intPart, fracPart = ""] = coeff.split(".");
  const digits = `${intPart}${fracPart}`.replace(/^0+(?=\d)/, "") || "0";
  const originalIndex = intPart.length;
  const newIndex = originalIndex + exp;

  if (newIndex <= 0) {
    return `${sign}0.${"0".repeat(-newIndex)}${digits}`;
  }
  if (newIndex >= digits.length) {
    return `${sign}${digits}${"0".repeat(newIndex - digits.length)}`;
  }
  return `${sign}${digits.slice(0, newIndex)}.${digits.slice(newIndex)}`;
}
🤖 Prompt for AI Agents
In packages/thirdweb/src/utils/units.ts around lines 76 to 79, the current code
uses Number(tokens).toFixed(decimals) which fails for uppercase 'E', can lose
precision and throws RangeError for decimals > 100; replace that block to first
normalize scientific notation via a new non-exported normalizeScientific(input:
string) helper (as provided in the review) that converts any 'e' or 'E'
formatted string into a plain decimal string without using Number(), then use
that normalized string for subsequent processing instead of
Number(...).toFixed(...). Add the normalizeScientific helper elsewhere in this
file (not exported) and ensure the replacement handles sign, preserves digits,
and avoids Number/toFixed entirely.

@github-actions
Copy link
Contributor

github-actions bot commented Sep 24, 2025

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 64.09 KB (+0.04% 🔺) 1.3 s (+0.04% 🔺) 163 ms (+78.52% 🔺) 1.5 s
thirdweb (cjs) 361.63 KB (+0.01% 🔺) 7.3 s (+0.01% 🔺) 805 ms (+7.91% 🔺) 8.1 s
thirdweb (minimal + tree-shaking) 5.73 KB (0%) 115 ms (0%) 37 ms (+774.89% 🔺) 152 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 31 ms (+1582.42% 🔺) 41 ms
thirdweb/react (minimal + tree-shaking) 19.14 KB (0%) 383 ms (0%) 38 ms (+922.81% 🔺) 421 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: 0

🧹 Nitpick comments (1)
packages/thirdweb/src/utils/units.test.ts (1)

203-214: Add coverage for uppercase 'E', explicit '+' exponent, and >100 decimals.

Strengthen the new suite and guard against regressions (current impl throws for decimals > 100):

   it("scientific notation", () => {
     // negative exponents
     expect(toUnits("1e-18", 18)).toMatchInlineSnapshot("1n");
     expect(toUnits("1e-16", 18)).toMatchInlineSnapshot("100n");
     expect(toUnits("1.23456789012345e-7", 18)).toMatchInlineSnapshot(
       "123456789012n",
     );
+    // uppercase E and spaces
+    expect(toUnits("1E-18", 18)).toMatchInlineSnapshot("1n");
+    expect(toUnits("  1e-18  ", 18)).toMatchInlineSnapshot("1n");
     // positive exponents
     expect(toUnits("1.234e3", 18)).toMatchInlineSnapshot(
       "1234000000000000000000n",
     );
+    expect(toUnits("1e+3", 18)).toMatchInlineSnapshot(
+      "1000000000000000000000n",
+    );
+    expect(toUnits("1E+3", 18)).toMatchInlineSnapshot(
+      "1000000000000000000000n",
+    );
+    // >100 decimals (would throw with Number(...).toFixed)
+    expect(toUnits("1e-101", 101)).toMatchInlineSnapshot("1n");
   });
📜 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 e4c378f and 2d51cba.

📒 Files selected for processing (2)
  • packages/thirdweb/src/utils/units.test.ts (1 hunks)
  • packages/thirdweb/src/utils/units.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{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/utils/units.test.ts
  • packages/thirdweb/src/utils/units.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/utils/units.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/utils/units.test.ts
  • packages/thirdweb/src/utils/units.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/utils/units.test.ts
  • packages/thirdweb/src/utils/units.ts
🧠 Learnings (3)
📚 Learning: 2025-05-20T19:03:35.954Z
Learnt from: MananTank
PR: thirdweb-dev/js#7081
File: apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/assets/create/create-token-page-impl.tsx:160-165
Timestamp: 2025-05-20T19:03:35.954Z
Learning: The `claimTo` function in Thirdweb's ERC20 extension does not require converting the quantity to the smallest units (using toUnits) as it handles unit conversion internally or works with the units as provided.

Applied to files:

  • packages/thirdweb/src/utils/units.ts
📚 Learning: 2025-06-06T23:47:55.122Z
Learnt from: MananTank
PR: thirdweb-dev/js#7298
File: apps/dashboard/src/app/nebula-app/move-funds/move-funds.tsx:255-277
Timestamp: 2025-06-06T23:47:55.122Z
Learning: The `transfer` function from `thirdweb/extensions/erc20` accepts human-readable amounts via the `amount` property and automatically handles conversion to base units (wei) by fetching the token decimals internally. Manual conversion using `toWei()` is not required when using the `amount` property.

Applied to files:

  • packages/thirdweb/src/utils/units.ts
📚 Learning: 2025-06-13T21:59:58.910Z
Learnt from: MananTank
PR: thirdweb-dev/js#7332
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/nft/overview/nfts-grid.tsx:347-351
Timestamp: 2025-06-13T21:59:58.910Z
Learning: Intl.NumberFormat.prototype.format supports bigint values in modern JavaScript (ES2020+), so bigint values can be passed directly to formatter.format() without conversion to number.

Applied to files:

  • packages/thirdweb/src/utils/units.ts
🧬 Code graph analysis (1)
packages/thirdweb/src/utils/units.test.ts (1)
packages/thirdweb/src/utils/units.ts (1)
  • toUnits (75-120)
⏰ 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: Unit Tests
  • GitHub Check: Size
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Lint Packages
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/thirdweb/src/utils/units.ts (1)

76-79: Avoid Number/toFixed; handle both 'e'/'E' and prevent precision loss/RangeError.

  • Number(...) loses precision for large/small magnitudes.
  • toFixed throws RangeError when decimals > 100 (ERC‑20 decimals can be up to 255).
  • Only lowercase 'e' is handled; uppercase 'E' is missed.

Replace this block and normalize scientifically-notated inputs via string math:

-  if (tokens.includes("e")) {
-    tokens = Number(tokens).toFixed(decimals);
-  }
+  tokens = tokens.trim();
+  if (/[eE]/.test(tokens)) {
+    tokens = normalizeScientific(tokens);
+  }

Add this helper in the same file (non‑exported):

/**
 * Normalize scientific notation to a plain decimal string without using Number().
 * Preserves sign and avoids precision/RangeError issues.
 * @internal
 */
function normalizeScientific(input: string): string {
  const str = input.trim();
  const match = /^([+-]?)(\d+(?:\.\d+)?|\.\d+)[eE]([+-]?\d+)$/.exec(str);
  if (!match) return input;
  const [, sign, coeff, expStr] = match;
  const exp = Number(expStr);

  const [intPart, fracPart = ""] = coeff.split(".");
  const digits = `${intPart}${fracPart}`.replace(/^0+(?=\d)/, "") || "0";
  const originalIndex = intPart.length;
  const newIndex = originalIndex + exp;

  if (newIndex <= 0) {
    return `${sign}0.${"0".repeat(-newIndex)}${digits}`;
  }
  if (newIndex >= digits.length) {
    return `${sign}${digits}${"0".repeat(newIndex - digits.length)}`;
  }
  return `${sign}${digits.slice(0, newIndex)}.${digits.slice(newIndex)}`;
}

@codecov
Copy link

codecov bot commented Sep 24, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 56.27%. Comparing base (a83104e) to head (8f6363f).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8112      +/-   ##
==========================================
- Coverage   56.28%   56.27%   -0.01%     
==========================================
  Files         906      906              
  Lines       59190    59193       +3     
  Branches     4176     4171       -5     
==========================================
- Hits        33313    33311       -2     
- Misses      25772    25777       +5     
  Partials      105      105              
Flag Coverage Δ
packages 56.27% <100.00%> (-0.01%) ⬇️
Files with missing lines Coverage Δ
packages/thirdweb/src/utils/units.ts 98.36% <100.00%> (+0.08%) ⬆️

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

@graphite-app
Copy link
Contributor

graphite-app bot commented Sep 24, 2025

Merge activity

)

<!--

## title your PR with this format: "[SDK/Dashboard/Portal] Feature/Fix: Concise title for the changes"

If you did not copy the branch name from Linear, paste the issue tag here (format is TEAM-0000):

## Notes for the reviewer

Anything important to call out? Be sure to also clarify these in your comments.

## How to test

Unit tests, playground, etc.

-->

<!-- start pr-codex -->

---

## PR-Codex overview
This PR enhances the `toUnits` function to handle both scientific notation and fixed-point notation, ensuring accurate conversion of token values with specified decimals. It also adds tests to verify the new functionality.

### Detailed summary
- Modified `toUnits` function to check for scientific notation (e.g., "1e-18").
- Converted scientific notation to fixed-point notation using `Number(tokens).toFixed(decimals)`.
- Added tests for `toUnits` to cover various scientific notation cases, including negative and positive exponents.

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

<!-- end pr-codex -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

* **New Features**
  * Unit conversion now accepts scientific notation (positive and negative exponents), normalizing values to the configured decimal precision for consistent fixed-point results.

* **Tests**
  * Added comprehensive tests covering positive and negative exponent cases to validate parsing and conversion from scientific notation.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@graphite-app graphite-app bot force-pushed the 09-24-sdk_fix_tounits_throwing_error_for_values_in_scintific_notation branch from 2d51cba to 8f6363f Compare September 24, 2025 23:07
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.

3 participants