-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathWalletContext.tsx
More file actions
190 lines (169 loc) · 6.65 KB
/
Copy pathWalletContext.tsx
File metadata and controls
190 lines (169 loc) · 6.65 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import { createContext, useContext, useState, useEffect, useRef, ReactNode } from 'react';
import { isAllowed, setAllowed, requestAccess, getAddress, getNetworkDetails } from '@stellar/freighter-api';
import { fetchUsdcBalance } from '../utils/horizon';
import { logger } from '../utils/logger';
export type WalletNetwork = 'TESTNET' | 'PUBLIC';
export type BalanceStatus = 'idle' | 'loading' | 'success' | 'no_trustline' | 'error';
interface WalletContextType {
address: string | null;
network: WalletNetwork | null;
balance: string | null;
balanceStatus: BalanceStatus;
balanceError: string | null;
isConnecting: boolean;
error: string | null;
connect: () => Promise<void>;
disconnect: () => void;
checkConnection: () => Promise<void>;
}
const WalletContext = createContext<WalletContextType | undefined>(undefined);
/** Polling interval in milliseconds. Override in tests via module augmentation or dependency injection. */
export const BALANCE_REFRESH_INTERVAL = 30_000;
export function WalletProvider({ children }: { children: ReactNode }) {
const [address, setAddress] = useState<string | null>(null);
const [network, setNetwork] = useState<WalletNetwork | null>(null);
const [balance, setBalance] = useState<string | null>(null);
const [balanceStatus, setBalanceStatus] = useState<BalanceStatus>('idle');
const [balanceError, setBalanceError] = useState<string | null>(null);
const [isConnecting, setIsConnecting] = useState(false);
const [error, setError] = useState<string | null>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const normalizeNetwork = (networkName: string): WalletNetwork => {
return networkName === 'PUBLIC' ? 'PUBLIC' : 'TESTNET';
};
const fetchNetworkAndBalance = async (pubKey: string) => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
abortControllerRef.current = new AbortController();
setBalanceStatus('loading');
setBalanceError(null);
try {
const netDetails = await getNetworkDetails();
const activeNetwork = normalizeNetwork(netDetails.network);
setNetwork(activeNetwork);
const usdcBalance = await fetchUsdcBalance(pubKey, activeNetwork, fetch, {
signal: abortControllerRef.current.signal,
});
setBalance(usdcBalance.balance);
setBalanceStatus(usdcBalance.hasTrustline ? 'success' : 'no_trustline');
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') {
return;
}
logger.error('Failed to get network details', err);
const message = err instanceof Error ? err.message : 'Unable to load USDC balance.';
setBalance(null);
setBalanceStatus('error');
setBalanceError(message);
}
};
const checkConnection = async () => {
try {
if (await isAllowed()) {
const { address: pubKey, error: addrError } = await getAddress();
if (pubKey && !addrError) {
setAddress(pubKey);
await fetchNetworkAndBalance(pubKey);
}
}
} catch (err) {
logger.error('Check connection error', err);
}
};
useEffect(() => {
checkConnection();
return () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
};
}, []);
// ── Balance auto-refresh ──────────────────────────────────────────────────
// Polls the balance at a configurable interval; pauses when the tab is
// hidden to avoid wasted Horizon calls. Never overlaps in-flight requests
// (fetchNetworkAndBalance already cancels the previous one via AbortController).
// No polling when disconnected (address is null).
useEffect(() => {
if (!address) return;
const tick = () => {
if (!document.hidden) {
fetchNetworkAndBalance(address);
}
};
const id = setInterval(tick, BALANCE_REFRESH_INTERVAL);
const onVisibilityChange = () => {
if (!document.hidden && address) {
fetchNetworkAndBalance(address);
}
};
document.addEventListener('visibilitychange', onVisibilityChange);
return () => {
clearInterval(id);
document.removeEventListener('visibilitychange', onVisibilityChange);
};
}, [address]);
const connect = async () => {
setIsConnecting(true);
setError(null);
try {
// Prompt user to allow access
await setAllowed();
const access = await requestAccess();
if (access) {
const { address: pubKey, error: addrError } = await getAddress();
if (pubKey && !addrError) {
setAddress(pubKey);
await fetchNetworkAndBalance(pubKey);
} else {
setError(addrError || 'Failed to get wallet address.');
}
} else {
setError('Wallet access denied.');
}
} catch (err: unknown) {
logger.error('Connection error', err);
const message = err instanceof Error ? err.message : undefined;
setError(message || 'Failed to connect wallet. Make sure Freighter is installed and unlocked.');
} finally {
setIsConnecting(false);
}
};
const disconnect = () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
setAddress(null);
setNetwork(null);
setBalance(null);
setBalanceStatus('idle');
setBalanceError(null);
lastKnownAddressRef.current = null;
lastKnownNetworkRef.current = null;
};
return (
<WalletContext.Provider
value={{
address,
network,
balance,
balanceStatus,
balanceError,
isConnecting,
error,
connect,
disconnect,
checkConnection,
}}
>
{children}
</WalletContext.Provider>
);
}
export function useWallet() {
const context = useContext(WalletContext);
if (context === undefined) {
throw new Error('useWallet must be used within a WalletProvider');
}
return context;
}