Skip to content

fix: format custom token balances with token decimals#604

Merged
Agilulfo1820 merged 3 commits intovechain:mainfrom
Emilvooo:fix/custom-token-balance-decimals
Mar 13, 2026
Merged

fix: format custom token balances with token decimals#604
Agilulfo1820 merged 3 commits intovechain:mainfrom
Emilvooo:fix/custom-token-balance-decimals

Conversation

@Emilvooo
Copy link
Copy Markdown
Contributor

@Emilvooo Emilvooo commented Mar 12, 2026

Summary

formatTokenBalance used formatEther (hardcoded 18 decimals) to scale raw on-chain balances. Custom tokens with non-18 decimals displayed incorrect amounts in the asset list (e.g. a 9-decimal token with 979 tokens showed as 0).

Changes

  • Replace formatEther(balance) with formatUnits(balance, decimals) in formatTokenBalance, defaulting to 18
  • Pass Number(token.decimals) from useGetCustomTokenBalances when formatting custom token balances

Backward compatibility

  • decimals parameter defaults to 18, so all existing callers (B3TR, VOT3, veDelegate, SASS) are unaffected
  • Only custom tokens with non-18 decimals see a behavioral change (from broken to correct)

Summary by CodeRabbit

  • Bug Fixes
    • Token balances now display correctly using each token's actual decimal precision, fixing incorrect balance rounding.
  • New Features
    • Improved handling for tokens with custom decimal settings so values are scaled and presented more accurately.
  • Chores
    • Added stricter address validation to reduce failed or unnecessary balance lookups.

@github-actions
Copy link
Copy Markdown

👋 Thanks for your contribution!

Since this PR comes from a forked repository, the lint and build will only run for internal PRs for security reasons.
Please ensure that your PR is coming from a meaningful branch name. Eg. feature/my-feature not main

      **Next steps:**
      1. A maintainer will review your code
      2. If approved, they'll add the `safe-to-build` label to trigger build and test
      3. **After each new commit**, the maintainer will need to remove and re-add the label for security

Thank you for your patience! 🙏

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 12, 2026

Warning

Rate limit exceeded

@Emilvooo has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 13 minutes and 48 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: af675242-eb97-43f7-b60b-f5781d107549

📥 Commits

Reviewing files that changed from the base of the PR and between 591cb9d and b8a7ff8.

📒 Files selected for processing (1)
  • packages/vechain-kit/src/hooks/api/wallet/useGetCustomTokenBalances.ts
📝 Walkthrough

Walkthrough

Updated token balance formatting to support arbitrary token decimals: formatTokenBalance now accepts an optional decimals parameter and uses formatUnits; the custom token balance hook passes token decimals and adds address validation checks.

Changes

Cohort / File(s) Summary
Token Balance Formatting
packages/vechain-kit/src/utils/formattingUtils.tsx
Replaced formatEther with formatUnits; formatTokenBalance(balance: bigint, decimals: number = 18) added decimals param; return now includes scaled and formatted in addition to original.
Custom Token Balance Hook
packages/vechain-kit/src/hooks/api/wallet/useGetCustomTokenBalances.ts
Query key/signature extended to include decimals; hook passes Number(token.decimals) to formatTokenBalance; added isValidAddress checks to enabled condition; minor import reformatting.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

safe-to-build

Suggested reviewers

  • Agilulfo1820

Poem

🐰 I nibbled decimals, small and neat,
I swapped formatEther for units sweet,
Now balances scale and show their face,
Precision hops into the place. ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: fixing custom token balance formatting to correctly handle token decimals instead of hardcoding 18 decimals.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

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

Copy link
Copy Markdown

@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: 3

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

Inline comments:
In `@packages/vechain-kit/src/hooks/api/wallet/useGetCustomTokenBalances.ts`:
- Around line 40-43: The query cache key for useGetCustomTokenBalances must
include token.decimals because formatTokenBalance(tokenBalanceOriginal[0],
Number(token.decimals)) depends on it; update the key that currently uses
token.address and address to also include token.decimals so React Query will
refetch/segregate cached results when decimals change (locate the
useQuery/useGetCustomTokenBalances call and adjust its key tuple to include
token.decimals alongside token.address and address).
- Around line 26-35: In useGetCustomTokenBalances, validate addresses with
isValidAddress() before calling getErc20Balance and stop queries from running on
invalid inputs by adding an enabled flag to each query entry (pattern used in
useIpfsMetadatas); update the queryKey returned by getCustomTokenBalanceQueryKey
to include token.decimals because formatTokenBalance/scaled depends on it;
specifically ensure each mapped query uses enabled: !!address &&
isValidAddress(address) && !!token.address && isValidAddress(token.address) &&
!!network.nodeUrl and that the queryFn still calls
getErc20Balance(token.address, address, { networkUrl: network.nodeUrl }) and
then formats with formatTokenBalance(balance, token.decimals).

In `@packages/vechain-kit/src/utils/formattingUtils.tsx`:
- Around line 95-96: formatTokenBalance currently forwards a potentially
NaN/invalid decimals value to formatUnits causing runtime errors; inside
formatTokenBalance normalize and validate the decimals parameter (e.g., coerce
to a finite number via Number(...) or Number.isFinite check, default to 18 when
invalid, and Math.trunc/clamp to a non-negative integer) before calling
formatUnits so only a safe integer decimals is passed to formatUnits.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4a39adea-d665-4bf6-abac-14c316a47d1a

📥 Commits

Reviewing files that changed from the base of the PR and between 40d9973 and e980f3f.

📒 Files selected for processing (2)
  • packages/vechain-kit/src/hooks/api/wallet/useGetCustomTokenBalances.ts
  • packages/vechain-kit/src/utils/formattingUtils.tsx

Comment thread packages/vechain-kit/src/utils/formattingUtils.tsx Outdated
Copy link
Copy Markdown

@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

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

Inline comments:
In `@packages/vechain-kit/src/hooks/api/wallet/useGetCustomTokenBalances.ts`:
- Around line 13-17: getCustomTokenBalanceQueryKey currently uses decimals as-is
which can become NaN when token.decimals is undefined, causing unstable cache
keys; update the function (and the similar key helper around lines 25-29) to
normalize decimals to a stable value (e.g., use a fallback like 0 or null and/or
coerce with Number(decimals ?? 0)) so the returned array always contains a
consistent primitive and avoids NaN-based inequality (refer to
getCustomTokenBalanceQueryKey to locate and change the key composition).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ec78bd6a-f0f9-4d46-9aaa-e286943ea63a

📥 Commits

Reviewing files that changed from the base of the PR and between e980f3f and 591cb9d.

📒 Files selected for processing (2)
  • packages/vechain-kit/src/hooks/api/wallet/useGetCustomTokenBalances.ts
  • packages/vechain-kit/src/utils/formattingUtils.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/vechain-kit/src/utils/formattingUtils.tsx

Comment thread packages/vechain-kit/src/hooks/api/wallet/useGetCustomTokenBalances.ts Outdated
@Agilulfo1820 Agilulfo1820 merged commit 330b2b8 into vechain:main Mar 13, 2026
7 checks passed
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.

2 participants