@tomo-inc/wallet-connect-protocol 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,169 @@
1
+ import { W as WalletConnectClient, S as SessionInfo, Q as QRCodeOptions, a as WalletConnectConfig, b as SiweConfig } from './vanilla-2_OWCFEZ.cjs';
2
+ export { Z as APTOS_CHAINS, R as APTOS_NAMESPACE, t as AuthMethod, A as AuthOptions, T as COSMOS_NAMESPACE, u as ChainType, C as ConnectParams, M as EIP155_NAMESPACE, X as EVM_CHAINS, E as EventHandler, V as NEAR_NAMESPACE, N as NamespaceConfig, U as POLKADOT_NAMESPACE, P as POPULAR_WALLET_IDS, Y as SOLANA_CHAINS, O as SOLANA_NAMESPACE, a8 as SiweAuth, a1 as SiweResult, k as Wallet, l as WalletApp, r as WalletConnectEvent, m as WalletImage, n as WalletListOptions, o as WalletListResponse, p as WalletMetadata, q as WalletPlatform, I as copyToClipboard, $ as createMultiChainNamespaces, a7 as createSiweConfigFromSession, a2 as createSiweMessage, y as extractAddressFromAccount, z as extractChainIdFromAccount, a6 as extractChainIdNumber, x as formatAddress, J as formatError, F as formatTimestamp, H as generateDeepLink, a5 as generateNonce, g as getAllWallets, c as getBrowserWallets, _ as getChainName, a0 as getChainType, d as getDesktopWallets, e as getMobileWallets, f as getRecommendedWallets, D as getSessionTimeRemaining, h as getWalletById, i as getWalletConnectWallets, j as getWalletsByChain, G as isMobile, B as isSessionExpired, K as isValidChainId, v as isValidWalletConnectUri, L as parseChainId, a3 as parseSiweMessage, w as parseWalletConnectUri, s as searchWallets, a4 as verifySiweSignature } from './vanilla-2_OWCFEZ.cjs';
3
+ import * as react_jsx_runtime from 'react/jsx-runtime';
4
+ import { ReactNode } from 'react';
5
+
6
+ /**
7
+ * WalletConnect Context type
8
+ */
9
+ interface WalletConnectContextType {
10
+ /** client instance */
11
+ client: WalletConnectClient | null;
12
+ /** whether initialized */
13
+ initialized: boolean;
14
+ /** whether connecting */
15
+ connecting: boolean;
16
+ /** current URI */
17
+ uri: string | null;
18
+ /** active sessions list */
19
+ sessions: SessionInfo[];
20
+ /** initialize client */
21
+ initialize: () => Promise<void>;
22
+ /** create connection */
23
+ connect: () => Promise<string>;
24
+ /** generate QR code */
25
+ generateQRCode: (uri: string, options?: QRCodeOptions) => Promise<string>;
26
+ /** disconnect session */
27
+ disconnect: (topic: string) => Promise<void>;
28
+ /** refresh sessions list */
29
+ refreshSessions: () => void;
30
+ }
31
+ /**
32
+ * WalletConnect Provider Props
33
+ */
34
+ interface WalletConnectProviderProps {
35
+ /** WalletConnect configuration */
36
+ config: WalletConnectConfig;
37
+ /** child components */
38
+ children: ReactNode;
39
+ /** whether to auto initialize */
40
+ autoInit?: boolean;
41
+ }
42
+ /**
43
+ * WalletConnect Provider Component
44
+ *
45
+ * @example
46
+ * ```tsx
47
+ * import { WalletConnectProvider } from '@tomo-inc/wallet-connect-protocol';
48
+ *
49
+ * function App() {
50
+ * return (
51
+ * <WalletConnectProvider
52
+ * config={{
53
+ * projectId: 'YOUR_PROJECT_ID',
54
+ * metadata: {
55
+ * name: 'My App',
56
+ * description: 'My awesome dApp',
57
+ * url: 'https://myapp.com',
58
+ * icons: ['https://myapp.com/icon.png']
59
+ * }
60
+ * }}
61
+ * autoInit
62
+ * >
63
+ * <YourApp />
64
+ * </WalletConnectProvider>
65
+ * );
66
+ * }
67
+ * ```
68
+ */
69
+ declare function WalletConnectProvider({ config, children, autoInit }: WalletConnectProviderProps): react_jsx_runtime.JSX.Element;
70
+ /**
71
+ * Hook to use WalletConnect Context
72
+ *
73
+ * @example
74
+ * ```tsx
75
+ * import { useWalletConnect } from '@tomo-inc/wallet-connect-protocol';
76
+ *
77
+ * function ConnectButton() {
78
+ * const { connect, uri, generateQRCode } = useWalletConnect();
79
+ * const [qrCode, setQrCode] = useState<string | null>(null);
80
+ *
81
+ * const handleConnect = async () => {
82
+ * const connectionUri = await connect();
83
+ * const qr = await generateQRCode(connectionUri);
84
+ * setQrCode(qr);
85
+ * };
86
+ *
87
+ * return (
88
+ * <div>
89
+ * <button onClick={handleConnect}>Connect Wallet</button>
90
+ * {qrCode && <img src={qrCode} alt="WalletConnect QR Code" />}
91
+ * </div>
92
+ * );
93
+ * }
94
+ * ```
95
+ *
96
+ * @throws if used outside WalletConnectProvider
97
+ */
98
+ declare function useWalletConnect(): WalletConnectContextType;
99
+
100
+ /**
101
+ * QR code generation Hook
102
+ * @param uri WalletConnect URI
103
+ * @param options QR code options
104
+ * @returns QR code data URL
105
+ */
106
+ declare function useQRCode(uri?: string, options?: QRCodeOptions): {
107
+ qrCode: string | null;
108
+ loading: boolean;
109
+ error: Error | null;
110
+ generate: (targetUri?: string) => Promise<void>;
111
+ };
112
+
113
+ /**
114
+ * session management Hook
115
+ * @param topic optional session topic (if not provided, manage all sessions)
116
+ */
117
+ declare function useSession(topic?: string): {
118
+ session: SessionInfo | null;
119
+ allSessions: SessionInfo[];
120
+ disconnect: (sessionTopic?: string) => Promise<void>;
121
+ refresh: () => void;
122
+ isExpired: boolean;
123
+ getAccounts: (session?: SessionInfo) => string[];
124
+ getChains: (session?: SessionInfo) => string[];
125
+ hasSession: boolean;
126
+ };
127
+
128
+ /**
129
+ * connection management Hook
130
+ * @param options configuration options
131
+ */
132
+ declare function useConnect(options?: {
133
+ autoGenerateQRCode?: boolean;
134
+ qrCodeOptions?: QRCodeOptions;
135
+ onConnect?: (uri: string) => void;
136
+ onError?: (error: Error) => void;
137
+ }): {
138
+ connect: () => Promise<string>;
139
+ uri: string | null;
140
+ qrCode: string | null;
141
+ connecting: boolean;
142
+ error: Error | null;
143
+ reset: () => void;
144
+ };
145
+
146
+ /**
147
+ * SIWE authentication Hook
148
+ */
149
+ declare function useSiwe(config?: Partial<SiweConfig>): {
150
+ signIn: (sessionTopic?: string) => Promise<{
151
+ success: boolean;
152
+ address: string;
153
+ message: string;
154
+ signature: any;
155
+ siweMessage: any;
156
+ }>;
157
+ signOut: () => void;
158
+ isAuthenticating: boolean;
159
+ authResult: {
160
+ success: boolean;
161
+ address?: string;
162
+ message?: string;
163
+ signature?: string;
164
+ error?: string;
165
+ } | null;
166
+ isAuthenticated: boolean;
167
+ };
168
+
169
+ export { QRCodeOptions, SessionInfo, SiweConfig, WalletConnectClient, WalletConnectConfig, WalletConnectProvider, type WalletConnectProviderProps, useConnect, useQRCode, useSession, useSiwe, useWalletConnect };
@@ -0,0 +1,169 @@
1
+ import { W as WalletConnectClient, S as SessionInfo, Q as QRCodeOptions, a as WalletConnectConfig, b as SiweConfig } from './vanilla-2_OWCFEZ.js';
2
+ export { Z as APTOS_CHAINS, R as APTOS_NAMESPACE, t as AuthMethod, A as AuthOptions, T as COSMOS_NAMESPACE, u as ChainType, C as ConnectParams, M as EIP155_NAMESPACE, X as EVM_CHAINS, E as EventHandler, V as NEAR_NAMESPACE, N as NamespaceConfig, U as POLKADOT_NAMESPACE, P as POPULAR_WALLET_IDS, Y as SOLANA_CHAINS, O as SOLANA_NAMESPACE, a8 as SiweAuth, a1 as SiweResult, k as Wallet, l as WalletApp, r as WalletConnectEvent, m as WalletImage, n as WalletListOptions, o as WalletListResponse, p as WalletMetadata, q as WalletPlatform, I as copyToClipboard, $ as createMultiChainNamespaces, a7 as createSiweConfigFromSession, a2 as createSiweMessage, y as extractAddressFromAccount, z as extractChainIdFromAccount, a6 as extractChainIdNumber, x as formatAddress, J as formatError, F as formatTimestamp, H as generateDeepLink, a5 as generateNonce, g as getAllWallets, c as getBrowserWallets, _ as getChainName, a0 as getChainType, d as getDesktopWallets, e as getMobileWallets, f as getRecommendedWallets, D as getSessionTimeRemaining, h as getWalletById, i as getWalletConnectWallets, j as getWalletsByChain, G as isMobile, B as isSessionExpired, K as isValidChainId, v as isValidWalletConnectUri, L as parseChainId, a3 as parseSiweMessage, w as parseWalletConnectUri, s as searchWallets, a4 as verifySiweSignature } from './vanilla-2_OWCFEZ.js';
3
+ import * as react_jsx_runtime from 'react/jsx-runtime';
4
+ import { ReactNode } from 'react';
5
+
6
+ /**
7
+ * WalletConnect Context type
8
+ */
9
+ interface WalletConnectContextType {
10
+ /** client instance */
11
+ client: WalletConnectClient | null;
12
+ /** whether initialized */
13
+ initialized: boolean;
14
+ /** whether connecting */
15
+ connecting: boolean;
16
+ /** current URI */
17
+ uri: string | null;
18
+ /** active sessions list */
19
+ sessions: SessionInfo[];
20
+ /** initialize client */
21
+ initialize: () => Promise<void>;
22
+ /** create connection */
23
+ connect: () => Promise<string>;
24
+ /** generate QR code */
25
+ generateQRCode: (uri: string, options?: QRCodeOptions) => Promise<string>;
26
+ /** disconnect session */
27
+ disconnect: (topic: string) => Promise<void>;
28
+ /** refresh sessions list */
29
+ refreshSessions: () => void;
30
+ }
31
+ /**
32
+ * WalletConnect Provider Props
33
+ */
34
+ interface WalletConnectProviderProps {
35
+ /** WalletConnect configuration */
36
+ config: WalletConnectConfig;
37
+ /** child components */
38
+ children: ReactNode;
39
+ /** whether to auto initialize */
40
+ autoInit?: boolean;
41
+ }
42
+ /**
43
+ * WalletConnect Provider Component
44
+ *
45
+ * @example
46
+ * ```tsx
47
+ * import { WalletConnectProvider } from '@tomo-inc/wallet-connect-protocol';
48
+ *
49
+ * function App() {
50
+ * return (
51
+ * <WalletConnectProvider
52
+ * config={{
53
+ * projectId: 'YOUR_PROJECT_ID',
54
+ * metadata: {
55
+ * name: 'My App',
56
+ * description: 'My awesome dApp',
57
+ * url: 'https://myapp.com',
58
+ * icons: ['https://myapp.com/icon.png']
59
+ * }
60
+ * }}
61
+ * autoInit
62
+ * >
63
+ * <YourApp />
64
+ * </WalletConnectProvider>
65
+ * );
66
+ * }
67
+ * ```
68
+ */
69
+ declare function WalletConnectProvider({ config, children, autoInit }: WalletConnectProviderProps): react_jsx_runtime.JSX.Element;
70
+ /**
71
+ * Hook to use WalletConnect Context
72
+ *
73
+ * @example
74
+ * ```tsx
75
+ * import { useWalletConnect } from '@tomo-inc/wallet-connect-protocol';
76
+ *
77
+ * function ConnectButton() {
78
+ * const { connect, uri, generateQRCode } = useWalletConnect();
79
+ * const [qrCode, setQrCode] = useState<string | null>(null);
80
+ *
81
+ * const handleConnect = async () => {
82
+ * const connectionUri = await connect();
83
+ * const qr = await generateQRCode(connectionUri);
84
+ * setQrCode(qr);
85
+ * };
86
+ *
87
+ * return (
88
+ * <div>
89
+ * <button onClick={handleConnect}>Connect Wallet</button>
90
+ * {qrCode && <img src={qrCode} alt="WalletConnect QR Code" />}
91
+ * </div>
92
+ * );
93
+ * }
94
+ * ```
95
+ *
96
+ * @throws if used outside WalletConnectProvider
97
+ */
98
+ declare function useWalletConnect(): WalletConnectContextType;
99
+
100
+ /**
101
+ * QR code generation Hook
102
+ * @param uri WalletConnect URI
103
+ * @param options QR code options
104
+ * @returns QR code data URL
105
+ */
106
+ declare function useQRCode(uri?: string, options?: QRCodeOptions): {
107
+ qrCode: string | null;
108
+ loading: boolean;
109
+ error: Error | null;
110
+ generate: (targetUri?: string) => Promise<void>;
111
+ };
112
+
113
+ /**
114
+ * session management Hook
115
+ * @param topic optional session topic (if not provided, manage all sessions)
116
+ */
117
+ declare function useSession(topic?: string): {
118
+ session: SessionInfo | null;
119
+ allSessions: SessionInfo[];
120
+ disconnect: (sessionTopic?: string) => Promise<void>;
121
+ refresh: () => void;
122
+ isExpired: boolean;
123
+ getAccounts: (session?: SessionInfo) => string[];
124
+ getChains: (session?: SessionInfo) => string[];
125
+ hasSession: boolean;
126
+ };
127
+
128
+ /**
129
+ * connection management Hook
130
+ * @param options configuration options
131
+ */
132
+ declare function useConnect(options?: {
133
+ autoGenerateQRCode?: boolean;
134
+ qrCodeOptions?: QRCodeOptions;
135
+ onConnect?: (uri: string) => void;
136
+ onError?: (error: Error) => void;
137
+ }): {
138
+ connect: () => Promise<string>;
139
+ uri: string | null;
140
+ qrCode: string | null;
141
+ connecting: boolean;
142
+ error: Error | null;
143
+ reset: () => void;
144
+ };
145
+
146
+ /**
147
+ * SIWE authentication Hook
148
+ */
149
+ declare function useSiwe(config?: Partial<SiweConfig>): {
150
+ signIn: (sessionTopic?: string) => Promise<{
151
+ success: boolean;
152
+ address: string;
153
+ message: string;
154
+ signature: any;
155
+ siweMessage: any;
156
+ }>;
157
+ signOut: () => void;
158
+ isAuthenticating: boolean;
159
+ authResult: {
160
+ success: boolean;
161
+ address?: string;
162
+ message?: string;
163
+ signature?: string;
164
+ error?: string;
165
+ } | null;
166
+ isAuthenticated: boolean;
167
+ };
168
+
169
+ export { QRCodeOptions, SessionInfo, SiweConfig, WalletConnectClient, WalletConnectConfig, WalletConnectProvider, type WalletConnectProviderProps, useConnect, useQRCode, useSession, useSiwe, useWalletConnect };
package/dist/index.js ADDED
@@ -0,0 +1,349 @@
1
+ import { WalletConnectClient, isSessionExpired, extractAddressFromAccount, extractChainIdFromAccount, extractChainIdNumber, createSiweConfigFromSession, SiweAuth } from './chunk-32KOSJUW.js';
2
+ export { APTOS_CHAINS, APTOS_NAMESPACE, AuthMethod, COSMOS_NAMESPACE, ChainType, EIP155_NAMESPACE, EVM_CHAINS, NEAR_NAMESPACE, POLKADOT_NAMESPACE, POPULAR_WALLET_IDS, SOLANA_CHAINS, SOLANA_NAMESPACE, SiweAuth, WalletConnectClient, copyToClipboard, createMultiChainNamespaces, createSiweConfigFromSession, createSiweMessage, extractAddressFromAccount, extractChainIdFromAccount, extractChainIdNumber, formatAddress, formatError, formatTimestamp, generateDeepLink, generateNonce, getAllWallets, getBrowserWallets, getChainName, getChainType, getDesktopWallets, getMobileWallets, getRecommendedWallets, getSessionTimeRemaining, getWalletById, getWalletConnectWallets, getWalletsByChain, isMobile, isSessionExpired, isValidChainId, isValidWalletConnectUri, parseChainId, parseSiweMessage, parseWalletConnectUri, searchWallets, verifySiweSignature } from './chunk-32KOSJUW.js';
3
+ import { createContext, useState, useCallback, useEffect, useContext } from 'react';
4
+ import { jsx } from 'react/jsx-runtime';
5
+
6
+ var WalletConnectContext = createContext(void 0);
7
+ function WalletConnectProvider({ config, children, autoInit = true }) {
8
+ const [client, setClient] = useState(null);
9
+ const [initialized, setInitialized] = useState(false);
10
+ const [connecting, setConnecting] = useState(false);
11
+ const [uri, setUri] = useState(null);
12
+ const [sessions, setSessions] = useState([]);
13
+ const refreshSessions = useCallback(() => {
14
+ if (client) {
15
+ const activeSessions = client.getActiveSessions();
16
+ setSessions(activeSessions);
17
+ }
18
+ }, [client]);
19
+ const initialize = useCallback(async () => {
20
+ if (initialized) {
21
+ return;
22
+ }
23
+ try {
24
+ const newClient = new WalletConnectClient(config);
25
+ newClient.on("display_uri", ({ uri: uri2 }) => {
26
+ setUri(uri2);
27
+ });
28
+ const handleSessionUpdate = () => {
29
+ const activeSessions2 = newClient.getActiveSessions();
30
+ setSessions(activeSessions2);
31
+ };
32
+ newClient.on("session_proposal", handleSessionUpdate);
33
+ newClient.on("session_update", handleSessionUpdate);
34
+ newClient.on("session_delete", handleSessionUpdate);
35
+ await newClient.initialize();
36
+ setClient(newClient);
37
+ setInitialized(true);
38
+ const activeSessions = newClient.getActiveSessions();
39
+ setSessions(activeSessions);
40
+ } catch (error) {
41
+ throw error;
42
+ }
43
+ }, [config, initialized]);
44
+ const connect = useCallback(async () => {
45
+ if (!client) {
46
+ throw new Error("WalletConnect client not initialized");
47
+ }
48
+ setConnecting(true);
49
+ try {
50
+ const connectionUri = await client.connect();
51
+ setUri(connectionUri);
52
+ return connectionUri;
53
+ } catch (error) {
54
+ throw error;
55
+ } finally {
56
+ setConnecting(false);
57
+ }
58
+ }, [client]);
59
+ const generateQRCode = useCallback(
60
+ async (uri2, options) => {
61
+ if (!client) {
62
+ throw new Error("WalletConnect client not initialized");
63
+ }
64
+ return client.generateQRCode(uri2, options);
65
+ },
66
+ [client]
67
+ );
68
+ const disconnect = useCallback(
69
+ async (topic) => {
70
+ if (!client) {
71
+ throw new Error("WalletConnect client not initialized");
72
+ }
73
+ await client.disconnectSession(topic);
74
+ refreshSessions();
75
+ },
76
+ [client]
77
+ );
78
+ useEffect(() => {
79
+ if (!client || !initialized) return;
80
+ const interval = setInterval(() => {
81
+ refreshSessions();
82
+ }, 2e3);
83
+ return () => clearInterval(interval);
84
+ }, [client, initialized, refreshSessions]);
85
+ useEffect(() => {
86
+ if (autoInit && !initialized) {
87
+ initialize().catch(console.error);
88
+ }
89
+ }, [autoInit, initialized, initialize]);
90
+ useEffect(() => {
91
+ return () => {
92
+ if (client) {
93
+ client.destroy().catch(console.error);
94
+ }
95
+ };
96
+ }, [client]);
97
+ const value = {
98
+ client,
99
+ initialized,
100
+ connecting,
101
+ uri,
102
+ sessions,
103
+ initialize,
104
+ connect,
105
+ generateQRCode,
106
+ disconnect,
107
+ refreshSessions
108
+ };
109
+ return /* @__PURE__ */ jsx(WalletConnectContext.Provider, { value, children });
110
+ }
111
+ function useWalletConnect() {
112
+ const context = useContext(WalletConnectContext);
113
+ if (!context) {
114
+ throw new Error("useWalletConnect must be used within WalletConnectProvider");
115
+ }
116
+ return context;
117
+ }
118
+ function useQRCode(uri, options) {
119
+ const { generateQRCode } = useWalletConnect();
120
+ const [qrCode, setQrCode] = useState(null);
121
+ const [loading, setLoading] = useState(false);
122
+ const [error, setError] = useState(null);
123
+ const generate = useCallback(
124
+ async (targetUri) => {
125
+ const uriToUse = targetUri || uri;
126
+ if (!uriToUse) {
127
+ setError(new Error("No URI provided"));
128
+ return;
129
+ }
130
+ setLoading(true);
131
+ setError(null);
132
+ try {
133
+ const qr = await generateQRCode(uriToUse, options);
134
+ setQrCode(qr);
135
+ } catch (err) {
136
+ setError(err);
137
+ setQrCode(null);
138
+ } finally {
139
+ setLoading(false);
140
+ }
141
+ },
142
+ [uri, options, generateQRCode]
143
+ );
144
+ useEffect(() => {
145
+ if (uri) {
146
+ generate(uri);
147
+ }
148
+ }, [uri, generate]);
149
+ return {
150
+ qrCode,
151
+ loading,
152
+ error,
153
+ generate
154
+ };
155
+ }
156
+ function useSession(topic) {
157
+ const { sessions, disconnect, refreshSessions, client } = useWalletConnect();
158
+ const [currentSession, setCurrentSession] = useState(null);
159
+ useEffect(() => {
160
+ if (topic) {
161
+ const session = sessions.find((s) => s.topic === topic);
162
+ setCurrentSession(session || null);
163
+ } else {
164
+ setCurrentSession(sessions[0] || null);
165
+ }
166
+ }, [topic, sessions]);
167
+ const disconnectSession = useCallback(
168
+ async (sessionTopic) => {
169
+ const topicToDisconnect = sessionTopic || topic || currentSession?.topic;
170
+ if (!topicToDisconnect) {
171
+ throw new Error("No session to disconnect");
172
+ }
173
+ await disconnect(topicToDisconnect);
174
+ },
175
+ [topic, currentSession, disconnect]
176
+ );
177
+ const checkExpired = useCallback((session) => {
178
+ return isSessionExpired(session.expiry);
179
+ }, []);
180
+ const getAccounts = useCallback(
181
+ (session) => {
182
+ const targetSession = session || currentSession;
183
+ if (!targetSession) return [];
184
+ const allAccounts = [];
185
+ Object.values(targetSession.namespaces).forEach((namespace) => {
186
+ if (namespace.accounts) {
187
+ allAccounts.push(...namespace.accounts);
188
+ }
189
+ });
190
+ return allAccounts;
191
+ },
192
+ [currentSession]
193
+ );
194
+ const getChains = useCallback(
195
+ (session) => {
196
+ const targetSession = session || currentSession;
197
+ if (!targetSession) return [];
198
+ const allChains = [];
199
+ Object.values(targetSession.namespaces).forEach((namespace) => {
200
+ if (namespace.chains) {
201
+ allChains.push(...namespace.chains);
202
+ }
203
+ });
204
+ return allChains;
205
+ },
206
+ [currentSession]
207
+ );
208
+ return {
209
+ session: currentSession,
210
+ allSessions: sessions,
211
+ disconnect: disconnectSession,
212
+ refresh: refreshSessions,
213
+ isExpired: currentSession ? checkExpired(currentSession) : false,
214
+ getAccounts,
215
+ getChains,
216
+ hasSession: !!currentSession
217
+ };
218
+ }
219
+ function useConnect(options) {
220
+ const { connect, generateQRCode, connecting } = useWalletConnect();
221
+ const [uri, setUri] = useState(null);
222
+ const [qrCode, setQrCode] = useState(null);
223
+ const [error, setError] = useState(null);
224
+ const handleConnect = useCallback(async () => {
225
+ setError(null);
226
+ try {
227
+ const connectionUri = await connect();
228
+ setUri(connectionUri);
229
+ if (options?.onConnect) {
230
+ options.onConnect(connectionUri);
231
+ }
232
+ if (options?.autoGenerateQRCode !== false) {
233
+ const qr = await generateQRCode(connectionUri, options?.qrCodeOptions);
234
+ setQrCode(qr);
235
+ }
236
+ return connectionUri;
237
+ } catch (err) {
238
+ const error2 = err;
239
+ setError(error2);
240
+ options?.onError?.(error2);
241
+ throw error2;
242
+ }
243
+ }, [connect, generateQRCode, options]);
244
+ const reset = useCallback(() => {
245
+ setUri(null);
246
+ setQrCode(null);
247
+ setError(null);
248
+ }, []);
249
+ return {
250
+ connect: handleConnect,
251
+ uri,
252
+ qrCode,
253
+ connecting,
254
+ error,
255
+ reset
256
+ };
257
+ }
258
+ function useSiwe(config) {
259
+ const { client } = useWalletConnect();
260
+ const [isAuthenticating, setIsAuthenticating] = useState(false);
261
+ const [authResult, setAuthResult] = useState(null);
262
+ const signIn = useCallback(
263
+ async (sessionTopic) => {
264
+ if (!client) {
265
+ throw new Error("WalletConnect client not initialized");
266
+ }
267
+ const sessions = client.getActiveSessions();
268
+ if (sessions.length === 0) {
269
+ throw new Error("No active sessions. Connect wallet first.");
270
+ }
271
+ setIsAuthenticating(true);
272
+ setAuthResult(null);
273
+ try {
274
+ const session = sessionTopic ? sessions.find((s) => s.topic === sessionTopic) : sessions[0];
275
+ if (!session) {
276
+ throw new Error("Session not found");
277
+ }
278
+ const accounts = Object.values(session.namespaces).flatMap((ns) => ns.accounts || []);
279
+ const primaryAccount = accounts[0];
280
+ if (!primaryAccount) {
281
+ throw new Error("No accounts found in session");
282
+ }
283
+ const address = extractAddressFromAccount(primaryAccount);
284
+ const chainIdStr = extractChainIdFromAccount(primaryAccount);
285
+ const chainId = extractChainIdNumber(primaryAccount);
286
+ const siweConfig = createSiweConfigFromSession({
287
+ domain: config?.domain || window.location.host,
288
+ uri: config?.uri || window.location.origin,
289
+ chainId,
290
+ statement: config?.statement,
291
+ resources: config?.resources
292
+ });
293
+ const siweAuth = new SiweAuth(siweConfig);
294
+ const message = await siweAuth.createMessage(address);
295
+ if (!client.signClient) {
296
+ throw new Error("SignClient not initialized");
297
+ }
298
+ const signature = await client.signClient.request({
299
+ topic: session.topic,
300
+ chainId: chainIdStr,
301
+ request: {
302
+ method: "personal_sign",
303
+ params: [message, address]
304
+ }
305
+ });
306
+ const verifyResult = await siweAuth.verify(message, signature);
307
+ if (verifyResult.success) {
308
+ setAuthResult({
309
+ success: true,
310
+ address,
311
+ message,
312
+ signature
313
+ });
314
+ return {
315
+ success: true,
316
+ address,
317
+ message,
318
+ signature,
319
+ siweMessage: verifyResult.data
320
+ };
321
+ } else {
322
+ throw new Error(verifyResult.error || "Signature verification failed");
323
+ }
324
+ } catch (error) {
325
+ const errorMsg = error.message || "Authentication failed";
326
+ setAuthResult({
327
+ success: false,
328
+ error: errorMsg
329
+ });
330
+ throw error;
331
+ } finally {
332
+ setIsAuthenticating(false);
333
+ }
334
+ },
335
+ [client, config]
336
+ );
337
+ const signOut = useCallback(() => {
338
+ setAuthResult(null);
339
+ }, []);
340
+ return {
341
+ signIn,
342
+ signOut,
343
+ isAuthenticating,
344
+ authResult,
345
+ isAuthenticated: authResult?.success || false
346
+ };
347
+ }
348
+
349
+ export { WalletConnectProvider, useConnect, useQRCode, useSession, useSiwe, useWalletConnect };