@b3dotfun/sdk 0.0.82 → 0.0.83-test.0

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.
Files changed (31) hide show
  1. package/dist/cjs/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +57 -12
  2. package/dist/cjs/global-account/react/hooks/index.d.ts +1 -0
  3. package/dist/cjs/global-account/react/hooks/index.js +3 -1
  4. package/dist/cjs/global-account/react/hooks/useAuth.d.ts +76 -0
  5. package/dist/cjs/global-account/react/hooks/useAuth.js +338 -0
  6. package/dist/cjs/global-account/react/hooks/useAuthentication.d.ts +1 -1
  7. package/dist/cjs/global-account/react/hooks/useAuthentication.js +36 -25
  8. package/dist/cjs/global-account/react/hooks/useTWAuth.d.ts +3 -0
  9. package/dist/cjs/global-account/react/hooks/useTWAuth.js +8 -0
  10. package/dist/cjs/global-account/react/hooks/useTurnkeyAuth.js +54 -24
  11. package/dist/esm/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +57 -12
  12. package/dist/esm/global-account/react/hooks/index.d.ts +1 -0
  13. package/dist/esm/global-account/react/hooks/index.js +1 -0
  14. package/dist/esm/global-account/react/hooks/useAuth.d.ts +76 -0
  15. package/dist/esm/global-account/react/hooks/useAuth.js +332 -0
  16. package/dist/esm/global-account/react/hooks/useAuthentication.d.ts +1 -1
  17. package/dist/esm/global-account/react/hooks/useAuthentication.js +36 -25
  18. package/dist/esm/global-account/react/hooks/useTWAuth.d.ts +3 -0
  19. package/dist/esm/global-account/react/hooks/useTWAuth.js +8 -0
  20. package/dist/esm/global-account/react/hooks/useTurnkeyAuth.js +54 -24
  21. package/dist/types/global-account/react/hooks/index.d.ts +1 -0
  22. package/dist/types/global-account/react/hooks/useAuth.d.ts +76 -0
  23. package/dist/types/global-account/react/hooks/useAuthentication.d.ts +1 -1
  24. package/dist/types/global-account/react/hooks/useTWAuth.d.ts +3 -0
  25. package/package.json +1 -1
  26. package/src/global-account/react/components/SignInWithB3/SignInWithB3Flow.tsx +77 -22
  27. package/src/global-account/react/hooks/index.ts +1 -0
  28. package/src/global-account/react/hooks/useAuth.ts +380 -0
  29. package/src/global-account/react/hooks/useAuthentication.ts +51 -47
  30. package/src/global-account/react/hooks/useTWAuth.tsx +10 -0
  31. package/src/global-account/react/hooks/useTurnkeyAuth.ts +59 -26
@@ -0,0 +1,332 @@
1
+ import app from "../../../global-account/app.js";
2
+ import { authenticateWithB3JWT } from "../../../global-account/bsmnt.js";
3
+ import { useAuthStore } from "../../../global-account/react/index.js";
4
+ import { ecosystemWalletId } from "../../../shared/constants/index.js";
5
+ import { debugB3React } from "../../../shared/utils/debug.js";
6
+ import { client } from "../../../shared/utils/thirdweb.js";
7
+ import { getConnectors } from "@wagmi/core";
8
+ import { useCallback, useContext, useEffect, useRef } from "react";
9
+ import { useActiveWallet, useAutoConnect, useConnectedWallets, useDisconnect, useSetActiveWallet, } from "thirdweb/react";
10
+ import { ecosystemWallet } from "thirdweb/wallets";
11
+ import { preAuthenticate } from "thirdweb/wallets/in-app";
12
+ import { useAccount, useConnect, useSwitchAccount } from "wagmi";
13
+ import { LocalSDKContext } from "../components/B3Provider/LocalSDKProvider.js";
14
+ import { useB3 } from "../components/B3Provider/useB3.js";
15
+ import { createWagmiConfig } from "../utils/createWagmiConfig.js";
16
+ import { useSearchParam } from "./useSearchParamsSSR.js";
17
+ import { useUserQuery } from "./useUserQuery.js";
18
+ const debug = debugB3React("useAuth");
19
+ /**
20
+ * Unified authentication hook that uses Turnkey for authentication
21
+ * This replaces the previous Thirdweb-based authentication
22
+ *
23
+ * This hook provides 1:1 feature parity with useAuthentication.ts
24
+ */
25
+ export function useAuth() {
26
+ const { onConnectCallback } = useContext(LocalSDKContext);
27
+ const { disconnect } = useDisconnect();
28
+ const wallets = useConnectedWallets();
29
+ const activeWallet = useActiveWallet();
30
+ const isAuthenticated = useAuthStore(state => state.isAuthenticated);
31
+ const setIsAuthenticated = useAuthStore(state => state.setIsAuthenticated);
32
+ const setIsConnected = useAuthStore(state => state.setIsConnected);
33
+ const isConnecting = useAuthStore(state => state.isConnecting);
34
+ const isConnected = useAuthStore(state => state.isConnected);
35
+ const isAuthenticating = useAuthStore(state => state.isAuthenticating);
36
+ const setIsAuthenticating = useAuthStore(state => state.setIsAuthenticating);
37
+ const setHasStartedConnecting = useAuthStore(state => state.setHasStartedConnecting);
38
+ const setActiveWallet = useSetActiveWallet();
39
+ const hasStartedConnecting = useAuthStore(state => state.hasStartedConnecting);
40
+ const useAutoConnectLoadingPrevious = useRef(false);
41
+ const referralCode = useSearchParam("referralCode");
42
+ const { partnerId } = useB3();
43
+ const wagmiConfig = createWagmiConfig({ partnerId });
44
+ const { connect } = useConnect();
45
+ const activeWagmiAccount = useAccount();
46
+ const { switchAccount } = useSwitchAccount();
47
+ const { user, setUser } = useUserQuery();
48
+ debug("@@activeWagmiAccount", activeWagmiAccount);
49
+ const wallet = ecosystemWallet(ecosystemWalletId, {
50
+ partnerId: partnerId,
51
+ });
52
+ /**
53
+ * Re-authenticate using existing session
54
+ * Also updates user state and authenticates with BSMNT
55
+ */
56
+ const reAuthenticate = useCallback(async () => {
57
+ debug("Re-authenticating...");
58
+ try {
59
+ const response = await app.reAuthenticate();
60
+ debug("Re-authentication successful", response);
61
+ // Update user state if user data exists
62
+ if (response.user) {
63
+ setUser(response.user);
64
+ debug("User state updated", response.user);
65
+ }
66
+ // Authenticate with BSMNT
67
+ try {
68
+ const b3Jwt = await authenticateWithB3JWT(response.accessToken);
69
+ debug("BSMNT re-authentication successful", b3Jwt);
70
+ }
71
+ catch (bsmntError) {
72
+ // BSMNT authentication failure shouldn't block the main auth flow
73
+ debug("BSMNT re-authentication failed (non-critical)", bsmntError);
74
+ }
75
+ return response;
76
+ }
77
+ catch (err) {
78
+ debug("Re-authentication failed", err);
79
+ throw err;
80
+ }
81
+ }, [setUser]);
82
+ const syncWagmi = useCallback(async () => {
83
+ function syncWagmiFunc() {
84
+ const connectors = getConnectors(wagmiConfig);
85
+ debug("@@syncWagmi", {
86
+ connectors,
87
+ wallets,
88
+ });
89
+ // For each that matchs a TW wallet on wallets, connect to the wagmi connector
90
+ // or, since ecosystem wallets is separate, connect those via in-app-wallet from wagmi
91
+ connectors.forEach(async (connector) => {
92
+ const twWallet = wallets.find(wallet => wallet.id === connector.id || connector.id === "in-app-wallet");
93
+ // If no TW wallet, do not prompt the user to connect
94
+ if (!twWallet) {
95
+ return;
96
+ }
97
+ // Metamask will prompt to connect, we can just switch accounts here.
98
+ if (connector.id === "io.metamask") {
99
+ return switchAccount({ connector });
100
+ }
101
+ if (
102
+ // If it's not an in-app wallet or it is the ecosystem wallet, connect
103
+ connector.id !== "in-app-wallet" ||
104
+ (connector.id === "in-app-wallet" && twWallet.id === ecosystemWalletId)) {
105
+ try {
106
+ const options = {
107
+ wallet: twWallet, // the connected wallet
108
+ };
109
+ debug("@@syncWagmi:connecting", { twWallet, connector });
110
+ connect({
111
+ connector,
112
+ ...options,
113
+ });
114
+ }
115
+ catch (error) {
116
+ console.error("@@syncWagmi:error", error);
117
+ }
118
+ }
119
+ else {
120
+ debug("@@syncWagmi:not-connecting", connector);
121
+ }
122
+ });
123
+ }
124
+ syncWagmiFunc();
125
+ // wagmi config shouldn't change
126
+ // eslint-disable-next-line react-hooks/exhaustive-deps
127
+ }, [partnerId, wallets]);
128
+ useEffect(() => {
129
+ syncWagmi();
130
+ }, [wallets, syncWagmi]);
131
+ /**
132
+ * Authenticate user using Turnkey
133
+ * Note: This no longer requires a wallet for authentication.
134
+ * Wallets are still used for signing transactions, but authentication is done via Turnkey email OTP.
135
+ *
136
+ * For backward compatibility, this function still accepts a wallet parameter,
137
+ * but it's not used for authentication anymore.
138
+ */
139
+ const authenticateUser = useCallback(async () => {
140
+ setHasStartedConnecting(true);
141
+ // Try to re-authenticate first
142
+ try {
143
+ const userAuth = await reAuthenticate();
144
+ setUser(userAuth.user);
145
+ setIsAuthenticated(true);
146
+ setIsAuthenticating(false);
147
+ debug("Re-authenticated successfully", { userAuth });
148
+ // Authenticate on BSMNT with B3 JWT
149
+ const b3Jwt = await authenticateWithB3JWT(userAuth.accessToken);
150
+ debug("@@b3Jwt", b3Jwt);
151
+ return userAuth;
152
+ }
153
+ catch (error) {
154
+ // If re-authentication fails, user needs to authenticate via Turnkey
155
+ // This should be handled by the Turnkey auth modal/flow
156
+ debug("Re-authentication failed. User needs to authenticate via Turnkey.", error);
157
+ setIsAuthenticated(false);
158
+ setIsAuthenticating(false);
159
+ throw new Error("Authentication required. Please authenticate via Turnkey.");
160
+ }
161
+ }, [reAuthenticate, setIsAuthenticated, setIsAuthenticating, setUser, setHasStartedConnecting]);
162
+ /**
163
+ * Authenticate with Turnkey using email OTP
164
+ * This is the primary authentication method, replacing Thirdweb wallet-based auth
165
+ *
166
+ * This function:
167
+ * 1. Authenticates with FeathersJS (persists session via cookies)
168
+ * 2. Sets user state in the user store (persists to localStorage)
169
+ * 3. Authenticates with BSMNT for basement integration
170
+ */
171
+ const authenticate = useCallback(async (turnkeySessionJwt, partnerId) => {
172
+ if (!turnkeySessionJwt) {
173
+ throw new Error("Turnkey session JWT is required");
174
+ }
175
+ debug("Authenticating with Turnkey JWT", { referralCode, partnerId });
176
+ try {
177
+ // Step 1: Authenticate with FeathersJS (session persisted via cookies)
178
+ const response = await app.authenticate({
179
+ strategy: "turnkey-jwt",
180
+ accessToken: turnkeySessionJwt,
181
+ referralCode,
182
+ partnerId: partnerId,
183
+ });
184
+ debug("Authentication successful", response);
185
+ // Step 2: Set user state (persists to localStorage via Zustand)
186
+ if (response.user) {
187
+ setUser(response.user);
188
+ debug("User state updated", response.user);
189
+ }
190
+ // Step 3: Authenticate with BSMNT for basement integration
191
+ try {
192
+ const b3Jwt = await authenticateWithB3JWT(response.accessToken);
193
+ debug("BSMNT authentication successful", b3Jwt);
194
+ }
195
+ catch (bsmntError) {
196
+ // BSMNT authentication failure shouldn't block the main auth flow
197
+ debug("BSMNT authentication failed (non-critical)", bsmntError);
198
+ }
199
+ return response;
200
+ }
201
+ catch (err) {
202
+ debug("Authentication failed", err);
203
+ throw err;
204
+ }
205
+ }, [referralCode, setUser]);
206
+ /**
207
+ * Handle wallet connection
208
+ * Note: With Turnkey migration, wallet connection is primarily for signing transactions,
209
+ * not for authentication. Authentication should be done separately via Turnkey email OTP.
210
+ */
211
+ /**
212
+ * Handle wallet connection
213
+ * Note: With Turnkey migration, wallet connection is primarily for signing transactions,
214
+ * not for authentication. Authentication should be done separately via Turnkey email OTP.
215
+ */
216
+ const onConnect = useCallback(async (_walleAutoConnectedWith, allConnectedWallets) => {
217
+ debug("@@useAuth:onConnect", { _walleAutoConnectedWith, allConnectedWallets });
218
+ const wallet = allConnectedWallets.find(wallet => wallet.id.startsWith("ecosystem."));
219
+ if (!wallet) {
220
+ throw new Error("No smart wallet found during auto-connect");
221
+ }
222
+ debug("@@useAuth:onConnect", { wallet });
223
+ try {
224
+ setHasStartedConnecting(true);
225
+ setIsConnected(true);
226
+ setIsAuthenticating(true);
227
+ await setActiveWallet(wallet);
228
+ // Try to authenticate user (will use re-authenticate if session exists)
229
+ // If no session exists, authentication will need to happen via Turnkey flow
230
+ try {
231
+ const userAuth = await authenticateUser();
232
+ if (userAuth && onConnectCallback) {
233
+ await onConnectCallback(wallet, userAuth.accessToken);
234
+ }
235
+ }
236
+ catch (authError) {
237
+ // Authentication failed - this is expected if user hasn't authenticated via Turnkey yet
238
+ // The Turnkey auth modal should handle this
239
+ debug("@@useAuth:onConnect:authFailed", { authError });
240
+ // Don't set isAuthenticated to false here - let the Turnkey flow handle it
241
+ }
242
+ }
243
+ catch (error) {
244
+ debug("@@useAuth:onConnect:failed", { error });
245
+ setIsAuthenticated(false);
246
+ setUser(undefined);
247
+ }
248
+ finally {
249
+ setIsAuthenticating(false);
250
+ }
251
+ debug({
252
+ isAuthenticated,
253
+ isAuthenticating,
254
+ isConnected,
255
+ });
256
+ }, [
257
+ onConnectCallback,
258
+ authenticateUser,
259
+ isAuthenticated,
260
+ isAuthenticating,
261
+ isConnected,
262
+ setActiveWallet,
263
+ setHasStartedConnecting,
264
+ setIsAuthenticated,
265
+ setIsAuthenticating,
266
+ setIsConnected,
267
+ setUser,
268
+ ]);
269
+ const logout = useCallback(async (callback) => {
270
+ if (activeWallet) {
271
+ debug("@@logout:activeWallet", activeWallet);
272
+ disconnect(activeWallet);
273
+ debug("@@logout:activeWallet", activeWallet);
274
+ }
275
+ // Log out of each wallet
276
+ wallets.forEach(wallet => {
277
+ console.log("@@logging out", wallet);
278
+ disconnect(wallet);
279
+ });
280
+ // Delete localStorage thirdweb:connected-wallet-ids
281
+ // https://npc-labs.slack.com/archives/C070E6HNG85/p1750185115273099
282
+ if (typeof localStorage !== "undefined") {
283
+ localStorage.removeItem("thirdweb:connected-wallet-ids");
284
+ localStorage.removeItem("wagmi.store");
285
+ localStorage.removeItem("lastAuthProvider");
286
+ localStorage.removeItem("b3-user");
287
+ }
288
+ app.logout();
289
+ debug("@@logout:loggedOut");
290
+ setIsAuthenticated(false);
291
+ setIsConnected(false);
292
+ setUser();
293
+ callback?.();
294
+ }, [activeWallet, disconnect, wallets, setIsAuthenticated, setUser, setIsConnected]);
295
+ const { isLoading: useAutoConnectLoading } = useAutoConnect({
296
+ client,
297
+ wallets: [wallet],
298
+ onConnect,
299
+ onTimeout: () => {
300
+ logout().catch(error => {
301
+ debug("@@useAuth:logout on timeout failed", { error });
302
+ });
303
+ },
304
+ });
305
+ /**
306
+ * useAutoConnectLoading starts as false
307
+ */
308
+ useEffect(() => {
309
+ if (!useAutoConnectLoading && useAutoConnectLoadingPrevious.current && !hasStartedConnecting) {
310
+ setIsAuthenticating(false);
311
+ }
312
+ useAutoConnectLoadingPrevious.current = useAutoConnectLoading;
313
+ }, [useAutoConnectLoading, hasStartedConnecting, setIsAuthenticating]);
314
+ const isReady = isAuthenticated && !isAuthenticating;
315
+ return {
316
+ authenticate,
317
+ reAuthenticate,
318
+ logout,
319
+ isAuthenticated,
320
+ isReady,
321
+ isConnecting,
322
+ isConnected,
323
+ wallet,
324
+ preAuthenticate,
325
+ connect: onConnect,
326
+ isAuthenticating,
327
+ onConnect,
328
+ user,
329
+ refetchUser: authenticateUser,
330
+ setUser,
331
+ };
332
+ }
@@ -63,6 +63,6 @@ export declare function useAuthentication(partnerId: string): {
63
63
  turnkeyOtpId?: string | undefined;
64
64
  };
65
65
  } | undefined;
66
- refetchUser: (wallet?: Wallet) => Promise<import("@feathersjs/authentication").AuthenticationResult>;
66
+ refetchUser: () => Promise<import("@feathersjs/authentication").AuthenticationResult>;
67
67
  setUser: (newUser?: import("@b3dotfun/b3-api").Users) => void;
68
68
  };
@@ -12,7 +12,7 @@ import { preAuthenticate } from "thirdweb/wallets/in-app";
12
12
  import { useAccount, useConnect, useSwitchAccount } from "wagmi";
13
13
  import { LocalSDKContext } from "../components/B3Provider/LocalSDKProvider.js";
14
14
  import { createWagmiConfig } from "../utils/createWagmiConfig.js";
15
- import { useTWAuth } from "./useTWAuth.js";
15
+ import { useAuth } from "./useAuth.js";
16
16
  import { useUserQuery } from "./useUserQuery.js";
17
17
  const debug = debugB3React("useAuthentication");
18
18
  export function useAuthentication(partnerId) {
@@ -30,7 +30,7 @@ export function useAuthentication(partnerId) {
30
30
  const setHasStartedConnecting = useAuthStore(state => state.setHasStartedConnecting);
31
31
  const setActiveWallet = useSetActiveWallet();
32
32
  const hasStartedConnecting = useAuthStore(state => state.hasStartedConnecting);
33
- const { authenticate } = useTWAuth();
33
+ const { reAuthenticate } = useAuth();
34
34
  const { user, setUser } = useUserQuery();
35
35
  const useAutoConnectLoadingPrevious = useRef(false);
36
36
  const wagmiConfig = createWagmiConfig({ partnerId });
@@ -90,18 +90,19 @@ export function useAuthentication(partnerId) {
90
90
  useEffect(() => {
91
91
  syncWagmi();
92
92
  }, [wallets, syncWagmi]);
93
- const authenticateUser = useCallback(async (wallet) => {
93
+ /**
94
+ * Authenticate user using Turnkey
95
+ * Note: This no longer requires a wallet for authentication.
96
+ * Wallets are still used for signing transactions, but authentication is done via Turnkey email OTP.
97
+ *
98
+ * For backward compatibility, this function still accepts a wallet parameter,
99
+ * but it's not used for authentication anymore.
100
+ */
101
+ const authenticateUser = useCallback(async () => {
94
102
  setHasStartedConnecting(true);
95
- if (!wallet) {
96
- throw new Error("No wallet found during auto-connect");
97
- }
98
- const account = wallet ? wallet.getAccount() : activeWallet?.getAccount();
99
- if (!account) {
100
- throw new Error("No account found during auto-connect");
101
- }
102
103
  // Try to re-authenticate first
103
104
  try {
104
- const userAuth = await app.reAuthenticate();
105
+ const userAuth = await reAuthenticate();
105
106
  setUser(userAuth.user);
106
107
  setIsAuthenticated(true);
107
108
  setIsAuthenticating(false);
@@ -112,19 +113,19 @@ export function useAuthentication(partnerId) {
112
113
  return userAuth;
113
114
  }
114
115
  catch (error) {
115
- // If re-authentication fails, try fresh authentication
116
- debug("Re-authentication failed, attempting fresh authentication");
117
- const userAuth = await authenticate(wallet, partnerId);
118
- setUser(userAuth.user);
119
- setIsAuthenticated(true);
116
+ // If re-authentication fails, user needs to authenticate via Turnkey
117
+ // This should be handled by the Turnkey auth modal/flow
118
+ debug("Re-authentication failed. User needs to authenticate via Turnkey.", error);
119
+ setIsAuthenticated(false);
120
120
  setIsAuthenticating(false);
121
- debug("Fresh authentication successful", { userAuth });
122
- // Authenticate on BSMNT with B3 JWT
123
- const b3Jwt = await authenticateWithB3JWT(userAuth.accessToken);
124
- debug("@@b3Jwt", b3Jwt);
125
- return userAuth;
121
+ throw new Error("Authentication required. Please authenticate via Turnkey.");
126
122
  }
127
- }, [activeWallet, partnerId, authenticate, setIsAuthenticated, setIsAuthenticating, setUser, setHasStartedConnecting]);
123
+ }, [reAuthenticate, setIsAuthenticated, setIsAuthenticating, setUser, setHasStartedConnecting]);
124
+ /**
125
+ * Handle wallet connection
126
+ * Note: With Turnkey migration, wallet connection is primarily for signing transactions,
127
+ * not for authentication. Authentication should be done separately via Turnkey email OTP.
128
+ */
128
129
  const onConnect = useCallback(async (_walleAutoConnectedWith, allConnectedWallets) => {
129
130
  debug("@@useAuthentication:onConnect", { _walleAutoConnectedWith, allConnectedWallets });
130
131
  const wallet = allConnectedWallets.find(wallet => wallet.id.startsWith("ecosystem."));
@@ -137,9 +138,19 @@ export function useAuthentication(partnerId) {
137
138
  setIsConnected(true);
138
139
  setIsAuthenticating(true);
139
140
  await setActiveWallet(wallet);
140
- const userAuth = await authenticateUser(wallet);
141
- if (userAuth && onConnectCallback) {
142
- await onConnectCallback(wallet, userAuth.accessToken);
141
+ // Try to authenticate user (will use re-authenticate if session exists)
142
+ // If no session exists, authentication will need to happen via Turnkey flow
143
+ try {
144
+ const userAuth = await authenticateUser();
145
+ if (userAuth && onConnectCallback) {
146
+ await onConnectCallback(wallet, userAuth.accessToken);
147
+ }
148
+ }
149
+ catch (authError) {
150
+ // Authentication failed - this is expected if user hasn't authenticated via Turnkey yet
151
+ // The Turnkey auth modal should handle this
152
+ debug("@@useAuthentication:onConnect:authFailed", { authError });
153
+ // Don't set isAuthenticated to false here - let the Turnkey flow handle it
143
154
  }
144
155
  }
145
156
  catch (error) {
@@ -1,4 +1,7 @@
1
1
  import { Wallet } from "thirdweb/wallets";
2
+ /**
3
+ * @deprecated Use useAuth() with Turnkey authentication instead
4
+ */
2
5
  export declare function useTWAuth(): {
3
6
  authenticate: (wallet: Wallet, partnerId: string) => Promise<import("@feathersjs/authentication").AuthenticationResult>;
4
7
  };
@@ -1,8 +1,16 @@
1
+ /**
2
+ * @deprecated This hook is deprecated. Use useAuth() with Turnkey authentication instead.
3
+ * This file is kept for backward compatibility but should not be used in new code.
4
+ */
1
5
  import app from "../../../global-account/app.js";
2
6
  import debug from "../../../shared/utils/debug.js";
3
7
  import { useCallback } from "react";
4
8
  import { useSearchParam } from "./useSearchParamsSSR.js";
9
+ /**
10
+ * @deprecated Use useAuth() with Turnkey authentication instead
11
+ */
5
12
  export function useTWAuth() {
13
+ console.warn("useTWAuth is deprecated. Please migrate to useAuth() with Turnkey authentication. See useTurnkeyAuth.ts for the new implementation.");
6
14
  const referralCode = useSearchParam("referralCode");
7
15
  const authenticate = useCallback(async (wallet, partnerId) => {
8
16
  if (!wallet || !wallet?.getAuthToken?.())
@@ -1,8 +1,9 @@
1
- import app from "../../app.js";
2
- import { useAuthStore } from "../stores/index.js";
1
+ import { debugB3React } from "../../../shared/utils/debug.js";
3
2
  import { useCallback, useState } from "react";
3
+ import app from "../../app.js";
4
4
  import { useB3 } from "../components/B3Provider/useB3.js";
5
- import { debugB3React } from "../../../shared/utils/debug.js";
5
+ import { useAuthStore } from "../stores/index.js";
6
+ import { useAuth } from "./useAuth.js";
6
7
  const debug = debugB3React("useTurnkeyAuth");
7
8
  /**
8
9
  * Hook for Turnkey email-based OTP authentication
@@ -17,29 +18,55 @@ export function useTurnkeyAuth() {
17
18
  const [error, setError] = useState(null);
18
19
  const setIsAuthenticating = useAuthStore(state => state.setIsAuthenticating);
19
20
  const setIsAuthenticated = useAuthStore(state => state.setIsAuthenticated);
20
- const { user } = useB3();
21
+ const { partnerId } = useB3();
22
+ const { authenticate } = useAuth();
21
23
  /**
22
24
  * Step 1: Initiate login with email
23
- * - Calls backend to create sub-org (if needed) and send OTP
25
+ * - Calls backend turnkey-jwt strategy (init action) to create sub-org (if needed) and send OTP
24
26
  * - Returns otpId to use in verification step
27
+ *
28
+ * Note: Uses the turnkey-jwt authentication strategy, not the service directly.
29
+ * The turnkey-jwt strategy handles both OTP flow (init/verify) and final authentication.
25
30
  */
26
31
  const initiateLogin = useCallback(async (email) => {
27
32
  setIsLoading(true);
28
33
  setError(null);
29
34
  setIsAuthenticating(true);
30
35
  try {
31
- if (!user?.userId) {
32
- throw new Error("User ID is required to initiate Turnkey login.");
33
- }
34
36
  debug(`Initiating login for: ${email}`);
35
- // Call FeathersJS service to initialize OTP
36
- const data = await app.service("turnkey-auth").init({ email, userId: user.userId });
37
+ // Use authentication service with turnkey-jwt strategy (init action)
38
+ // userId is resolved from authentication context on the backend (params.user.userId)
39
+ // Backend will get userId from _params.user?.userId if authenticated, or handle unauthenticated case
40
+ // So we only need to send email
41
+ debug(`Calling app.authenticate with turnkey-jwt strategy (init action)`, { email });
42
+ const response = await app.authenticate({
43
+ strategy: "turnkey-jwt",
44
+ action: "init",
45
+ email,
46
+ });
47
+ // The strategy returns the TurnkeyAuthInitResponse directly
48
+ const data = response;
37
49
  debug(`OTP initialized successfully. OtpId: ${data.otpId}`);
38
50
  return data;
39
51
  }
40
52
  catch (err) {
41
53
  debug("Error initiating login:", err);
42
- const errorMessage = err.message || "Failed to send OTP email. Please try again.";
54
+ // Provide more detailed error information
55
+ let errorMessage = "Failed to send OTP email. Please try again.";
56
+ if (err.message) {
57
+ errorMessage = err.message;
58
+ }
59
+ else if (err.name === "TypeError" && err.message?.includes("fetch")) {
60
+ errorMessage = "Network error: Unable to reach the server. Please check your connection and try again.";
61
+ }
62
+ else if (err.code === "ECONNREFUSED" || err.code === "ENOTFOUND") {
63
+ errorMessage = "Connection error: Unable to reach the server. Please check your internet connection.";
64
+ }
65
+ else if (err.response) {
66
+ // FeathersJS error response
67
+ errorMessage = err.response.message || err.message || errorMessage;
68
+ debug("FeathersJS error response:", err.response);
69
+ }
43
70
  setError(errorMessage);
44
71
  throw err;
45
72
  }
@@ -47,11 +74,11 @@ export function useTurnkeyAuth() {
47
74
  setIsLoading(false);
48
75
  setIsAuthenticating(false);
49
76
  }
50
- }, [user, setIsAuthenticating]);
77
+ }, [setIsAuthenticating]);
51
78
  /**
52
79
  * Step 2: Verify OTP and authenticate
53
- * - Verifies OTP with backend
54
- * - Gets Turnkey session JWT
80
+ * - Verifies OTP with backend via turnkey-jwt strategy (verify action)
81
+ * - Gets Turnkey session JWT from the verify response
55
82
  * - Authenticates with b3-api using "turnkey-jwt" strategy
56
83
  * - JWT automatically stored in cookies by SDK
57
84
  */
@@ -60,19 +87,22 @@ export function useTurnkeyAuth() {
60
87
  setError(null);
61
88
  setIsAuthenticating(true);
62
89
  try {
63
- debug(`Verifying OTP...`, { userId: user?.userId });
64
- // Step 1: Verify OTP and get Turnkey session JWT
65
- const { turnkeySessionJwt } = await app.service("turnkey-auth").verify({
90
+ debug(`Verifying OTP...`, { otpId });
91
+ // Step 1: Verify OTP with backend using turnkey-jwt strategy (verify action)
92
+ // This returns the Turnkey session JWT
93
+ const response = await app.authenticate({
94
+ strategy: "turnkey-jwt",
95
+ action: "verify",
66
96
  otpId,
67
97
  otpCode,
68
98
  });
69
- debug(`OTP verified! Authenticating with b3-api...`);
99
+ // The strategy returns the TurnkeyAuthVerifyResponse directly
100
+ const verifyResult = response;
101
+ const { turnkeySessionJwt } = verifyResult;
102
+ debug(`OTP verified! Got Turnkey session JWT. Authenticating with b3-api...`);
70
103
  // Step 2: Authenticate with b3-api using Turnkey JWT
71
- // The SDK will automatically store the b3-api JWT in cookies
72
- const authResult = await app.authenticate({
73
- strategy: "turnkey-jwt",
74
- accessToken: turnkeySessionJwt,
75
- });
104
+ // Use the unified useAuth hook for authentication with "turnkey-jwt" strategy
105
+ const authResult = await authenticate(turnkeySessionJwt, partnerId || "");
76
106
  debug(`Successfully authenticated with b3-api!`, authResult);
77
107
  // Update auth store to reflect authenticated state
78
108
  setIsAuthenticated(true);
@@ -92,7 +122,7 @@ export function useTurnkeyAuth() {
92
122
  setIsLoading(false);
93
123
  setIsAuthenticating(false);
94
124
  }
95
- }, [user, setIsAuthenticating, setIsAuthenticated]);
125
+ }, [partnerId, setIsAuthenticating, setIsAuthenticated, authenticate]);
96
126
  const clearError = useCallback(() => {
97
127
  setError(null);
98
128
  }, []);
@@ -3,6 +3,7 @@ export { useAccountAssets } from "./useAccountAssets";
3
3
  export { useAccountWallet } from "./useAccountWallet";
4
4
  export { useAddTWSessionKey } from "./useAddTWSessionKey";
5
5
  export { useAnalytics } from "./useAnalytics";
6
+ export { useAuth } from "./useAuth";
6
7
  export { useAuthentication } from "./useAuthentication";
7
8
  export { useB3BalanceFromAddresses } from "./useB3BalanceFromAddresses";
8
9
  export { useB3EnsName } from "./useB3EnsName";