forked from FlowwStar/FlowStar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwallet-provider.tsx
More file actions
470 lines (408 loc) · 15.4 KB
/
Copy pathwallet-provider.tsx
File metadata and controls
470 lines (408 loc) · 15.4 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import { setSignTransaction } from "@/lib/contract";
import { type NetworkName, getNetworkConfig } from "@/lib/stellar";
import { setSentryUser } from "@/lib/sentry";
import { useNetwork } from "./network-provider";
// ─── Wallet SDK Interfaces ───────────────────────────────────────────────────
export interface FreighterApi {
isConnected(): Promise<{ isConnected: boolean }>;
getAddress(): Promise<{ address: string; error?: string }>;
requestAccess(): Promise<void>;
signTransaction(xdr: string, opts: { networkPassphrase: string }): Promise<{ signedTxXdr: string; error?: string }>;
getNetwork(): Promise<{ network?: string; error?: string }>;
}
export interface XBullApi {
connect(): Promise<{ publicKey: string }>;
signXDR(xdr: string, opts: { networkPassphrase: string }): Promise<{ signedXDR: string }>;
}
export interface LobstrApi {
getPublicKey(): Promise<{ publicKey: string }>;
signTransaction(xdr: string, opts: { networkPassphrase: string }): Promise<{ signedXdr: string }>;
}
// ─── Window wallet SDK type augmentation ─────────────────────────────────────
declare global {
interface Window {
freighter?: FreighterApi;
xBullSDK?: XBullApi;
lobstrSDK?: LobstrApi;
}
}
// ─── Wallet options ───────────────────────────────────────────────────────────
export interface WalletOption {
id: string;
name: string;
detail: string;
}
export const WALLET_OPTIONS: WalletOption[] = [
{
id: "freighter",
name: "Freighter",
detail: "Browser extension · stellar.org",
},
{ id: "xbull", name: "xBull", detail: "Extension & web" },
{ id: "lobstr", name: "LOBSTR", detail: "Mobile & extension" },
{ id: "albedo", name: "Albedo", detail: "Web signer" },
];
// ─── Wallet adapter interface ─────────────────────────────────────────────────
export interface WalletAdapter {
connect(): Promise<string>;
signTransaction(xdr: string, networkPassphrase: string): Promise<string>;
isAvailable(): boolean;
}
// ─── Freighter adapter ────────────────────────────────────────────────────────
const freighterAdapter: WalletAdapter = {
isAvailable: () =>
typeof window !== "undefined" && !!window.freighter,
async connect() {
const { isConnected, getAddress, requestAccess } =
await import("@stellar/freighter-api");
const { isConnected: connected } = await isConnected();
if (!connected)
throw new Error(
"Freighter is not installed. Install the extension and refresh.",
);
await requestAccess();
const result = await getAddress();
if (result.error) throw new Error(result.error);
return result.address;
},
async signTransaction(xdr, networkPassphrase) {
const { signTransaction } = await import("@stellar/freighter-api");
const result = await signTransaction(xdr, { networkPassphrase });
if (result.error) throw new Error(result.error);
return result.signedTxXdr;
},
};
// ─── xBull adapter ────────────────────────────────────────────────────────────
const xbullAdapter: WalletAdapter = {
isAvailable: () =>
typeof window !== "undefined" && !!window.xBullSDK,
async connect() {
const sdk = window.xBullSDK;
if (!sdk)
throw new Error(
"xBull is not installed. Install the xBull extension and refresh.",
);
const result = await sdk.connect();
if (!result?.publicKey)
throw new Error("xBull did not return a public key.");
return result.publicKey;
},
async signTransaction(xdr, networkPassphrase) {
const sdk = window.xBullSDK;
if (!sdk) throw new Error("xBull is not installed.");
const result = await sdk.signXDR(xdr, { networkPassphrase });
if (!result?.signedXDR) throw new Error("xBull signing failed.");
return result.signedXDR;
},
};
// ─── LOBSTR adapter ───────────────────────────────────────────────────────────
// Prefers the LOBSTR browser extension (window.lobstrSDK); falls back to
// WalletConnect v2 so mobile users can connect via the LOBSTR app.
export interface WalletConnectClient {
request(args: { topic: string; chainId: string; request: { method: string; params: { xdr: string } } }): Promise<{ signedXDR: string }>;
}
export interface WalletConnectSession {
topic: string;
namespaces: Record<string, { accounts: string[] }>;
}
let _lobstrWcClient: WalletConnectClient | null = null;
let _lobstrWcSession: WalletConnectSession | null = null;
async function connectLobstrViaWalletConnect(): Promise<string> {
const projectId = process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID;
if (!projectId) {
throw new Error(
"Set NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID to enable LOBSTR on mobile. " +
"Get a free project ID at https://cloud.walletconnect.com",
);
}
const { SignClient } = await import("@walletconnect/sign-client");
const { WalletConnectModal } = await import("@walletconnect/modal");
const client = await SignClient.init({
projectId,
metadata: {
name: "FlowStar",
description: "Stellar payment streaming",
url: typeof window !== "undefined" ? window.location.origin : "",
icons: [],
},
});
const modal = new WalletConnectModal({
projectId,
chains: ["stellar:pubnet"],
});
return new Promise(async (resolve, reject) => {
try {
const { uri, approval } = await client.connect({
requiredNamespaces: {
stellar: {
methods: ["stellar_signXDR"],
chains: ["stellar:pubnet"],
events: [],
},
},
});
if (uri) modal.openModal({ uri });
const session = await approval();
modal.closeModal();
_lobstrWcClient = client as unknown as WalletConnectClient;
_lobstrWcSession = session as unknown as WalletConnectSession;
const account = session.namespaces.stellar?.accounts[0];
const address = account?.split(":")[2];
if (!address)
throw new Error(
"LOBSTR WalletConnect session has no Stellar accounts.",
);
resolve(address);
} catch (err) {
try {
modal.closeModal();
} catch {
/* ignore */
}
reject(err instanceof Error ? err : new Error(String(err)));
}
});
}
async function signWithLobstrWalletConnect(
xdr: string,
networkPassphrase: string,
): Promise<string> {
if (!_lobstrWcClient || !_lobstrWcSession) {
throw new Error(
"No active LOBSTR WalletConnect session. Reconnect LOBSTR.",
);
}
const chainId = networkPassphrase.includes("Test")
? "stellar:testnet"
: "stellar:pubnet";
const result = await _lobstrWcClient.request({
topic: _lobstrWcSession.topic,
chainId,
request: { method: "stellar_signXDR", params: { xdr } },
});
if (!result?.signedXDR)
throw new Error("LOBSTR WalletConnect signing returned no signed XDR.");
return result.signedXDR;
}
export const lobstrAdapter: WalletAdapter = {
isAvailable: () => true, // WalletConnect available even without extension
async connect() {
if (typeof window !== "undefined" && window.lobstrSDK) {
const sdk = window.lobstrSDK;
const { publicKey } = await sdk.getPublicKey();
if (!publicKey) throw new Error("LOBSTR did not return a public key.");
return publicKey;
}
return connectLobstrViaWalletConnect();
},
async signTransaction(xdr, networkPassphrase) {
if (typeof window !== "undefined" && window.lobstrSDK) {
const sdk = window.lobstrSDK;
const { signedXdr } = await sdk.signTransaction(xdr, {
networkPassphrase,
});
if (!signedXdr) throw new Error("LOBSTR signing failed.");
return signedXdr;
}
return signWithLobstrWalletConnect(xdr, networkPassphrase);
},
};
// ─── Albedo adapter ───────────────────────────────────────────────────────────
const albedoAdapter: WalletAdapter = {
isAvailable: () => true, // web-based — always available
async connect() {
const albedo = (await import("@albedo-link/intent")).default;
try {
const result = await albedo.publicKey({});
if (!result?.pubkey)
throw new Error("Albedo did not return a public key.");
return result.pubkey;
} catch (err: unknown) {
if (err instanceof Error && /popup/i.test(err.message)) {
throw new Error(
"Albedo popup was blocked. Allow popups for this site and try again.",
);
}
throw err;
}
},
async signTransaction(xdr, networkPassphrase) {
const albedo = (await import("@albedo-link/intent")).default;
const network = networkPassphrase.includes("Test") ? "testnet" : "public";
const result = await albedo.tx({ xdr, network, submit: false });
if (!result?.signed_envelope_xdr) throw new Error("Albedo signing failed.");
return result.signed_envelope_xdr;
},
};
// ─── Adapter registry ─────────────────────────────────────────────────────────
const ADAPTERS: Record<string, WalletAdapter> = {
freighter: freighterAdapter,
xbull: xbullAdapter,
lobstr: lobstrAdapter,
albedo: albedoAdapter,
};
function getAdapter(id: string): WalletAdapter {
const adapter = ADAPTERS[id];
if (!adapter) throw new Error(`Unknown wallet: ${id}`);
return adapter;
}
// ─── Context ──────────────────────────────────────────────────────────────────
interface WalletContextValue {
address: string | null;
walletId: string | null;
connecting: boolean;
reconnecting: boolean;
isConnected: boolean;
networkMismatch: boolean;
walletNetwork: string | null;
connect: (walletId: string) => Promise<void>;
disconnect: () => void;
signTransaction: (xdr: string, network?: NetworkName) => Promise<string>;
}
const WalletContext = createContext<WalletContextValue | null>(null);
// ─── Freighter network helpers ────────────────────────────────────────────────
async function getFreighterNetwork(): Promise<string | null> {
try {
const { getNetwork } = await import("@stellar/freighter-api");
const result = await getNetwork();
if (result.error) return null;
return result.network ?? null;
} catch {
return null;
}
}
// Maps Freighter network names → our NetworkName
function normalizeFreighterNetwork(raw: string): NetworkName | null {
const lower = raw.toLowerCase();
if (lower.includes("test")) return "testnet";
if (lower === "mainnet" || lower === "public" || lower.includes("public"))
return "mainnet";
return null;
}
// ─── Provider ─────────────────────────────────────────────────────────────────
export function WalletProvider({ children }: { children: ReactNode }) {
const [address, setAddress] = useState<string | null>(null);
const [walletId, setWalletId] = useState<string | null>(null);
const [connecting, setConnecting] = useState(false);
const [reconnecting, setReconnecting] = useState(true);
const [walletNetwork, setWalletNetwork] = useState<string | null>(null);
const { network } = useNetwork();
// Auto-reconnect on mount using persisted walletId
useEffect(() => {
const saved = localStorage.getItem("walletId");
if (!saved) {
setReconnecting(false);
return;
}
getAdapter(saved)
.connect()
.then((addr) => {
setAddress(addr);
setWalletId(saved);
})
.catch(() => {
localStorage.removeItem("walletId");
})
.finally(() => setReconnecting(false));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Poll Freighter's active network while connected
useEffect(() => {
if (!address || walletId !== "freighter") {
setWalletNetwork(null);
return;
}
let cancelled = false;
const check = () => {
getFreighterNetwork().then((net) => {
if (!cancelled) setWalletNetwork(net);
});
};
check();
const interval = setInterval(check, 5000);
return () => {
cancelled = true;
clearInterval(interval);
};
}, [address, walletId]);
const networkMismatch = useMemo(() => {
if (!address || walletId !== "freighter" || !walletNetwork) return false;
const normalized = normalizeFreighterNetwork(walletNetwork);
return normalized !== null && normalized !== network;
}, [address, walletId, walletNetwork, network]);
const connect = useCallback(async (id: string) => {
setConnecting(true);
try {
const addr = await getAdapter(id).connect();
setAddress(addr);
setWalletId(id);
localStorage.setItem("walletId", id);
setSentryUser(addr);
} finally {
setConnecting(false);
}
}, []);
const disconnect = useCallback(() => {
setAddress(null);
setWalletId(null);
setWalletNetwork(null);
localStorage.removeItem("walletId");
setSentryUser(null);
}, []);
const signTransaction = useCallback(
async (xdr: string, customNetwork?: NetworkName): Promise<string> => {
if (!walletId) throw new Error("No wallet connected");
const config = getNetworkConfig(customNetwork ?? network);
return getAdapter(walletId).signTransaction(xdr, config.passphrase);
},
[walletId, network],
);
// Keep contract layer in sync
useEffect(() => {
setSignTransaction((xdr: string) => signTransaction(xdr));
}, [signTransaction]);
const value = useMemo<WalletContextValue>(
() => ({
address,
walletId,
connecting,
reconnecting,
isConnected: address !== null,
networkMismatch,
walletNetwork,
connect,
disconnect,
signTransaction,
}),
[
address,
walletId,
connecting,
reconnecting,
networkMismatch,
walletNetwork,
connect,
disconnect,
signTransaction,
],
);
return (
<WalletContext.Provider value={value}>{children}</WalletContext.Provider>
);
}
// ─── Hook ─────────────────────────────────────────────────────────────────────
export function useWalletContext() {
const ctx = useContext(WalletContext);
if (!ctx) throw new Error("useWallet must be used within a WalletProvider");
return ctx;
}