Skip to content

refactor: migrate from jsbi for currency#7391

Open
limitofzero wants to merge 10 commits into
developfrom
feat/migration-from-jsbi-1
Open

refactor: migrate from jsbi for currency#7391
limitofzero wants to merge 10 commits into
developfrom
feat/migration-from-jsbi-1

Conversation

@limitofzero
Copy link
Copy Markdown
Contributor

@limitofzero limitofzero commented Apr 22, 2026

Summary

Migrate currency lib from jsbi. It's a first pr with replacing jsbi operations by native bigint.

To Test

Need some regress due to this refactor. Check rates and token rounding (it should works as before).

Summary by CodeRabbit

  • Refactor

    • Switched internal big-integer handling to native JavaScript bigint and updated numeric/decimal utilities and type support.
  • Tests

    • Expanded and updated tests for arithmetic, fraction, currency and cross-type compatibility using native bigint.
  • New Features

    • Added localized recovery banner strings informing users the service is back online.

@vercel
Copy link
Copy Markdown

vercel Bot commented Apr 22, 2026

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

Project Deployment Actions Updated (UTC)
cowfi Ready Ready Preview May 7, 2026 11:27am
explorer-dev Ready Ready Preview May 7, 2026 11:27am
storybook Error Error May 7, 2026 11:27am
swap-dev Ready Ready Preview May 7, 2026 11:27am
widget-configurator Ready Ready Preview May 7, 2026 11:27am
2 Skipped Deployments
Project Deployment Actions Updated (UTC)
cosmos Ignored Ignored May 7, 2026 11:27am
sdk-tools Ignored Ignored Preview May 7, 2026 11:27am

Request Review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 22, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: f0bf8aa2-a2e7-4543-825e-fcd77b7ca23c

📥 Commits

Reviewing files that changed from the base of the PR and between a778e19 and b0cc401.

📒 Files selected for processing (3)
  • apps/cowswap-frontend/src/locales/en-US.po
  • apps/cowswap-frontend/src/utils/orderUtils/calculateAmountForRate.test.ts
  • libs/common-utils/src/rawToTokenAmount.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/cowswap-frontend/src/locales/en-US.po

Walkthrough

This PR migrates code from the JSBI library to native JavaScript bigint across core fraction/currency classes, utilities, tests, and some frontend modules; it also broadens a type to accept bigint and updates one utility function signature.

Changes

Cohort / File(s) Summary
Core Fraction & Currency Classes
libs/currency/src/entities/fractions/fraction.ts, libs/currency/src/entities/fractions/currencyAmount.ts, libs/currency/src/entities/fractions/price.ts, libs/currency/src/entities/fractions/percent.ts
Replaces JSBI with native bigint for storage and arithmetic. Fraction now uses bigint numerator/denominator; arithmetic/comparison methods use native operators. CurrencyAmount.decimalScale switches to bigint and validation compares against MAX_UINT256 via native bigint.
Type Definition
libs/currency/src/entities/constants.ts
Expands exported BigintIsh to include native bigint (was `JSBI
Common Utilities
libs/common-utils/src/fractionUtils.ts, libs/common-utils/src/maxAmountSpend.ts, libs/common-utils/src/rawToTokenAmount.ts, libs/common-utils/src/amountFormat/index.ts
Removes jsbi import and converts math to native bigint. rawToTokenAmount signature updated to accept/return bigint. Rounding, exponentiation, GCD/reduction, and comparisons now use native operators.
Tests (updated & expanded)
libs/currency/src/entities/fractions/fraction.test.ts, libs/currency/src/entities/fractions/currencyAmount.test.ts, libs/common-utils/src/fractionUtils.test.ts
All tests migrated to assert native bigint literals; added coverage for input-type compatibility (bigint/JSBI/string/number) and additional arithmetic/edge-case scenarios (max-uint256, overflow, operations).
Frontend utilities/hooks
apps/cowswap-frontend/src/legacy/hooks/useCombinedBalance.ts, apps/cowswap-frontend/src/legacy/state/orders/utils.ts, apps/cowswap-frontend/src/utils/orderUtils/calculateExecutionPrice.ts, apps/cowswap-frontend/src/utils/orderUtils/calculateAmountForRate.test.ts
Replaces JSBI usage with native bigint in balance accumulation, denominator underflow guards, decimal-adjustment logic, and related tests.
i18n
apps/cowswap-frontend/src/locales/en-US.po
Adds new recovery/incident notice strings for a RecoveryBanner component.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through JSBI fields at dawn,

swapped tiny crates for one big lawn.
Now numbers wear an n so bright,
and operators dance through the night.
Hop on — native bigints make it right! 🥕✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is incomplete and does not follow the provided template structure. It lacks required sections like issue reference, concrete testing steps, background context, and is largely generic. Add the missing template sections: reference the issue number, provide concrete testing steps specific to the migration (e.g., which rates/rounding to verify), add any relevant background, and include screenshots if applicable.
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: migrating currency-related code from jsbi library to native bigint operations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/migration-from-jsbi-1

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

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

@cloudflare-workers-and-pages
Copy link
Copy Markdown

cloudflare-workers-and-pages Bot commented Apr 28, 2026

Deploying swap-dev with  Cloudflare Pages  Cloudflare Pages

Latest commit: 49f93ea
Status:🚫  Build failed.

View logs

@limitofzero
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 28, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@libs/common-utils/src/rawToTokenAmount.ts`:
- Around line 1-2: Change rawToTokenAmount to accept value: bigint | string
instead of number and return bigint; inside the function, detect typeof value—if
bigint, use it directly; if string, validate it is an integer numeric string (no
decimal point or non-digit chars) and convert with BigInt(value), otherwise
throw a clear error; multiply the resulting BigInt by 10n **
BigInt(tokenDecimals) as before; update any callers that pass numbers to provide
bigint or numeric strings to preserve integer precision.

In `@libs/currency/src/entities/fractions/fraction.ts`:
- Around line 8-13: The toBigInt helper currently accepts numbers which allows
callers to pass unsafe IEEE-754 values; update the toBigInt function to reject
number inputs (throw a clear error advising to pass a string or bigint) instead
of converting them, so amount-backed types (Fraction, CurrencyAmount, Percent,
Price) only accept exact representations; keep handling for bigint, string, and
JSBI-like objects (use value.toString() for the latter) and ensure the thrown
message references this requirement.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 1eeeaa69-8358-4cc7-9e21-72f498d949c4

📥 Commits

Reviewing files that changed from the base of the PR and between aca2898 and a778e19.

📒 Files selected for processing (15)
  • apps/cowswap-frontend/src/legacy/hooks/useCombinedBalance.ts
  • apps/cowswap-frontend/src/legacy/state/orders/utils.ts
  • apps/cowswap-frontend/src/utils/orderUtils/calculateExecutionPrice.ts
  • libs/common-utils/src/amountFormat/index.ts
  • libs/common-utils/src/fractionUtils.test.ts
  • libs/common-utils/src/fractionUtils.ts
  • libs/common-utils/src/maxAmountSpend.ts
  • libs/common-utils/src/rawToTokenAmount.ts
  • libs/currency/src/entities/constants.ts
  • libs/currency/src/entities/fractions/currencyAmount.test.ts
  • libs/currency/src/entities/fractions/currencyAmount.ts
  • libs/currency/src/entities/fractions/fraction.test.ts
  • libs/currency/src/entities/fractions/fraction.ts
  • libs/currency/src/entities/fractions/percent.ts
  • libs/currency/src/entities/fractions/price.ts

Comment thread libs/common-utils/src/rawToTokenAmount.ts Outdated
Comment thread libs/currency/src/entities/fractions/fraction.ts
Copy link
Copy Markdown
Contributor

@kernelwhisperer kernelwhisperer left a comment

Choose a reason for hiding this comment

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

I get typecheck errors:

daniel in cowswap on  feat/migration-from-jsbi-1 [$] via ⬢ v22.22.1 
➜ pnpm exec tsc --noEmit -p libs/common-utils/tsconfig.lib.json
libs/common-utils/src/calculateSlippageAmount.ts:9:11 - error TS2322: Type 'bigint' is not assignable to type 'JSBI'.

9   return [value.multiply(ONE_FRACTION.subtract(slippage)).quotient, value.multiply(ONE_FRACTION.add(slippage)).quotient]
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

libs/common-utils/src/calculateSlippageAmount.ts:9:69 - error TS2322: Type 'bigint' is not assignable to type 'JSBI'.

9   return [value.multiply(ONE_FRACTION.subtract(slippage)).quotient, value.multiply(ONE_FRACTION.add(slippage)).quotient]
                                                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

libs/common-utils/src/formatCurrencyAmount.ts:18:18 - error TS2345: Argument of type 'bigint' is not assignable to parameter of type 'JSBI'.

18   if (JSBI.equal(amount.quotient, JSBI.BigInt(0))) {
                    ~~~~~~~~~~~~~~~


Found 3 errors in 2 files.

Errors  Files
     2  libs/common-utils/src/calculateSlippageAmount.ts:9
     1  libs/common-utils/src/formatCurrencyAmount.ts:18

if (typeof value === 'bigint') return value
if (typeof value === 'number') return BigInt(value)
if (typeof value === 'string') return BigInt(value)
// JSBI instance
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is this comment needed?


// exports for external consumption
export type BigintIsh = JSBI | string | number
export type BigintIsh = JSBI | bigint | string | number
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Will we be able to remove JSBI from here?

Copy link
Copy Markdown
Collaborator

@shoom3301 shoom3301 left a comment

Choose a reason for hiding this comment

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

Awesome! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants