@b3dotfun/sdk 0.0.82-alpha.3 → 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 (53) hide show
  1. package/dist/cjs/anyspend/react/components/AnySpend.js +3 -0
  2. package/dist/cjs/anyspend/react/components/AnySpendCustom.js +3 -0
  3. package/dist/cjs/anyspend/react/components/common/CryptoPaymentMethod.js +177 -47
  4. package/dist/cjs/anyspend/react/hooks/useAnyspendFlow.js +3 -0
  5. package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
  6. package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +73 -0
  7. package/dist/cjs/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +57 -12
  8. package/dist/cjs/global-account/react/hooks/index.d.ts +1 -0
  9. package/dist/cjs/global-account/react/hooks/index.js +3 -1
  10. package/dist/cjs/global-account/react/hooks/useAuth.d.ts +76 -0
  11. package/dist/cjs/global-account/react/hooks/useAuth.js +338 -0
  12. package/dist/cjs/global-account/react/hooks/useAuthentication.d.ts +2 -2
  13. package/dist/cjs/global-account/react/hooks/useAuthentication.js +72 -63
  14. package/dist/cjs/global-account/react/hooks/useTWAuth.d.ts +3 -0
  15. package/dist/cjs/global-account/react/hooks/useTWAuth.js +8 -0
  16. package/dist/cjs/global-account/react/hooks/useTurnkeyAuth.js +54 -24
  17. package/dist/cjs/global-account/react/hooks/useUserQuery.d.ts +1 -1
  18. package/dist/esm/anyspend/react/components/AnySpend.js +3 -0
  19. package/dist/esm/anyspend/react/components/AnySpendCustom.js +3 -0
  20. package/dist/esm/anyspend/react/components/common/CryptoPaymentMethod.js +175 -45
  21. package/dist/esm/anyspend/react/hooks/useAnyspendFlow.js +3 -0
  22. package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
  23. package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +70 -0
  24. package/dist/esm/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +57 -12
  25. package/dist/esm/global-account/react/hooks/index.d.ts +1 -0
  26. package/dist/esm/global-account/react/hooks/index.js +1 -0
  27. package/dist/esm/global-account/react/hooks/useAuth.d.ts +76 -0
  28. package/dist/esm/global-account/react/hooks/useAuth.js +332 -0
  29. package/dist/esm/global-account/react/hooks/useAuthentication.d.ts +2 -2
  30. package/dist/esm/global-account/react/hooks/useAuthentication.js +72 -63
  31. package/dist/esm/global-account/react/hooks/useTWAuth.d.ts +3 -0
  32. package/dist/esm/global-account/react/hooks/useTWAuth.js +8 -0
  33. package/dist/esm/global-account/react/hooks/useTurnkeyAuth.js +54 -24
  34. package/dist/esm/global-account/react/hooks/useUserQuery.d.ts +1 -1
  35. package/dist/styles/index.css +1 -1
  36. package/dist/types/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
  37. package/dist/types/global-account/react/hooks/index.d.ts +1 -0
  38. package/dist/types/global-account/react/hooks/useAuth.d.ts +76 -0
  39. package/dist/types/global-account/react/hooks/useAuthentication.d.ts +2 -2
  40. package/dist/types/global-account/react/hooks/useTWAuth.d.ts +3 -0
  41. package/dist/types/global-account/react/hooks/useUserQuery.d.ts +1 -1
  42. package/package.json +1 -1
  43. package/src/anyspend/react/components/AnySpend.tsx +4 -0
  44. package/src/anyspend/react/components/AnySpendCustom.tsx +4 -0
  45. package/src/anyspend/react/components/common/CryptoPaymentMethod.tsx +253 -22
  46. package/src/anyspend/react/hooks/useAnyspendFlow.ts +4 -0
  47. package/src/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.ts +80 -0
  48. package/src/global-account/react/components/SignInWithB3/SignInWithB3Flow.tsx +77 -22
  49. package/src/global-account/react/hooks/index.ts +1 -0
  50. package/src/global-account/react/hooks/useAuth.ts +380 -0
  51. package/src/global-account/react/hooks/useAuthentication.ts +88 -85
  52. package/src/global-account/react/hooks/useTWAuth.tsx +10 -0
  53. package/src/global-account/react/hooks/useTurnkeyAuth.ts +59 -26
@@ -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,67 +113,50 @@ 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;
126
- }
127
- }, [activeWallet, partnerId, authenticate, setIsAuthenticated, setIsAuthenticating, setUser, setHasStartedConnecting]);
128
- const logout = useCallback(async (callback) => {
129
- if (activeWallet) {
130
- debug("@@logout:activeWallet", activeWallet);
131
- disconnect(activeWallet);
132
- debug("@@logout:activeWallet", activeWallet);
121
+ throw new Error("Authentication required. Please authenticate via Turnkey.");
133
122
  }
134
- // Log out of each wallet
135
- wallets.forEach(wallet => {
136
- console.log("@@logging out", wallet);
137
- disconnect(wallet);
138
- });
139
- // Delete localStorage thirdweb:connected-wallet-ids
140
- // https://npc-labs.slack.com/archives/C070E6HNG85/p1750185115273099
141
- if (typeof localStorage !== "undefined") {
142
- localStorage.removeItem("thirdweb:connected-wallet-ids");
143
- localStorage.removeItem("wagmi.store");
144
- localStorage.removeItem("lastAuthProvider");
145
- localStorage.removeItem("b3-user");
146
- }
147
- app.logout();
148
- debug("@@logout:loggedOut");
149
- setIsAuthenticated(false);
150
- setIsConnected(false);
151
- setUser();
152
- callback?.();
153
- }, [activeWallet, disconnect, wallets, setIsAuthenticated, setUser, setIsConnected]);
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
+ */
154
129
  const onConnect = useCallback(async (_walleAutoConnectedWith, allConnectedWallets) => {
155
130
  debug("@@useAuthentication:onConnect", { _walleAutoConnectedWith, allConnectedWallets });
131
+ const wallet = allConnectedWallets.find(wallet => wallet.id.startsWith("ecosystem."));
132
+ if (!wallet) {
133
+ throw new Error("No smart wallet found during auto-connect");
134
+ }
135
+ debug("@@useAuthentication:onConnect", { wallet });
156
136
  try {
157
- const wallet = allConnectedWallets.find(wallet => wallet.id.startsWith("ecosystem."));
158
- if (!wallet) {
159
- throw new Error("No smart wallet found during auto-connect");
160
- }
161
- debug("@@useAuthentication:onConnect", { wallet });
162
137
  setHasStartedConnecting(true);
163
138
  setIsConnected(true);
164
139
  setIsAuthenticating(true);
165
140
  await setActiveWallet(wallet);
166
- const userAuth = await authenticateUser(wallet);
167
- if (userAuth && onConnectCallback) {
168
- 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
169
154
  }
170
155
  }
171
156
  catch (error) {
172
157
  debug("@@useAuthentication:onConnect:failed", { error });
173
158
  setIsAuthenticated(false);
174
159
  setUser(undefined);
175
- await logout();
176
160
  }
177
161
  finally {
178
162
  setIsAuthenticating(false);
@@ -183,19 +167,44 @@ export function useAuthentication(partnerId) {
183
167
  isConnected,
184
168
  });
185
169
  }, [
170
+ onConnectCallback,
171
+ authenticateUser,
186
172
  isAuthenticated,
187
173
  isAuthenticating,
188
174
  isConnected,
189
- setHasStartedConnecting,
190
- setIsConnected,
191
- setIsAuthenticating,
192
175
  setActiveWallet,
193
- authenticateUser,
194
- onConnectCallback,
176
+ setHasStartedConnecting,
195
177
  setIsAuthenticated,
178
+ setIsAuthenticating,
179
+ setIsConnected,
196
180
  setUser,
197
- logout,
198
181
  ]);
182
+ const logout = useCallback(async (callback) => {
183
+ if (activeWallet) {
184
+ debug("@@logout:activeWallet", activeWallet);
185
+ disconnect(activeWallet);
186
+ debug("@@logout:activeWallet", activeWallet);
187
+ }
188
+ // Log out of each wallet
189
+ wallets.forEach(wallet => {
190
+ console.log("@@logging out", wallet);
191
+ disconnect(wallet);
192
+ });
193
+ // Delete localStorage thirdweb:connected-wallet-ids
194
+ // https://npc-labs.slack.com/archives/C070E6HNG85/p1750185115273099
195
+ if (typeof localStorage !== "undefined") {
196
+ localStorage.removeItem("thirdweb:connected-wallet-ids");
197
+ localStorage.removeItem("wagmi.store");
198
+ localStorage.removeItem("lastAuthProvider");
199
+ localStorage.removeItem("b3-user");
200
+ }
201
+ app.logout();
202
+ debug("@@logout:loggedOut");
203
+ setIsAuthenticated(false);
204
+ setIsConnected(false);
205
+ setUser();
206
+ callback?.();
207
+ }, [activeWallet, disconnect, wallets, setIsAuthenticated, setUser, setIsConnected]);
199
208
  const { isLoading: useAutoConnectLoading } = useAutoConnect({
200
209
  client,
201
210
  wallets: [wallet],
@@ -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
  }, []);
@@ -36,8 +36,8 @@ export declare function useUserQuery(): {
36
36
  name?: string | undefined;
37
37
  address?: string | undefined;
38
38
  email?: string | undefined;
39
- username?: string | undefined;
40
39
  phone?: string | undefined;
40
+ username?: string | undefined;
41
41
  fid?: string | undefined;
42
42
  };
43
43
  }[] | undefined;