@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
@@ -19,7 +19,7 @@ import { preAuthenticate } from "thirdweb/wallets/in-app";
19
19
  import { useAccount, useConnect, useSwitchAccount } from "wagmi";
20
20
  import { LocalSDKContext } from "../components/B3Provider/LocalSDKProvider";
21
21
  import { createWagmiConfig } from "../utils/createWagmiConfig";
22
- import { useTWAuth } from "./useTWAuth";
22
+ import { useAuth } from "./useAuth";
23
23
  import { useUserQuery } from "./useUserQuery";
24
24
 
25
25
  const debug = debugB3React("useAuthentication");
@@ -39,7 +39,7 @@ export function useAuthentication(partnerId: string) {
39
39
  const setHasStartedConnecting = useAuthStore(state => state.setHasStartedConnecting);
40
40
  const setActiveWallet = useSetActiveWallet();
41
41
  const hasStartedConnecting = useAuthStore(state => state.hasStartedConnecting);
42
- const { authenticate } = useTWAuth();
42
+ const { reAuthenticate } = useAuth();
43
43
  const { user, setUser } = useUserQuery();
44
44
  const useAutoConnectLoadingPrevious = useRef(false);
45
45
  const wagmiConfig = createWagmiConfig({ partnerId });
@@ -106,51 +106,45 @@ export function useAuthentication(partnerId: string) {
106
106
  syncWagmi();
107
107
  }, [wallets, syncWagmi]);
108
108
 
109
- const authenticateUser = useCallback(
110
- async (wallet?: Wallet) => {
111
- setHasStartedConnecting(true);
112
-
113
- if (!wallet) {
114
- throw new Error("No wallet found during auto-connect");
115
- }
116
-
117
- const account = wallet ? wallet.getAccount() : activeWallet?.getAccount();
118
- if (!account) {
119
- throw new Error("No account found during auto-connect");
120
- }
121
-
122
- // Try to re-authenticate first
123
- try {
124
- const userAuth = await app.reAuthenticate();
125
- setUser(userAuth.user);
126
- setIsAuthenticated(true);
127
- setIsAuthenticating(false);
128
- debug("Re-authenticated successfully", { userAuth });
129
-
130
- // Authenticate on BSMNT with B3 JWT
131
- const b3Jwt = await authenticateWithB3JWT(userAuth.accessToken);
132
- debug("@@b3Jwt", b3Jwt);
133
-
134
- return userAuth;
135
- } catch (error) {
136
- // If re-authentication fails, try fresh authentication
137
- debug("Re-authentication failed, attempting fresh authentication");
138
- const userAuth = await authenticate(wallet, partnerId);
139
- setUser(userAuth.user);
140
- setIsAuthenticated(true);
141
- setIsAuthenticating(false);
142
- debug("Fresh authentication successful", { userAuth });
109
+ /**
110
+ * Authenticate user using Turnkey
111
+ * Note: This no longer requires a wallet for authentication.
112
+ * Wallets are still used for signing transactions, but authentication is done via Turnkey email OTP.
113
+ *
114
+ * For backward compatibility, this function still accepts a wallet parameter,
115
+ * but it's not used for authentication anymore.
116
+ */
117
+ const authenticateUser = useCallback(async () => {
118
+ setHasStartedConnecting(true);
119
+
120
+ // Try to re-authenticate first
121
+ try {
122
+ const userAuth = await reAuthenticate();
123
+ setUser(userAuth.user);
124
+ setIsAuthenticated(true);
125
+ setIsAuthenticating(false);
126
+ debug("Re-authenticated successfully", { userAuth });
143
127
 
144
- // Authenticate on BSMNT with B3 JWT
145
- const b3Jwt = await authenticateWithB3JWT(userAuth.accessToken);
146
- debug("@@b3Jwt", b3Jwt);
128
+ // Authenticate on BSMNT with B3 JWT
129
+ const b3Jwt = await authenticateWithB3JWT(userAuth.accessToken);
130
+ debug("@@b3Jwt", b3Jwt);
147
131
 
148
- return userAuth;
149
- }
150
- },
151
- [activeWallet, partnerId, authenticate, setIsAuthenticated, setIsAuthenticating, setUser, setHasStartedConnecting],
152
- );
132
+ return userAuth;
133
+ } catch (error) {
134
+ // If re-authentication fails, user needs to authenticate via Turnkey
135
+ // This should be handled by the Turnkey auth modal/flow
136
+ debug("Re-authentication failed. User needs to authenticate via Turnkey.", error);
137
+ setIsAuthenticated(false);
138
+ setIsAuthenticating(false);
139
+ throw new Error("Authentication required. Please authenticate via Turnkey.");
140
+ }
141
+ }, [reAuthenticate, setIsAuthenticated, setIsAuthenticating, setUser, setHasStartedConnecting]);
153
142
 
143
+ /**
144
+ * Handle wallet connection
145
+ * Note: With Turnkey migration, wallet connection is primarily for signing transactions,
146
+ * not for authentication. Authentication should be done separately via Turnkey email OTP.
147
+ */
154
148
  const onConnect = useCallback(
155
149
  async (_walleAutoConnectedWith: Wallet, allConnectedWallets: Wallet[]) => {
156
150
  debug("@@useAuthentication:onConnect", { _walleAutoConnectedWith, allConnectedWallets });
@@ -168,10 +162,20 @@ export function useAuthentication(partnerId: string) {
168
162
  setIsConnected(true);
169
163
  setIsAuthenticating(true);
170
164
  await setActiveWallet(wallet);
171
- const userAuth = await authenticateUser(wallet);
172
165
 
173
- if (userAuth && onConnectCallback) {
174
- await onConnectCallback(wallet, userAuth.accessToken);
166
+ // Try to authenticate user (will use re-authenticate if session exists)
167
+ // If no session exists, authentication will need to happen via Turnkey flow
168
+ try {
169
+ const userAuth = await authenticateUser();
170
+
171
+ if (userAuth && onConnectCallback) {
172
+ await onConnectCallback(wallet, userAuth.accessToken);
173
+ }
174
+ } catch (authError) {
175
+ // Authentication failed - this is expected if user hasn't authenticated via Turnkey yet
176
+ // The Turnkey auth modal should handle this
177
+ debug("@@useAuthentication:onConnect:authFailed", { authError });
178
+ // Don't set isAuthenticated to false here - let the Turnkey flow handle it
175
179
  }
176
180
  } catch (error) {
177
181
  debug("@@useAuthentication:onConnect:failed", { error });
@@ -1,10 +1,20 @@
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 "@b3dotfun/sdk/global-account/app";
2
6
  import debug from "@b3dotfun/sdk/shared/utils/debug";
3
7
  import { useCallback } from "react";
4
8
  import { Wallet } from "thirdweb/wallets";
5
9
  import { useSearchParam } from "./useSearchParamsSSR";
6
10
 
11
+ /**
12
+ * @deprecated Use useAuth() with Turnkey authentication instead
13
+ */
7
14
  export function useTWAuth() {
15
+ console.warn(
16
+ "useTWAuth is deprecated. Please migrate to useAuth() with Turnkey authentication. See useTurnkeyAuth.ts for the new implementation.",
17
+ );
8
18
  const referralCode = useSearchParam("referralCode");
9
19
 
10
20
  const authenticate = useCallback(
@@ -1,9 +1,10 @@
1
- import app from "../../app";
2
- import { useAuthStore } from "../stores";
3
- import { useCallback, useState } from "react";
4
- import { useB3 } from "../components/B3Provider/useB3";
5
1
  import { TurnkeyAuthInitResponse } from "@b3dotfun/b3-api";
6
2
  import { debugB3React } from "@b3dotfun/sdk/shared/utils/debug";
3
+ import { useCallback, useState } from "react";
4
+ import app from "../../app";
5
+ import { useB3 } from "../components/B3Provider/useB3";
6
+ import { useAuthStore } from "../stores";
7
+ import { useAuth } from "./useAuth";
7
8
 
8
9
  const debug = debugB3React("useTurnkeyAuth");
9
10
 
@@ -32,12 +33,16 @@ export function useTurnkeyAuth(): UseTurnkeyAuthReturn {
32
33
  const [error, setError] = useState<string | null>(null);
33
34
  const setIsAuthenticating = useAuthStore(state => state.setIsAuthenticating);
34
35
  const setIsAuthenticated = useAuthStore(state => state.setIsAuthenticated);
35
- const { user } = useB3();
36
+ const { partnerId } = useB3();
37
+ const { authenticate } = useAuth();
36
38
 
37
39
  /**
38
40
  * Step 1: Initiate login with email
39
- * - Calls backend to create sub-org (if needed) and send OTP
41
+ * - Calls backend turnkey-jwt strategy (init action) to create sub-org (if needed) and send OTP
40
42
  * - Returns otpId to use in verification step
43
+ *
44
+ * Note: Uses the turnkey-jwt authentication strategy, not the service directly.
45
+ * The turnkey-jwt strategy handles both OTP flow (init/verify) and final authentication.
41
46
  */
42
47
  const initiateLogin = useCallback(
43
48
  async (email: string): Promise<TurnkeyAuthInitResponse> => {
@@ -46,20 +51,44 @@ export function useTurnkeyAuth(): UseTurnkeyAuthReturn {
46
51
  setIsAuthenticating(true);
47
52
 
48
53
  try {
49
- if (!user?.userId) {
50
- throw new Error("User ID is required to initiate Turnkey login.");
51
- }
52
54
  debug(`Initiating login for: ${email}`);
53
55
 
54
- // Call FeathersJS service to initialize OTP
55
- const data: TurnkeyAuthInitResponse = await app.service("turnkey-auth").init({ email, userId: user.userId });
56
+ // Use authentication service with turnkey-jwt strategy (init action)
57
+ // userId is resolved from authentication context on the backend (params.user.userId)
58
+ // Backend will get userId from _params.user?.userId if authenticated, or handle unauthenticated case
59
+ // So we only need to send email
60
+ debug(`Calling app.authenticate with turnkey-jwt strategy (init action)`, { email });
61
+
62
+ const response = await app.authenticate({
63
+ strategy: "turnkey-jwt",
64
+ action: "init",
65
+ email,
66
+ } as any);
67
+
68
+ // The strategy returns the TurnkeyAuthInitResponse directly
69
+ const data = response as unknown as TurnkeyAuthInitResponse;
56
70
 
57
71
  debug(`OTP initialized successfully. OtpId: ${data.otpId}`);
58
72
 
59
73
  return data;
60
74
  } catch (err: any) {
61
75
  debug("Error initiating login:", err);
62
- const errorMessage = err.message || "Failed to send OTP email. Please try again.";
76
+
77
+ // Provide more detailed error information
78
+ let errorMessage = "Failed to send OTP email. Please try again.";
79
+
80
+ if (err.message) {
81
+ errorMessage = err.message;
82
+ } else if (err.name === "TypeError" && err.message?.includes("fetch")) {
83
+ errorMessage = "Network error: Unable to reach the server. Please check your connection and try again.";
84
+ } else if (err.code === "ECONNREFUSED" || err.code === "ENOTFOUND") {
85
+ errorMessage = "Connection error: Unable to reach the server. Please check your internet connection.";
86
+ } else if (err.response) {
87
+ // FeathersJS error response
88
+ errorMessage = err.response.message || err.message || errorMessage;
89
+ debug("FeathersJS error response:", err.response);
90
+ }
91
+
63
92
  setError(errorMessage);
64
93
  throw err;
65
94
  } finally {
@@ -67,13 +96,13 @@ export function useTurnkeyAuth(): UseTurnkeyAuthReturn {
67
96
  setIsAuthenticating(false);
68
97
  }
69
98
  },
70
- [user, setIsAuthenticating],
99
+ [setIsAuthenticating],
71
100
  );
72
101
 
73
102
  /**
74
103
  * Step 2: Verify OTP and authenticate
75
- * - Verifies OTP with backend
76
- * - Gets Turnkey session JWT
104
+ * - Verifies OTP with backend via turnkey-jwt strategy (verify action)
105
+ * - Gets Turnkey session JWT from the verify response
77
106
  * - Authenticates with b3-api using "turnkey-jwt" strategy
78
107
  * - JWT automatically stored in cookies by SDK
79
108
  */
@@ -84,22 +113,26 @@ export function useTurnkeyAuth(): UseTurnkeyAuthReturn {
84
113
  setIsAuthenticating(true);
85
114
 
86
115
  try {
87
- debug(`Verifying OTP...`, { userId: user?.userId });
116
+ debug(`Verifying OTP...`, { otpId });
88
117
 
89
- // Step 1: Verify OTP and get Turnkey session JWT
90
- const { turnkeySessionJwt }: TurnkeyVerifyResponse = await app.service("turnkey-auth").verify({
118
+ // Step 1: Verify OTP with backend using turnkey-jwt strategy (verify action)
119
+ // This returns the Turnkey session JWT
120
+ const response = await app.authenticate({
121
+ strategy: "turnkey-jwt",
122
+ action: "verify",
91
123
  otpId,
92
124
  otpCode,
93
- });
125
+ } as any);
126
+
127
+ // The strategy returns the TurnkeyAuthVerifyResponse directly
128
+ const verifyResult = response as unknown as TurnkeyVerifyResponse;
129
+ const { turnkeySessionJwt } = verifyResult;
94
130
 
95
- debug(`OTP verified! Authenticating with b3-api...`);
131
+ debug(`OTP verified! Got Turnkey session JWT. Authenticating with b3-api...`);
96
132
 
97
133
  // Step 2: Authenticate with b3-api using Turnkey JWT
98
- // The SDK will automatically store the b3-api JWT in cookies
99
- const authResult = await app.authenticate({
100
- strategy: "turnkey-jwt",
101
- accessToken: turnkeySessionJwt,
102
- } as any);
134
+ // Use the unified useAuth hook for authentication with "turnkey-jwt" strategy
135
+ const authResult = await authenticate(turnkeySessionJwt, partnerId || "");
103
136
 
104
137
  debug(`Successfully authenticated with b3-api!`, authResult);
105
138
 
@@ -121,7 +154,7 @@ export function useTurnkeyAuth(): UseTurnkeyAuthReturn {
121
154
  setIsAuthenticating(false);
122
155
  }
123
156
  },
124
- [user, setIsAuthenticating, setIsAuthenticated],
157
+ [partnerId, setIsAuthenticating, setIsAuthenticated, authenticate],
125
158
  );
126
159
 
127
160
  const clearError = useCallback(() => {