Skip to content

fix(trade): use the exact base-unit balance for percent and auto-adju… - #851

Open
furkan3152 wants to merge 1 commit into
nansen-ai:mainfrom
furkan3152:fix/exact-balance-amounts
Open

furkan3152 wants to merge 1 commit into
nansen-ai:mainfrom
furkan3152:fix/exact-balance-amounts

Conversation

@furkan3152

Copy link
Copy Markdown

Summary

resolvePercentAmount and validateBalance read the sell-token balance as a JavaScript number (Number(raw) / 10 ** decimals) and turn that number back into the amount the quote is requested for. Most 18-decimal balances, and 9-decimal SPL balances above about 9M tokens, do not fit in a float, so the quoted amount is off:

Balance (base units) Command Amount quoted on main With this PR
1234567891234567891 (18 dec) --amount 100 --amount-unit percent 1234567891234568000 (109 more than the wallet holds) 1234567891234567891
2718281828459045235 (18 dec) --amount 100 --amount-unit percent 2718281828459045500 (265 more) 2718281828459045235
987654321987654321 (18 dec) --amount 100 --amount-unit percent 987654321987654200 (121 left as dust) 987654321987654321
987654321987654321 (18 dec) --amount 0.987654321987654321 --amount-unit token 987654321987654200, after "Warning: Amount 0.987654321987654321 exceeds balance 0.9876543219876542. Auto-adjusting to 0.9876543219876542" 987654321987654321, no warning
123456789123456789 (SPL, 9 dec) --amount 100 --amount-unit percent 123456789123456790 (1 more) 123456789123456789
500000000000 (18 dec) --amount 100 --amount-unit percent rejected with Invalid amount: "5e-7" 0.0000005

The Base rows were measured by running trade quote with the RPC and quote endpoints mocked and reading the amount sent to /quote; the SPL row comes from the unit test. A quote for more than the balance fails when the swap is executed.

The two functions now keep the balance in base units (BigInt):

  • The percentage is applied exactly, so 100% is the whole balance and other percentages round down to a base unit.
  • The 2% auto-adjust and 95% fee-buffer checks compare base units, so the documented boundaries (≤2%, ≥95%) now hold exactly.
  • The result is a plain decimal string for convertToBaseUnits().

Error and warning messages keep their wording and now show the exact balance. fetchNativeBalance and fetchTokenBalance still return numbers (validateGasBalance uses the native one) and now wrap the base-unit reads. formatBaseUnits is local because importing formatAmount from transfer.js would create an import cycle.

New tests in trade-validation.test.js cover the rows above. On main they fail with the values in the table, for example expected '1.234567891234568' to be '1.234567891234567891' and expected '5e-7' to be '0.0000005'.

Checklist

  • Tests pass (npm test)
  • src/schema.json updated if new commands or flags were added (none added)
  • README.md updated if new top-level commands or categories were added (none added)
  • Changeset added (.changeset/exact-balance-amounts.md)

npm run lint: no errors.

npm test:

 Test Files  129 passed (129)
      Tests  6309 passed | 16 skipped (6325)
   Start at  01:04:02
   Duration  334.23s (transform 5.77s, setup 1.27s, import 19.88s, tests 781.95s, environment 13ms)

…sted amounts

resolvePercentAmount and validateBalance read the sell-token balance as a
JavaScript number and turned it back into the quoted amount. Most 18-decimal
balances, and large 9-decimal SPL balances, do not fit in a float, so 100%
could quote more than the wallet holds or leave dust, an amount equal to the
balance was reported as exceeding it, and a small balance became "5e-7".

Keep the balance in base units (BigInt) for these checks, apply the
percentage exactly and format the result as a plain decimal string.
@nansen-pr-reviewer

Copy link
Copy Markdown

nansen-pr-reviewer summary

The change moves balance comparisons and percentage calculations to base-unit BigInt arithmetic, preserving exact token amounts and avoiding scientific notation. Raw balance fetching, native gas reserves, formatting, and the new edge cases are covered by mocked unit tests, and the user-facing fix includes a changeset. No correctness or security issues were identified.

Deterministic check: success — No issues found

Risk: 2/5 (Low)

✅ Auto-approved — Deterministic gates passed: severity thresholds met, recommendation "approve", risk level 2/5 within threshold 3.


Token usage: 156,087 input, 1,957 output, 95,019 cache read | Usage Guide

Cooldown: for the next 10 minutes (counting from when this review finished), new pushes to this PR will not trigger another review — the next push after the window expires will. Need a fresh review sooner? Comment @nansen-pr-reviewer[bot] re-review.

@nansen-pr-reviewer nansen-pr-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Auto-approved by Nansen review

Deterministic gates passed: severity thresholds met, recommendation "approve", risk level 2/5 within threshold 3.

  • The deterministic severity check passed: No issues found
  • Risk level 2/5 (Low)
  • The model recommended: approve

Approval was decided by deterministic gates, not by the model. The model's recommendation can block auto-approval but never cause it.

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.

1 participant