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
453 lines (405 loc) · 14.3 KB
/
Copy pathuseNetworkMode.ts
File metadata and controls
453 lines (405 loc) · 14.3 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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import { useCallback, useEffect, useState } from 'react';
import rawFreighterApi from '@stellar/freighter-api';
import {
isMainnetEnabled,
isTestnet,
resolveNetworkMode,
STELLAR_MAINNET_PASSPHRASE,
STELLAR_TESTNET_PASSPHRASE,
} from '../config/networks';
import { resolveViteMainnetRpcUrl, resolveViteSepoliaRpcUrl } from '../config/rpc-urls';
import { checkNetworkMode, type NetworkModeGuard } from '@oversync/sdk';
const freighterApi = (rawFreighterApi as any)?.default ?? rawFreighterApi;
export type NetworkMode = 'testnet' | 'mainnet';
export { STELLAR_MAINNET_PASSPHRASE, STELLAR_TESTNET_PASSPHRASE };
const ETH_MAINNET_CHAIN_ID_HEX = '0x1';
const ETH_SEPOLIA_CHAIN_ID_HEX = '0xaa36a7';
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();
}
export function readRequestedModeFromUrl(): NetworkMode {
if (typeof window === 'undefined') {
return 'testnet';
}
const url = new URLSearchParams(window.location.search).get('network');
if (url === 'mainnet' || url === 'testnet') {
return url;
}
return isTestnet() ? 'testnet' : 'mainnet';
}
function expectedEthChainIdHex(mode: NetworkMode): string {
return mode === 'mainnet' ? ETH_MAINNET_CHAIN_ID_HEX : ETH_SEPOLIA_CHAIN_ID_HEX;
}
export function expectedStellarPassphrase(mode: NetworkMode): string {
return mode === 'mainnet' ? STELLAR_MAINNET_PASSPHRASE : STELLAR_TESTNET_PASSPHRASE;
}
/**
* Extract and normalize a Stellar network passphrase from Freighter API responses.
* Supports { networkPassphrase }, { network }, and string responses.
*/
export function normalizeFreighterPassphrase(info: any): string | null {
if (!info) return null;
if (typeof info === 'object') {
if (typeof info.networkPassphrase === 'string' && info.networkPassphrase.trim()) {
return info.networkPassphrase.trim();
}
if (typeof info.network === 'string') {
const net = info.network.trim().toUpperCase();
if (net === 'PUBLIC' || net === 'MAINNET') {
return STELLAR_MAINNET_PASSPHRASE;
}
if (net === 'TESTNET') {
return STELLAR_TESTNET_PASSPHRASE;
}
return info.network.trim();
}
}
if (typeof info === 'string') {
const trimmed = info.trim();
const upper = trimmed.toUpperCase();
if (upper === 'PUBLIC' || upper === 'MAINNET') {
return STELLAR_MAINNET_PASSPHRASE;
}
if (upper === 'TESTNET') {
return STELLAR_TESTNET_PASSPHRASE;
}
return trimmed;
}
return null;
}
export interface FreighterAgreementResult {
matches: boolean;
actualPassphrase: string | null;
expectedPassphrase: string;
reason?: string;
}
/**
* Compare Freighter's network to the order network mode or expected passphrase.
*/
export function verifyFreighterNetworkAgreement(
freighterInfoOrPassphrase: any,
orderNetworkOrPassphrase: NetworkMode | string,
): FreighterAgreementResult {
const expectedPassphrase =
orderNetworkOrPassphrase === 'mainnet'
? STELLAR_MAINNET_PASSPHRASE
: orderNetworkOrPassphrase === 'testnet'
? STELLAR_TESTNET_PASSPHRASE
: orderNetworkOrPassphrase;
const actualPassphrase = normalizeFreighterPassphrase(freighterInfoOrPassphrase);
if (!actualPassphrase) {
return {
matches: false,
actualPassphrase: null,
expectedPassphrase,
reason: 'Freighter network could not be determined',
};
}
const matches = actualPassphrase.trim().toLowerCase() === expectedPassphrase.trim().toLowerCase();
return {
matches,
actualPassphrase,
expectedPassphrase,
reason: matches
? undefined
: `Freighter network passphrase "${actualPassphrase}" does not match expected order network passphrase "${expectedPassphrase}"`,
};
}
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;
requestedMode: NetworkMode;
guard: NetworkModeGuard;
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 [requestedMode, setRequestedMode] = useState<NetworkMode>(() => readRequestedModeFromUrl());
const [mode, setLocalMode] = useState<NetworkMode>(() => resolveNetworkMode(readRequestedModeFromUrl()));
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 = () => {
const requested = readRequestedModeFromUrl();
setRequestedMode(requested);
setLocalMode(resolveNetworkMode(requested));
};
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());
setRequestedMode('mainnet');
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 =
typeof freighterApi.getNetwork === 'function' ? await freighterApi.getNetwork() : null;
const passphrase = normalizeFreighterPassphrase(info);
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]);
// Re-check after network change events across wallets and app
useEffect(() => {
const handleNetworkChange = () => {
refreshFreighter();
refreshMetamask();
};
window.addEventListener('networkChange', handleNetworkChange);
window.addEventListener('freighter:networkChange', handleNetworkChange);
window.addEventListener('stellar:networkChange', handleNetworkChange);
return () => {
window.removeEventListener('networkChange', handleNetworkChange);
window.removeEventListener('freighter:networkChange', handleNetworkChange);
window.removeEventListener('stellar:networkChange', handleNetworkChange);
};
}, [refreshFreighter, refreshMetamask]);
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();
if (typeof window !== 'undefined') {
window.dispatchEvent(new Event('networkChange'));
}
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) {
setRequestedMode(next);
return { ok: true };
}
if (metamaskConnected) {
const result = await switchMetamaskChain(next);
if (!result.ok) {
return result;
}
}
writeUrlMode(next);
setRequestedMode(next);
setLocalMode(next);
await refreshMetamask();
await refreshFreighter();
if (typeof window !== 'undefined') {
window.dispatchEvent(new Event('networkChange'));
}
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 freighterAgreement = verifyFreighterNetworkAgreement(
freighterNetworkPassphrase,
expectedPassphrase,
);
const freighterMatches = freighterConnected
? freighterAgreement.matches
: true;
const guard = checkNetworkMode(requestedMode, isMainnetEnabled());
return {
mode,
requestedMode,
guard,
expectedEthChainIdHex: expectedChain,
expectedStellarPassphrase: expectedPassphrase,
metamaskChainId,
metamaskConnected,
metamaskMatches,
freighterNetworkPassphrase,
freighterConnected,
freighterMatches,
hasAnyMismatch: !metamaskMatches || !freighterMatches,
setMode,
syncWalletsToAppMode,
refreshWalletNetworks,
};
}