Skip to content

Commit 5ac3867

Browse files
committed
feat: Make useBalance & getBalance return chain-specific unit & decimals even w/o address
1 parent 80d15a6 commit 5ac3867

File tree

2 files changed

+21
-15
lines changed

2 files changed

+21
-15
lines changed

src/helpers/getBalance.ts

+13-7
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,26 @@ import { BN, formatBalance } from '@polkadot/util'
77
*/
88
export const getBalance = async (
99
api: ApiPromise,
10-
address: string | AccountId,
11-
fractionDigits = 2,
10+
address: string | AccountId | undefined,
1211
): Promise<{
13-
freeBalance: BN
14-
reservedBalance: BN
15-
balance: BN
16-
balanceFormatted: string
17-
tokenSymbol: string
1812
tokenDecimals: number
13+
tokenSymbol: string
14+
freeBalance?: BN
15+
reservedBalance?: BN
16+
balance?: BN
17+
balanceFormatted?: string
1918
}> => {
2019
// Get the token decimals and symbol
2120
const tokenDecimals = api.registry.chainDecimals?.[0] || 12
2221
const tokenSymbol = api.registry.chainTokens?.[0] || 'Unit'
2322

23+
if (!address) {
24+
return {
25+
tokenDecimals,
26+
tokenSymbol,
27+
}
28+
}
29+
2430
// Get the balance
2531
const result: any = await api.query.system.account(address)
2632
const freeBalance: BN = new BN(result?.data?.free || 0)

src/hooks/useBalance.ts

+8-8
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,7 @@ import { useEffect, useState } from 'react'
77
/**
88
* Hook that returns the native token balance of the given `address`.
99
*/
10-
export const useBalance = (
11-
address?: string | AccountId,
12-
fractionDigits = 2,
13-
) => {
10+
export const useBalance = (address?: string | AccountId) => {
1411
const { api } = useInkathon()
1512
const [freeBalance, setFreeBalance] = useState<BN>()
1613
const [reservedBalance, setReservedBalance] = useState<BN>()
@@ -21,7 +18,7 @@ export const useBalance = (
2118

2219
useEffect(() => {
2320
;(async () => {
24-
if (!api || !address) {
21+
if (!api) {
2522
setFreeBalance(undefined)
2623
setReservedBalance(undefined)
2724
setBalance(undefined)
@@ -31,16 +28,19 @@ export const useBalance = (
3128
return
3229
}
3330

34-
const result = await getBalance(api, address, fractionDigits)
31+
const result = await getBalance(api, address)
3532

3633
setFreeBalance(result.freeBalance)
3734
setReservedBalance(result.reservedBalance)
3835
setBalance(result.balance)
39-
setBalanceFormatted(`${result.balanceFormatted} ${result.tokenSymbol}`)
36+
setBalanceFormatted(
37+
result.balanceFormatted &&
38+
`${result.balanceFormatted} ${result.tokenSymbol}`,
39+
)
4040
setTokenSymbol(result.tokenSymbol)
4141
setTokenDecimals(result.tokenDecimals)
4242
})()
43-
}, [api, address, fractionDigits])
43+
}, [api, address])
4444

4545
return {
4646
freeBalance,

0 commit comments

Comments
 (0)