forked from real-boys/soroban-multisig-safe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWalletContext.tsx
More file actions
77 lines (67 loc) · 2.06 KB
/
Copy pathWalletContext.tsx
File metadata and controls
77 lines (67 loc) · 2.06 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
import React, { createContext, useState, useEffect, ReactNode, useCallback } from 'react';
import { StellarWalletsKit, WalletType, Network } from '@stellar/wallet-kit';
interface WalletContextType {
publicKey: string;
kit: StellarWalletsKit | null;
connect: () => Promise<void>;
disconnect: () => Promise<void>;
network: Network;
setNetwork: (network: Network) => void;
}
export const WalletContext = createContext<WalletContextType | undefined>(undefined);
interface WalletProviderProps {
children: ReactNode;
}
export const WalletProvider: React.FC<WalletProviderProps> = ({ children }) => {
const [publicKey, setPublicKey] = useState('');
const [network, setNetwork] = useState<Network>(Network.TESTNET);
const [kit, setKit] = useState<StellarWalletsKit | null>(null);
useEffect(() => {
const newKit = new StellarWalletsKit({
network: network,
selectedWallet: localStorage.getItem('selectedWallet') as WalletType | undefined,
});
setKit(newKit);
}, [network]);
// Persistent session management: check for a public key on kit initialization
useEffect(() => {
if (kit?.publicKey) {
setPublicKey(kit.publicKey);
localStorage.setItem('selectedWallet', kit.walletType as string);
}
}, [kit]);
const connect = useCallback(async () => {
if (!kit) return;
try {
await kit.openModal({
onWalletSelected: async (option) => {
kit.setWallet(option.type);
const pk = await kit.getPublicKey();
setPublicKey(pk);
localStorage.setItem('selectedWallet', option.type);
},
});
} catch (error) {
console.error('Wallet connection failed:', error);
}
}, [kit]);
const disconnect = useCallback(async () => {
if (!kit) return;
await kit.signOut();
setPublicKey('');
localStorage.removeItem('selectedWallet');
}, [kit]);
const value = {
publicKey,
kit,
connect,
disconnect,
network,
setNetwork,
};
return (
<WalletContext.Provider value={value}>
{children}
</WalletContext.Provider>
);
};