forked from HandCash/external-wallet-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWalletContext.tsx
79 lines (66 loc) · 2.31 KB
/
WalletContext.tsx
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
76
77
78
79
'use client';
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { Types } from '@handcash/handcash-sdk';
interface WalletInfo {
isWalletConnected: boolean;
depositInfo: Types.DepositInfo | undefined;
balances: Types.UserBalance[];
}
interface WalletContextType extends WalletInfo {
refreshBalances: () => Promise<void>;
getAllInfo: () => Promise<void>;
getBSVBalance: () => Types.UserBalance | undefined;
}
const WalletContext = createContext<WalletContextType | undefined>(undefined);
interface WalletProviderProps {
initialWalletInfo: WalletInfo;
refreshBalancesActionName: string;
getAllInfoActionName: string;
children: React.ReactNode;
}
export const WalletProvider: React.FC<WalletProviderProps> = ({
children,
initialWalletInfo,
refreshBalancesActionName,
getAllInfoActionName,
}) => {
const [walletInfo, setWalletInfo] = useState<WalletInfo>(initialWalletInfo);
useEffect(() => {
setWalletInfo(initialWalletInfo);
}, [initialWalletInfo]);
const refreshBalances = useCallback(async () => {
try {
const { getUserBalances } = await import(`@/app/actions/wallet/${refreshBalancesActionName}`);
const newBalances = await getUserBalances();
setWalletInfo(prev => ({ ...prev, balances: newBalances }));
} catch (error) {
console.error('Error refreshing balances:', error);
}
}, [refreshBalancesActionName]);
const getAllInfo = useCallback(async () => {
try {
const { fetchWalletInfo } = await import(`@/app/actions/wallet/${getAllInfoActionName}`);
const newInfo = await fetchWalletInfo();
setWalletInfo(newInfo);
} catch (error) {
console.error('Error fetching all wallet info:', error);
}
}, [getAllInfoActionName]);
const getBSVBalance = useCallback(() => {
return walletInfo.balances.find(balance => balance.currency.code === 'BSV');
}, [walletInfo.balances]);
const value: WalletContextType = {
...walletInfo,
refreshBalances,
getAllInfo,
getBSVBalance,
};
return <WalletContext.Provider value={value}>{children}</WalletContext.Provider>;
};
export const useWallet = () => {
const context = useContext(WalletContext);
if (context === undefined) {
throw new Error('useWallet must be used within a WalletProvider');
}
return context;
};