apibara / starknet-react

A collection of React providers and hooks for StarkNet
https://starknet-react.com
MIT License
369 stars 147 forks source link

fix: useBalance rounding issues #408

Closed notV4l closed 8 months ago

notV4l commented 8 months ago

use formatUnits from viem in useBalance

netlify[bot] commented 8 months ago

Deploy Preview for starknet-react ready!

Name Link
Latest commit 2df5559dd5636366eb1fac19215aef1d4ae93823
Latest deploy log https://app.netlify.com/sites/starknet-react/deploys/65ef68c54dece800087dd2de
Deploy Preview https://deploy-preview-408--starknet-react.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

fracek commented 8 months ago

Thank you for this. I believe this is also the wrong approach, but it can be fixed! Let's add a formatBalance(amount: bigint, decimals: bigint): string helper that does the following (roughly).

Notice you can convert to its decimal form by working directly with the number digits, without loss of precision. I added spaces to make it easier to follow.

2500 00000 00000 00000 00000 00000 <- original bigint

2500 00000 00.000 00000 00000 00000 <- add a '.' to make it into a decimal

2500 00000 00 <- remove decimal digits and '.' since all zero

You also need to consider if the number is less than 1 (need to add extra 0s before .) and less than 0 (need to take into account the sign).

notV4l commented 8 months ago

Yes we just need this formatUnit I can't believe we don't have formatEther / formatUnits / etc helpers in sn libs 😢

fracek commented 8 months ago

Yep. I'm happy if you copy-paste that function for now as long as you copy the viem copyright notice as a comment before it.