forked from karagozemin/OverSync
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseNetworkMode.ts
More file actions
325 lines (289 loc) · 10.5 KB
/
useNetworkMode.ts
File metadata and controls
325 lines (289 loc) · 10.5 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import { useCallback, useEffect, useState } from 'react';
import freighterApi from '@stellar/freighter-api';
import { isMainnetEnabled, isTestnet, resolveNetworkMode } from '../config/networks';
import { resolveViteMainnetRpcUrl, resolveViteSepoliaRpcUrl } from '../config/rpc-urls';
export type NetworkMode = 'testnet' | 'mainnet';
const ETH_MAINNET_CHAIN_ID_HEX = '0x1';
const ETH_SEPOLIA_CHAIN_ID_HEX = '0xaa36a7';
const STELLAR_MAINNET_PASSPHRASE = 'Public Global Stellar Network ; September 2015';
const STELLAR_TESTNET_PASSPHRASE = 'Test SDF Network ; September 2015';
const MAINNET_RPC_URL = resolveViteMainnetRpcUrl();
const SEPOLIA_RPC_URL = resolveViteSepoliaRpcUrl();
/** Normalize eth_chainId responses (0xaa36a7 vs 11155111 vs mixed case). */
function normalizeChainId(chainId: string | null): string | null {
if (!chainId) return null;
const trimmed = chainId.trim();
try {
if (trimmed.startsWith('0x') || trimmed.startsWith('0X')) {
return `0x${BigInt(trimmed).toString(16)}`;
}
if (/^\d+$/.test(trimmed)) {
return `0x${BigInt(trimmed).toString(16)}`;
}
} catch {
return trimmed.toLowerCase();
}
return trimmed.toLowerCase();
}
function readModeFromUrl(): NetworkMode {
if (typeof window === 'undefined') {
return 'testnet';
}
const url = new URLSearchParams(window.location.search).get('network');
if (url === 'mainnet' || url === 'testnet') {
return resolveNetworkMode(url);
}
return isTestnet() ? 'testnet' : 'mainnet';
}
function expectedEthChainIdHex(mode: NetworkMode): string {
return mode === 'mainnet' ? ETH_MAINNET_CHAIN_ID_HEX : ETH_SEPOLIA_CHAIN_ID_HEX;
}
function expectedStellarPassphrase(mode: NetworkMode): string {
return mode === 'mainnet' ? STELLAR_MAINNET_PASSPHRASE : STELLAR_TESTNET_PASSPHRASE;
}
function eqHexChainId(a: string | null, b: string): boolean {
const left = normalizeChainId(a);
const right = normalizeChainId(b);
if (!left || !right) return false;
return left === right;
}
export interface NetworkModeState {
mode: NetworkMode;
expectedEthChainIdHex: string;
expectedStellarPassphrase: string;
metamaskChainId: string | null;
metamaskConnected: boolean;
metamaskMatches: boolean;
freighterNetworkPassphrase: string | null;
freighterConnected: boolean;
freighterMatches: boolean;
hasAnyMismatch: boolean;
setMode: (next: NetworkMode) => Promise<{ ok: boolean; reason?: string }>;
/** Ask connected wallets to match the current app mode (even if mode unchanged). */
syncWalletsToAppMode: () => Promise<{ ok: boolean; reason?: string }>;
refreshWalletNetworks: () => void;
}
/**
* Single source of truth for "is the app in testnet or mainnet mode?".
*
* - Reads the chosen mode from the `?network=` URL param (falls back to env).
* - Subscribes to `chainChanged` from MetaMask so manual wallet switches
* are reflected immediately.
* - Polls Freighter once on mount and once every 4s to detect manual
* network switches (Freighter exposes no event API).
* - `setMode` first asks the connected wallets to switch; only once a
* wallet acknowledges (or no wallet is connected) does it update the
* URL. This removes the previous race where the URL could flip while
* one wallet stayed on the wrong chain.
*/
export function useNetworkMode(opts: {
ethAddress?: string;
stellarAddress?: string;
}): NetworkModeState {
const [mode, setLocalMode] = useState<NetworkMode>(() => readModeFromUrl());
const [metamaskChainId, setMetamaskChainId] = useState<string | null>(null);
const [freighterNetworkPassphrase, setFreighterNetworkPassphrase] = useState<string | null>(null);
const metamaskConnected = Boolean(opts.ethAddress);
const freighterConnected = Boolean(opts.stellarAddress);
useEffect(() => {
const handler = () => setLocalMode(readModeFromUrl());
window.addEventListener('popstate', handler);
return () => window.removeEventListener('popstate', handler);
}, []);
// When mainnet is disabled, strip ?network=mainnet from the URL so bookmarks stay on testnet.
useEffect(() => {
if (typeof window === 'undefined' || isMainnetEnabled()) {
return;
}
const url = new URL(window.location.href);
if (url.searchParams.get('network') === 'mainnet') {
url.searchParams.set('network', 'testnet');
window.history.replaceState({}, '', url.toString());
setLocalMode('testnet');
}
}, []);
const refreshMetamask = useCallback(async () => {
if (typeof window === 'undefined' || !window.ethereum) {
setMetamaskChainId(null);
return;
}
try {
const chainId = (await window.ethereum.request({ method: 'eth_chainId' })) as string;
setMetamaskChainId(normalizeChainId(chainId));
} catch {
setMetamaskChainId(null);
}
}, []);
const refreshFreighter = useCallback(async () => {
try {
if (!freighterApi || typeof freighterApi.isConnected !== 'function') {
setFreighterNetworkPassphrase(null);
return;
}
const connectedRaw: any = await freighterApi.isConnected();
const connected =
typeof connectedRaw === 'boolean'
? connectedRaw
: Boolean(connectedRaw?.isConnected);
if (!connected) {
setFreighterNetworkPassphrase(null);
return;
}
const info: any = await freighterApi.getNetwork();
const passphrase =
(info && typeof info === 'object' && info.networkPassphrase) ||
(typeof info === 'string' ? info : null);
setFreighterNetworkPassphrase(passphrase || null);
} catch {
setFreighterNetworkPassphrase(null);
}
}, []);
useEffect(() => {
refreshMetamask();
if (typeof window === 'undefined' || !window.ethereum) {
return;
}
const eth = window.ethereum as any;
const onChainChanged = (next: string) => setMetamaskChainId(normalizeChainId(next));
if (typeof eth.on === 'function') {
eth.on('chainChanged', onChainChanged);
}
return () => {
if (typeof eth.removeListener === 'function') {
eth.removeListener('chainChanged', onChainChanged);
}
};
}, [refreshMetamask]);
// Re-read chain when MetaMask connects; poll while connected (some wallets omit chainChanged).
useEffect(() => {
if (!metamaskConnected) {
return;
}
refreshMetamask();
const id = window.setInterval(refreshMetamask, 4000);
return () => window.clearInterval(id);
}, [metamaskConnected, refreshMetamask]);
useEffect(() => {
refreshFreighter();
const id = window.setInterval(refreshFreighter, 4000);
return () => window.clearInterval(id);
}, [refreshFreighter, freighterConnected]);
const writeUrlMode = (next: NetworkMode) => {
if (typeof window === 'undefined') return;
const url = new URL(window.location.href);
url.searchParams.set('network', next);
window.history.replaceState({}, '', url.toString());
};
const switchMetamaskChain = async (next: NetworkMode): Promise<{ ok: boolean; reason?: string }> => {
if (typeof window === 'undefined' || !window.ethereum) {
return { ok: true };
}
const target = expectedEthChainIdHex(next);
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: target }],
});
return { ok: true };
} catch (err: any) {
if (err?.code === 4902) {
try {
if (next === 'mainnet') {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: target,
chainName: 'Ethereum Mainnet',
rpcUrls: [MAINNET_RPC_URL],
blockExplorerUrls: ['https://etherscan.io'],
nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
},
],
});
} else {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: target,
chainName: 'Sepolia Testnet',
rpcUrls: [SEPOLIA_RPC_URL],
blockExplorerUrls: ['https://sepolia.etherscan.io'],
nativeCurrency: { name: 'Sepolia Ether', symbol: 'ETH', decimals: 18 },
},
],
});
}
return { ok: true };
} catch {
return { ok: false, reason: 'metamask-add-failed' };
}
}
if (err?.code === 4001) {
return { ok: false, reason: 'user-rejected' };
}
return { ok: false, reason: 'metamask-switch-failed' };
}
};
const syncWalletsToAppMode = useCallback(async (): Promise<{ ok: boolean; reason?: string }> => {
if (metamaskConnected) {
const result = await switchMetamaskChain(mode);
if (!result.ok) {
return result;
}
}
await refreshMetamask();
await refreshFreighter();
return { ok: true };
}, [mode, metamaskConnected, refreshMetamask, refreshFreighter]);
const setMode = useCallback(
async (next: NetworkMode): Promise<{ ok: boolean; reason?: string }> => {
if (next === 'mainnet' && !isMainnetEnabled()) {
return { ok: false, reason: 'mainnet-disabled' };
}
if (next === mode) {
return { ok: true };
}
if (metamaskConnected) {
const result = await switchMetamaskChain(next);
if (!result.ok) {
return result;
}
}
writeUrlMode(next);
setLocalMode(next);
await refreshMetamask();
await refreshFreighter();
return { ok: true };
},
[mode, metamaskConnected, refreshMetamask, refreshFreighter],
);
const refreshWalletNetworks = useCallback(() => {
refreshMetamask();
refreshFreighter();
}, [refreshMetamask, refreshFreighter]);
const expectedChain = expectedEthChainIdHex(mode);
const expectedPassphrase = expectedStellarPassphrase(mode);
const metamaskMatches = metamaskConnected
? eqHexChainId(metamaskChainId, expectedChain)
: true;
const freighterMatches = freighterConnected
? freighterNetworkPassphrase === expectedPassphrase
: true;
return {
mode,
expectedEthChainIdHex: expectedChain,
expectedStellarPassphrase: expectedPassphrase,
metamaskChainId,
metamaskConnected,
metamaskMatches,
freighterNetworkPassphrase,
freighterConnected,
freighterMatches,
hasAnyMismatch: !metamaskMatches || !freighterMatches,
setMode,
syncWalletsToAppMode,
refreshWalletNetworks,
};
}