forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseWalletBalance.ts
More file actions
75 lines (68 loc) · 1.99 KB
/
Copy pathuseWalletBalance.ts
File metadata and controls
75 lines (68 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { useCallback, useEffect, useState } from "react";
import { useWallet } from "./useWallet";
import { fetchBalance, type Balance } from "../util/wallet";
const formatter = new Intl.NumberFormat();
const checkFunding = (balances: Balance[]) =>
balances.some(({ balance }) =>
!Number.isNaN(Number(balance)) ? Number(balance) > 0 : false,
);
type WalletBalance = {
balances: Balance[];
xlm: string;
isFunded: boolean;
isLoading: boolean;
error: Error | null;
};
export const useWalletBalance = () => {
const { address } = useWallet();
const [state, setState] = useState<WalletBalance>({
balances: [],
xlm: "-",
isFunded: false,
isLoading: false,
error: null,
});
const updateBalance = useCallback(async () => {
if (!address) return;
try {
setState((prev) => ({ ...prev, isLoading: true }));
const response = await fetchBalance(address) as any;
const balancesArray = Array.isArray(response) ? response : (response.balances || []);
const isFunded = checkFunding(balancesArray);
const native = balancesArray.find((b: any) => b.asset_type === "native");
setState({
isLoading: false,
balances: balancesArray,
xlm: native?.balance ? formatter.format(Number(native.balance)) : "-",
isFunded,
error: null,
});
} catch (err) {
if (err instanceof Error && err.message.match(/not found/i)) {
setState({
isLoading: false,
balances: [],
xlm: "-",
isFunded: false,
error: new Error("Error fetching balance. Is your wallet funded?"),
});
} else {
console.error(err);
setState({
isLoading: false,
balances: [],
xlm: "-",
isFunded: false,
error: new Error("Unknown error fetching balance."),
});
}
}
}, [address]);
useEffect(() => {
void updateBalance();
}, [updateBalance]);
return {
...state,
updateBalance,
};
};