-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathuseWalletCenter.tsx
More file actions
85 lines (77 loc) · 2.58 KB
/
useWalletCenter.tsx
File metadata and controls
85 lines (77 loc) · 2.58 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
import { useCallback, useState } from 'react';
import { PolkadotWallet, PolkadotWalletName } from './PolkadotWallet';
import { BaseWalletType } from './types';
/**
* Represents the names of supported wallets that can be connected.
*/
export type ConnectedWalletsName = 'polkadot-js' | 'keyring' | 'metamask' | 'talisman' | 'subwallet-js' | 'enkrypt' | 'novawallet';
const wallets = new Map<
ConnectedWalletsName,
typeof PolkadotWallet
>([
['polkadot-js', PolkadotWallet],
['talisman', PolkadotWallet],
['subwallet-js', PolkadotWallet],
['enkrypt', PolkadotWallet],
['novawallet', PolkadotWallet],
]);
/**
* Key used for storing the type of connected wallet in localStorage.
*
* @constant
*/
export const CONNECTED_WALLET_TYPE = 'connected-wallet-type';
/**
* Custom React hook for managing wallet connections.
*
* @returns An object containing:
* - `connectWallet`: A function to connect a wallet of the specified type.
* - `connectedWallets`: A Map of connected wallets and their respective accounts.
*
* @example
* ```typescript
* const { connectWallet, connectedWallets } = useWalletCenter();
*
* // Connect to a Polkadot.js wallet
* await connectWallet('polkadot-js');
*
* // Access the connected wallets and their accounts
* console.log(connectedWallets);
* ```
*/
export const useWalletCenter = (chainProperties?: any) => {
const [connectedWallets, setConnectedWallets] = useState(
new Map<ConnectedWalletsName, Map<string, BaseWalletType<any>>>([])
);
const connectWallet = useCallback(
async (typeWallet: ConnectedWalletsName) => {
try {
const wallet = new (wallets.get(typeWallet)!)(typeWallet as PolkadotWalletName);
const currentWallets = await wallet.getAccounts();
const connectedWallets =
localStorage.getItem(CONNECTED_WALLET_TYPE)?.split(';') || [];
if (!connectedWallets.includes(typeWallet)) {
connectedWallets.push(typeWallet);
localStorage.setItem(CONNECTED_WALLET_TYPE, connectedWallets.join(';'));
}
setConnectedWallets((prev) => new Map([...prev, [typeWallet, currentWallets]]));
return currentWallets;
} catch (e: any) {
const connectedWallets =
localStorage.getItem(CONNECTED_WALLET_TYPE)?.split(';') || [];
if (connectedWallets.includes(typeWallet)) {
localStorage.setItem(
CONNECTED_WALLET_TYPE,
connectedWallets.filter((type) => type !== typeWallet).join(';')
);
}
throw e;
}
},
[]
);
return {
connectWallet,
connectedWallets
} as const;
};