Skip to content

Commit

Permalink
Format an amount for dApp
Browse files Browse the repository at this point in the history
We should correctly display user balances. Let us use the formatting functions and display the balance correctly by region.
  • Loading branch information
kkosiorowska committed Nov 17, 2023
1 parent 65ab5ab commit 0b6c887
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
5 changes: 4 additions & 1 deletion dapp/src/components/Navbar/ConnectWallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
useRequestEthereumAccount,
} from "../../hooks"
import { LedgerLiveAppContext } from "../../contexts/LedgerLiveAppContext"
import { formatSatoshiAmount } from "../../utils"

export type ConnectButtonsProps = {
leftIcon: string
Expand Down Expand Up @@ -46,7 +47,9 @@ export default function ConnectWallet() {
<Box display="flex" gap="2">
<Text>Balance</Text>
<Text as="b">
{!btcAccount ? "0.00" : btcAccount.balance.toString()}
{!btcAccount || btcAccount?.balance.isZero()
? "0.00"
: formatSatoshiAmount(btcAccount.balance.toString())}
</Text>
<Text>{BITCOIN.token}</Text>
</Box>
Expand Down
1 change: 1 addition & 0 deletions dapp/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./numbers"
26 changes: 26 additions & 0 deletions dapp/src/utils/numbers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const toLocaleString = (value: number): string =>
value.toLocaleString("default", { maximumFractionDigits: 2 })

// Parse token amount by moving the decimal point
export function bigIntToUserAmount(
amount: bigint,
decimals = 18,
desiredDecimals = 2,
): string {
const desiredDecimalsAmount =
amount / 10n ** BigInt(Math.max(1, decimals - desiredDecimals))

return toLocaleString(
Number(desiredDecimalsAmount) / 10 ** Math.min(desiredDecimals, decimals),
)
}
export const formatTokenAmount = (
amount: number | string,
decimals = 18,
desiredDecimals = 2,
) => bigIntToUserAmount(BigInt(amount), decimals, desiredDecimals)

export const formatSatoshiAmount = (
amount: number | string,
desiredDecimals = 2,
) => formatTokenAmount(amount, 8, desiredDecimals)

0 comments on commit 0b6c887

Please sign in to comment.