-
Notifications
You must be signed in to change notification settings - Fork 619
SDK: Fix toUnits throwing error for values in scientific notation #8112
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
SDK: Fix toUnits throwing error for values in scientific notation #8112
Conversation
|
WalkthroughAdds 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
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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro Disabled knowledge base sources:
📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
🧰 Additional context used📓 Path-based instructions (3)**/*.{ts,tsx}📄 CodeRabbit inference engine (CLAUDE.md)
Files:
**/*.{ts,tsx,js,jsx}📄 CodeRabbit inference engine (CLAUDE.md)
Files:
packages/thirdweb/**/*.{ts,tsx}📄 CodeRabbit inference engine (AGENTS.md)
Files:
🧠 Learnings (3)📚 Learning: 2025-06-06T23:47:55.122ZApplied to files:
📚 Learning: 2025-05-20T19:03:35.954ZApplied to files:
📚 Learning: 2025-06-13T21:59:58.910ZApplied to files:
⏰ 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)
🔇 Additional comments (1)
Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (1)
Comment |
How to use the Graphite Merge QueueAdd either label to this PR to merge it via the merge queue:
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. |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this 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.
📒 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@/typesor localtypes.tsbarrels
Prefer type aliases over interface except for nominal shapes
Avoidanyandunknownunless 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@/typeswhere applicable
Prefertypealiases overinterfaceexcept for nominal shapes
Avoidanyandunknownunless 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.tspackages/thirdweb/src/utils/units.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.test.{ts,tsx}: Place tests alongside code:foo.ts↔foo.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
UseFORKED_ETHEREUM_CHAINfor mainnet interactions andANVIL_CHAINfor isolated tests
**/*.test.{ts,tsx}: Co‑locate tests asfoo.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.tspackages/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@exampleand 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.tspackages/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)
| if (tokens.includes("e")) { | ||
| tokens = Number(tokens).toFixed(decimals); | ||
| } | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
size-limit report 📦
|
e4c378f to
2d51cba
Compare
There was a problem hiding this 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.
📒 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@/typesor localtypes.tsbarrels
Prefer type aliases over interface except for nominal shapes
Avoidanyandunknownunless 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@/typeswhere applicable
Prefertypealiases overinterfaceexcept for nominal shapes
Avoidanyandunknownunless 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.tspackages/thirdweb/src/utils/units.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.test.{ts,tsx}: Place tests alongside code:foo.ts↔foo.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
UseFORKED_ETHEREUM_CHAINfor mainnet interactions andANVIL_CHAINfor isolated tests
**/*.test.{ts,tsx}: Co‑locate tests asfoo.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.tspackages/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@exampleand 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.tspackages/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 Report✅ All modified and coverable lines are covered by tests. 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
🚀 New features to boost your workflow:
|
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 -->
2d51cba to
8f6363f
Compare

PR-Codex overview
This PR focuses on enhancing the
toUnitsfunction in theunits.tsfile to handle scientific notation for token inputs and adds corresponding tests inunits.test.ts.Detailed summary
toUnitsfunction to convert scientific notation strings to fixed decimal format.toUnitsfunction to verify handling of negative and positive exponents in scientific notation.Summary by CodeRabbit
New Features
Tests