@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
@@ -6,6 +6,7 @@ const react_1 = require("../../../../global-account/react");
6
6
  const debug_1 = require("../../../../shared/utils/debug");
7
7
  const react_2 = require("react");
8
8
  const react_3 = require("thirdweb/react");
9
+ const TurnkeyAuthModal_1 = require("../TurnkeyAuthModal");
9
10
  const SignInWithB3Privy_1 = require("./SignInWithB3Privy");
10
11
  const LoginStep_1 = require("./steps/LoginStep");
11
12
  const LoginStepCustom_1 = require("./steps/LoginStepCustom");
@@ -23,7 +24,9 @@ function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySuccess, onE
23
24
  const account = (0, react_3.useActiveAccount)();
24
25
  const isAuthenticating = (0, react_1.useAuthStore)(state => state.isAuthenticating);
25
26
  const isAuthenticated = (0, react_1.useAuthStore)(state => state.isAuthenticated);
27
+ const setIsAuthenticated = (0, react_1.useAuthStore)(state => state.setIsAuthenticated);
26
28
  const isConnected = (0, react_1.useAuthStore)(state => state.isConnected);
29
+ const setIsConnected = (0, react_1.useAuthStore)(state => state.setIsConnected);
27
30
  const setJustCompletedLogin = (0, react_1.useAuthStore)(state => state.setJustCompletedLogin);
28
31
  const [refetchCount, setRefetchCount] = (0, react_2.useState)(0);
29
32
  const [refetchError, setRefetchError] = (0, react_2.useState)(null);
@@ -125,6 +128,10 @@ function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySuccess, onE
125
128
  debug("Refetching user after Turnkey success...");
126
129
  await refetchUser();
127
130
  debug("User refetched successfully");
131
+ // Set authentication and connection state so UI updates properly
132
+ setIsAuthenticated(true);
133
+ setIsConnected(true);
134
+ setJustCompletedLogin(true);
128
135
  // After user data is refreshed, close Turnkey modal and go back to sign-in flow
129
136
  debug("Switching back to signInWithB3 modal");
130
137
  setB3ModalContentType({
@@ -154,6 +161,9 @@ function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySuccess, onE
154
161
  closeAfterLogin,
155
162
  source,
156
163
  signersEnabled,
164
+ setIsAuthenticated,
165
+ setIsConnected,
166
+ setJustCompletedLogin,
157
167
  ]);
158
168
  // Handle post-login flow after signers are loaded
159
169
  (0, react_2.useEffect)(() => {
@@ -289,21 +299,56 @@ function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySuccess, onE
289
299
  if (refetchError) {
290
300
  content = ((0, jsx_runtime_1.jsx)(LoginStep_1.LoginStepContainer, { partnerId: partnerId, children: (0, jsx_runtime_1.jsx)("div", { className: "p-4 text-center text-red-500", children: refetchError }) }));
291
301
  }
292
- else if (isAuthenticating || (isFetchingSigners && step === "login") || source === "requestPermissions") {
293
- content = ((0, jsx_runtime_1.jsx)(LoginStep_1.LoginStepContainer, { partnerId: partnerId, children: (0, jsx_runtime_1.jsx)("div", { className: "my-8 flex min-h-[350px] items-center justify-center", children: (0, jsx_runtime_1.jsx)(react_1.Loading, { variant: "white", size: "lg" }) }) }));
294
- }
295
302
  else if (step === "login") {
296
- // Custom strategy
297
- if (strategies?.[0] === "privy") {
298
- content = (0, jsx_runtime_1.jsx)(SignInWithB3Privy_1.SignInWithB3Privy, { onSuccess: handleLoginSuccess, chain: chain });
299
- }
300
- else if (strategies) {
301
- // Strategies are explicitly provided
302
- content = ((0, jsx_runtime_1.jsx)(LoginStepCustom_1.LoginStepCustom, { strategies: strategies, chain: chain, onSuccess: handleLoginSuccess, onError: onError, automaticallySetFirstEoa: !!automaticallySetFirstEoa }));
303
+ // PRIORITY: If Turnkey is enabled, show Turnkey modal FIRST as the primary authentication option
304
+ // Show Turnkey when enabled and not already completed in this session
305
+ const shouldShowTurnkeyFirst = enableTurnkey && !turnkeyAuthCompleted;
306
+ if (shouldShowTurnkeyFirst) {
307
+ // Don't show loading spinner for Turnkey - let the modal handle its own loading state
308
+ // This prevents the infinite loop where isAuthenticating causes the modal to be replaced
309
+ debug("Showing Turnkey as primary authentication option", {
310
+ enableTurnkey,
311
+ turnkeyAuthCompleted,
312
+ isAuthenticated,
313
+ });
314
+ // Show Turnkey authentication as primary option
315
+ content = ((0, jsx_runtime_1.jsx)(LoginStep_1.LoginStepContainer, { partnerId: partnerId, children: (0, jsx_runtime_1.jsx)(TurnkeyAuthModal_1.TurnkeyAuthModal, { onSuccess: async (authenticatedUser) => {
316
+ debug("Turnkey authentication successful in primary flow", { authenticatedUser });
317
+ setTurnkeyAuthCompleted(true);
318
+ // After Turnkey auth, refetch user to get the full user object
319
+ await refetchUser();
320
+ // User is now authenticated via Turnkey
321
+ // Set both isAuthenticated and isConnected to true so UI updates properly
322
+ // Wallet connection is optional and can happen later for signing transactions
323
+ setIsAuthenticated(true);
324
+ setIsConnected(true);
325
+ setJustCompletedLogin(true);
326
+ // Call the login success callback
327
+ onLoginSuccess?.({});
328
+ }, onClose: () => {
329
+ // If user closes Turnkey modal, they can still use wallet connection as fallback
330
+ setTurnkeyAuthCompleted(true);
331
+ }, initialEmail: "", skipToOtp: false }) }));
303
332
  }
304
333
  else {
305
- // Default to handle all strategies we support
306
- content = (0, jsx_runtime_1.jsx)(LoginStep_1.LoginStep, { chain: chain, onSuccess: handleLoginSuccess, onError: onError });
334
+ // Show loading spinner only if not in Turnkey flow
335
+ if (isAuthenticating || (isFetchingSigners && step === "login") || source === "requestPermissions") {
336
+ content = ((0, jsx_runtime_1.jsx)(LoginStep_1.LoginStepContainer, { partnerId: partnerId, children: (0, jsx_runtime_1.jsx)("div", { className: "my-8 flex min-h-[350px] items-center justify-center", children: (0, jsx_runtime_1.jsx)(react_1.Loading, { variant: "white", size: "lg" }) }) }));
337
+ }
338
+ else {
339
+ // Custom strategy
340
+ if (strategies?.[0] === "privy") {
341
+ content = (0, jsx_runtime_1.jsx)(SignInWithB3Privy_1.SignInWithB3Privy, { onSuccess: handleLoginSuccess, chain: chain });
342
+ }
343
+ else if (strategies) {
344
+ // Strategies are explicitly provided
345
+ content = ((0, jsx_runtime_1.jsx)(LoginStepCustom_1.LoginStepCustom, { strategies: strategies, chain: chain, onSuccess: handleLoginSuccess, onError: onError, automaticallySetFirstEoa: !!automaticallySetFirstEoa }));
346
+ }
347
+ else {
348
+ // Default to handle all strategies we support
349
+ content = (0, jsx_runtime_1.jsx)(LoginStep_1.LoginStep, { chain: chain, onSuccess: handleLoginSuccess, onError: onError });
350
+ }
351
+ }
307
352
  }
308
353
  }
309
354
  return content;
@@ -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";
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.useURLParams = exports.useUnifiedChainSwitchAndExecute = exports.useTurnkeyAuth = exports.useTokensFromAddress = exports.useTokenPriceWithFallback = exports.useTokenPrice = exports.useTokenFromUrl = exports.useTokenData = exports.useTokenBalancesByChain = exports.useTokenBalanceDirect = exports.useTokenBalance = exports.useSiwe = exports.useSimSvmBalance = exports.useSimBalance = exports.useSearchParamsSSR = exports.useRouter = exports.useRemoveSessionKey = exports.useQueryBSMNT = exports.useQueryB3 = exports.useProfileSettings = exports.useProfilePreference = exports.useProfile = exports.useDisplayName = exports.useOneBalance = exports.useNotifications = exports.useNativeBalanceFromRPC = exports.useNativeBalance = exports.useMediaQuery = exports.useIsomorphicLayoutEffect = exports.useIsMobile = exports.useHasMounted = exports.useHandleConnectWithPrivy = exports.useGlobalAccount = exports.useGetGeo = exports.useGetAllTWSigners = exports.useFirstEOA = exports.useExchangeRate = exports.useConnect = exports.useClient = exports.useChainSwitchWithAction = exports.useBestTransactionPath = exports.useB3EnsName = exports.useB3BalanceFromAddresses = exports.useAuthentication = exports.useAnalytics = exports.useAddTWSessionKey = exports.useAccountWallet = exports.useAccountAssets = exports.createWagmiConfig = void 0;
17
+ exports.useURLParams = exports.useUnifiedChainSwitchAndExecute = exports.useTurnkeyAuth = exports.useTokensFromAddress = exports.useTokenPriceWithFallback = exports.useTokenPrice = exports.useTokenFromUrl = exports.useTokenData = exports.useTokenBalancesByChain = exports.useTokenBalanceDirect = exports.useTokenBalance = exports.useSiwe = exports.useSimSvmBalance = exports.useSimBalance = exports.useSearchParamsSSR = exports.useRouter = exports.useRemoveSessionKey = exports.useQueryBSMNT = exports.useQueryB3 = exports.useProfileSettings = exports.useProfilePreference = exports.useProfile = exports.useDisplayName = exports.useOneBalance = exports.useNotifications = exports.useNativeBalanceFromRPC = exports.useNativeBalance = exports.useMediaQuery = exports.useIsomorphicLayoutEffect = exports.useIsMobile = exports.useHasMounted = exports.useHandleConnectWithPrivy = exports.useGlobalAccount = exports.useGetGeo = exports.useGetAllTWSigners = exports.useFirstEOA = exports.useExchangeRate = exports.useConnect = exports.useClient = exports.useChainSwitchWithAction = exports.useBestTransactionPath = exports.useB3EnsName = exports.useB3BalanceFromAddresses = exports.useAuthentication = exports.useAuth = exports.useAnalytics = exports.useAddTWSessionKey = exports.useAccountWallet = exports.useAccountAssets = exports.createWagmiConfig = void 0;
18
18
  var createWagmiConfig_1 = require("../utils/createWagmiConfig");
19
19
  Object.defineProperty(exports, "createWagmiConfig", { enumerable: true, get: function () { return createWagmiConfig_1.createWagmiConfig; } });
20
20
  var useAccountAssets_1 = require("./useAccountAssets");
@@ -25,6 +25,8 @@ var useAddTWSessionKey_1 = require("./useAddTWSessionKey");
25
25
  Object.defineProperty(exports, "useAddTWSessionKey", { enumerable: true, get: function () { return useAddTWSessionKey_1.useAddTWSessionKey; } });
26
26
  var useAnalytics_1 = require("./useAnalytics");
27
27
  Object.defineProperty(exports, "useAnalytics", { enumerable: true, get: function () { return useAnalytics_1.useAnalytics; } });
28
+ var useAuth_1 = require("./useAuth");
29
+ Object.defineProperty(exports, "useAuth", { enumerable: true, get: function () { return useAuth_1.useAuth; } });
28
30
  var useAuthentication_1 = require("./useAuthentication");
29
31
  Object.defineProperty(exports, "useAuthentication", { enumerable: true, get: function () { return useAuthentication_1.useAuthentication; } });
30
32
  var useB3BalanceFromAddresses_1 = require("./useB3BalanceFromAddresses");
@@ -0,0 +1,76 @@
1
+ import { Wallet } from "thirdweb/wallets";
2
+ import { preAuthenticate } from "thirdweb/wallets/in-app";
3
+ /**
4
+ * Unified authentication hook that uses Turnkey for authentication
5
+ * This replaces the previous Thirdweb-based authentication
6
+ *
7
+ * This hook provides 1:1 feature parity with useAuthentication.ts
8
+ */
9
+ export declare function useAuth(): {
10
+ authenticate: (turnkeySessionJwt: string, partnerId: string) => Promise<import("@feathersjs/authentication").AuthenticationResult>;
11
+ reAuthenticate: () => Promise<import("@feathersjs/authentication").AuthenticationResult>;
12
+ logout: (callback?: () => void) => Promise<void>;
13
+ isAuthenticated: boolean;
14
+ isReady: boolean;
15
+ isConnecting: boolean;
16
+ isConnected: boolean;
17
+ wallet: import("thirdweb/dist/types/wallets/in-app/core/wallet/types").EcosystemWallet;
18
+ preAuthenticate: typeof preAuthenticate;
19
+ connect: (_walleAutoConnectedWith: Wallet, allConnectedWallets: Wallet[]) => Promise<void>;
20
+ isAuthenticating: boolean;
21
+ onConnect: (_walleAutoConnectedWith: Wallet, allConnectedWallets: Wallet[]) => Promise<void>;
22
+ user: {
23
+ email?: string | undefined;
24
+ telNumber?: string | undefined;
25
+ username?: string | undefined;
26
+ ens?: string | undefined;
27
+ avatar?: string | undefined;
28
+ preferences?: {} | undefined;
29
+ referredBy?: string | {} | undefined;
30
+ sourceApp?: string | undefined;
31
+ referralCode?: string | undefined;
32
+ userGroups?: number[] | undefined;
33
+ isMigratedFromBSMNT?: boolean | undefined;
34
+ privyLinkedAccounts?: {
35
+ name?: string | undefined;
36
+ address?: string | undefined;
37
+ email?: string | undefined;
38
+ chain_type?: string | undefined;
39
+ lv?: number | undefined;
40
+ wallet_client_type?: string | undefined;
41
+ smart_wallet_type?: string | undefined;
42
+ subject?: string | undefined;
43
+ type: string;
44
+ }[] | undefined;
45
+ twProfiles?: {
46
+ type: string;
47
+ details: {
48
+ id?: string | undefined;
49
+ name?: string | undefined;
50
+ address?: string | undefined;
51
+ email?: string | undefined;
52
+ phone?: string | undefined;
53
+ username?: string | undefined;
54
+ fid?: string | undefined;
55
+ };
56
+ }[] | undefined;
57
+ turnkeySubOrgs?: {
58
+ hasDelegatedUser?: boolean | undefined;
59
+ subOrgId: string;
60
+ accounts: Record<string, any>[];
61
+ }[] | undefined;
62
+ _id: string | {};
63
+ userId: string;
64
+ smartAccountAddress: string;
65
+ createdAt: number;
66
+ updatedAt: number;
67
+ partnerIds: {
68
+ privyId?: string | undefined;
69
+ thirdwebId?: string | undefined;
70
+ turnkeyId?: string | undefined;
71
+ turnkeyOtpId?: string | undefined;
72
+ };
73
+ } | undefined;
74
+ refetchUser: () => Promise<import("@feathersjs/authentication").AuthenticationResult>;
75
+ setUser: (newUser?: import("@b3dotfun/b3-api").Users) => void;
76
+ };
@@ -0,0 +1,338 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.useAuth = useAuth;
7
+ const app_1 = __importDefault(require("../../../global-account/app"));
8
+ const bsmnt_1 = require("../../../global-account/bsmnt");
9
+ const react_1 = require("../../../global-account/react");
10
+ const constants_1 = require("../../../shared/constants");
11
+ const debug_1 = require("../../../shared/utils/debug");
12
+ const thirdweb_1 = require("../../../shared/utils/thirdweb");
13
+ const core_1 = require("@wagmi/core");
14
+ const react_2 = require("react");
15
+ const react_3 = require("thirdweb/react");
16
+ const wallets_1 = require("thirdweb/wallets");
17
+ const in_app_1 = require("thirdweb/wallets/in-app");
18
+ const wagmi_1 = require("wagmi");
19
+ const LocalSDKProvider_1 = require("../components/B3Provider/LocalSDKProvider");
20
+ const useB3_1 = require("../components/B3Provider/useB3");
21
+ const createWagmiConfig_1 = require("../utils/createWagmiConfig");
22
+ const useSearchParamsSSR_1 = require("./useSearchParamsSSR");
23
+ const useUserQuery_1 = require("./useUserQuery");
24
+ const debug = (0, debug_1.debugB3React)("useAuth");
25
+ /**
26
+ * Unified authentication hook that uses Turnkey for authentication
27
+ * This replaces the previous Thirdweb-based authentication
28
+ *
29
+ * This hook provides 1:1 feature parity with useAuthentication.ts
30
+ */
31
+ function useAuth() {
32
+ const { onConnectCallback } = (0, react_2.useContext)(LocalSDKProvider_1.LocalSDKContext);
33
+ const { disconnect } = (0, react_3.useDisconnect)();
34
+ const wallets = (0, react_3.useConnectedWallets)();
35
+ const activeWallet = (0, react_3.useActiveWallet)();
36
+ const isAuthenticated = (0, react_1.useAuthStore)(state => state.isAuthenticated);
37
+ const setIsAuthenticated = (0, react_1.useAuthStore)(state => state.setIsAuthenticated);
38
+ const setIsConnected = (0, react_1.useAuthStore)(state => state.setIsConnected);
39
+ const isConnecting = (0, react_1.useAuthStore)(state => state.isConnecting);
40
+ const isConnected = (0, react_1.useAuthStore)(state => state.isConnected);
41
+ const isAuthenticating = (0, react_1.useAuthStore)(state => state.isAuthenticating);
42
+ const setIsAuthenticating = (0, react_1.useAuthStore)(state => state.setIsAuthenticating);
43
+ const setHasStartedConnecting = (0, react_1.useAuthStore)(state => state.setHasStartedConnecting);
44
+ const setActiveWallet = (0, react_3.useSetActiveWallet)();
45
+ const hasStartedConnecting = (0, react_1.useAuthStore)(state => state.hasStartedConnecting);
46
+ const useAutoConnectLoadingPrevious = (0, react_2.useRef)(false);
47
+ const referralCode = (0, useSearchParamsSSR_1.useSearchParam)("referralCode");
48
+ const { partnerId } = (0, useB3_1.useB3)();
49
+ const wagmiConfig = (0, createWagmiConfig_1.createWagmiConfig)({ partnerId });
50
+ const { connect } = (0, wagmi_1.useConnect)();
51
+ const activeWagmiAccount = (0, wagmi_1.useAccount)();
52
+ const { switchAccount } = (0, wagmi_1.useSwitchAccount)();
53
+ const { user, setUser } = (0, useUserQuery_1.useUserQuery)();
54
+ debug("@@activeWagmiAccount", activeWagmiAccount);
55
+ const wallet = (0, wallets_1.ecosystemWallet)(constants_1.ecosystemWalletId, {
56
+ partnerId: partnerId,
57
+ });
58
+ /**
59
+ * Re-authenticate using existing session
60
+ * Also updates user state and authenticates with BSMNT
61
+ */
62
+ const reAuthenticate = (0, react_2.useCallback)(async () => {
63
+ debug("Re-authenticating...");
64
+ try {
65
+ const response = await app_1.default.reAuthenticate();
66
+ debug("Re-authentication successful", response);
67
+ // Update user state if user data exists
68
+ if (response.user) {
69
+ setUser(response.user);
70
+ debug("User state updated", response.user);
71
+ }
72
+ // Authenticate with BSMNT
73
+ try {
74
+ const b3Jwt = await (0, bsmnt_1.authenticateWithB3JWT)(response.accessToken);
75
+ debug("BSMNT re-authentication successful", b3Jwt);
76
+ }
77
+ catch (bsmntError) {
78
+ // BSMNT authentication failure shouldn't block the main auth flow
79
+ debug("BSMNT re-authentication failed (non-critical)", bsmntError);
80
+ }
81
+ return response;
82
+ }
83
+ catch (err) {
84
+ debug("Re-authentication failed", err);
85
+ throw err;
86
+ }
87
+ }, [setUser]);
88
+ const syncWagmi = (0, react_2.useCallback)(async () => {
89
+ function syncWagmiFunc() {
90
+ const connectors = (0, core_1.getConnectors)(wagmiConfig);
91
+ debug("@@syncWagmi", {
92
+ connectors,
93
+ wallets,
94
+ });
95
+ // For each that matchs a TW wallet on wallets, connect to the wagmi connector
96
+ // or, since ecosystem wallets is separate, connect those via in-app-wallet from wagmi
97
+ connectors.forEach(async (connector) => {
98
+ const twWallet = wallets.find(wallet => wallet.id === connector.id || connector.id === "in-app-wallet");
99
+ // If no TW wallet, do not prompt the user to connect
100
+ if (!twWallet) {
101
+ return;
102
+ }
103
+ // Metamask will prompt to connect, we can just switch accounts here.
104
+ if (connector.id === "io.metamask") {
105
+ return switchAccount({ connector });
106
+ }
107
+ if (
108
+ // If it's not an in-app wallet or it is the ecosystem wallet, connect
109
+ connector.id !== "in-app-wallet" ||
110
+ (connector.id === "in-app-wallet" && twWallet.id === constants_1.ecosystemWalletId)) {
111
+ try {
112
+ const options = {
113
+ wallet: twWallet, // the connected wallet
114
+ };
115
+ debug("@@syncWagmi:connecting", { twWallet, connector });
116
+ connect({
117
+ connector,
118
+ ...options,
119
+ });
120
+ }
121
+ catch (error) {
122
+ console.error("@@syncWagmi:error", error);
123
+ }
124
+ }
125
+ else {
126
+ debug("@@syncWagmi:not-connecting", connector);
127
+ }
128
+ });
129
+ }
130
+ syncWagmiFunc();
131
+ // wagmi config shouldn't change
132
+ // eslint-disable-next-line react-hooks/exhaustive-deps
133
+ }, [partnerId, wallets]);
134
+ (0, react_2.useEffect)(() => {
135
+ syncWagmi();
136
+ }, [wallets, syncWagmi]);
137
+ /**
138
+ * Authenticate user using Turnkey
139
+ * Note: This no longer requires a wallet for authentication.
140
+ * Wallets are still used for signing transactions, but authentication is done via Turnkey email OTP.
141
+ *
142
+ * For backward compatibility, this function still accepts a wallet parameter,
143
+ * but it's not used for authentication anymore.
144
+ */
145
+ const authenticateUser = (0, react_2.useCallback)(async () => {
146
+ setHasStartedConnecting(true);
147
+ // Try to re-authenticate first
148
+ try {
149
+ const userAuth = await reAuthenticate();
150
+ setUser(userAuth.user);
151
+ setIsAuthenticated(true);
152
+ setIsAuthenticating(false);
153
+ debug("Re-authenticated successfully", { userAuth });
154
+ // Authenticate on BSMNT with B3 JWT
155
+ const b3Jwt = await (0, bsmnt_1.authenticateWithB3JWT)(userAuth.accessToken);
156
+ debug("@@b3Jwt", b3Jwt);
157
+ return userAuth;
158
+ }
159
+ catch (error) {
160
+ // If re-authentication fails, user needs to authenticate via Turnkey
161
+ // This should be handled by the Turnkey auth modal/flow
162
+ debug("Re-authentication failed. User needs to authenticate via Turnkey.", error);
163
+ setIsAuthenticated(false);
164
+ setIsAuthenticating(false);
165
+ throw new Error("Authentication required. Please authenticate via Turnkey.");
166
+ }
167
+ }, [reAuthenticate, setIsAuthenticated, setIsAuthenticating, setUser, setHasStartedConnecting]);
168
+ /**
169
+ * Authenticate with Turnkey using email OTP
170
+ * This is the primary authentication method, replacing Thirdweb wallet-based auth
171
+ *
172
+ * This function:
173
+ * 1. Authenticates with FeathersJS (persists session via cookies)
174
+ * 2. Sets user state in the user store (persists to localStorage)
175
+ * 3. Authenticates with BSMNT for basement integration
176
+ */
177
+ const authenticate = (0, react_2.useCallback)(async (turnkeySessionJwt, partnerId) => {
178
+ if (!turnkeySessionJwt) {
179
+ throw new Error("Turnkey session JWT is required");
180
+ }
181
+ debug("Authenticating with Turnkey JWT", { referralCode, partnerId });
182
+ try {
183
+ // Step 1: Authenticate with FeathersJS (session persisted via cookies)
184
+ const response = await app_1.default.authenticate({
185
+ strategy: "turnkey-jwt",
186
+ accessToken: turnkeySessionJwt,
187
+ referralCode,
188
+ partnerId: partnerId,
189
+ });
190
+ debug("Authentication successful", response);
191
+ // Step 2: Set user state (persists to localStorage via Zustand)
192
+ if (response.user) {
193
+ setUser(response.user);
194
+ debug("User state updated", response.user);
195
+ }
196
+ // Step 3: Authenticate with BSMNT for basement integration
197
+ try {
198
+ const b3Jwt = await (0, bsmnt_1.authenticateWithB3JWT)(response.accessToken);
199
+ debug("BSMNT authentication successful", b3Jwt);
200
+ }
201
+ catch (bsmntError) {
202
+ // BSMNT authentication failure shouldn't block the main auth flow
203
+ debug("BSMNT authentication failed (non-critical)", bsmntError);
204
+ }
205
+ return response;
206
+ }
207
+ catch (err) {
208
+ debug("Authentication failed", err);
209
+ throw err;
210
+ }
211
+ }, [referralCode, setUser]);
212
+ /**
213
+ * Handle wallet connection
214
+ * Note: With Turnkey migration, wallet connection is primarily for signing transactions,
215
+ * not for authentication. Authentication should be done separately via Turnkey email OTP.
216
+ */
217
+ /**
218
+ * Handle wallet connection
219
+ * Note: With Turnkey migration, wallet connection is primarily for signing transactions,
220
+ * not for authentication. Authentication should be done separately via Turnkey email OTP.
221
+ */
222
+ const onConnect = (0, react_2.useCallback)(async (_walleAutoConnectedWith, allConnectedWallets) => {
223
+ debug("@@useAuth:onConnect", { _walleAutoConnectedWith, allConnectedWallets });
224
+ const wallet = allConnectedWallets.find(wallet => wallet.id.startsWith("ecosystem."));
225
+ if (!wallet) {
226
+ throw new Error("No smart wallet found during auto-connect");
227
+ }
228
+ debug("@@useAuth:onConnect", { wallet });
229
+ try {
230
+ setHasStartedConnecting(true);
231
+ setIsConnected(true);
232
+ setIsAuthenticating(true);
233
+ await setActiveWallet(wallet);
234
+ // Try to authenticate user (will use re-authenticate if session exists)
235
+ // If no session exists, authentication will need to happen via Turnkey flow
236
+ try {
237
+ const userAuth = await authenticateUser();
238
+ if (userAuth && onConnectCallback) {
239
+ await onConnectCallback(wallet, userAuth.accessToken);
240
+ }
241
+ }
242
+ catch (authError) {
243
+ // Authentication failed - this is expected if user hasn't authenticated via Turnkey yet
244
+ // The Turnkey auth modal should handle this
245
+ debug("@@useAuth:onConnect:authFailed", { authError });
246
+ // Don't set isAuthenticated to false here - let the Turnkey flow handle it
247
+ }
248
+ }
249
+ catch (error) {
250
+ debug("@@useAuth:onConnect:failed", { error });
251
+ setIsAuthenticated(false);
252
+ setUser(undefined);
253
+ }
254
+ finally {
255
+ setIsAuthenticating(false);
256
+ }
257
+ debug({
258
+ isAuthenticated,
259
+ isAuthenticating,
260
+ isConnected,
261
+ });
262
+ }, [
263
+ onConnectCallback,
264
+ authenticateUser,
265
+ isAuthenticated,
266
+ isAuthenticating,
267
+ isConnected,
268
+ setActiveWallet,
269
+ setHasStartedConnecting,
270
+ setIsAuthenticated,
271
+ setIsAuthenticating,
272
+ setIsConnected,
273
+ setUser,
274
+ ]);
275
+ const logout = (0, react_2.useCallback)(async (callback) => {
276
+ if (activeWallet) {
277
+ debug("@@logout:activeWallet", activeWallet);
278
+ disconnect(activeWallet);
279
+ debug("@@logout:activeWallet", activeWallet);
280
+ }
281
+ // Log out of each wallet
282
+ wallets.forEach(wallet => {
283
+ console.log("@@logging out", wallet);
284
+ disconnect(wallet);
285
+ });
286
+ // Delete localStorage thirdweb:connected-wallet-ids
287
+ // https://npc-labs.slack.com/archives/C070E6HNG85/p1750185115273099
288
+ if (typeof localStorage !== "undefined") {
289
+ localStorage.removeItem("thirdweb:connected-wallet-ids");
290
+ localStorage.removeItem("wagmi.store");
291
+ localStorage.removeItem("lastAuthProvider");
292
+ localStorage.removeItem("b3-user");
293
+ }
294
+ app_1.default.logout();
295
+ debug("@@logout:loggedOut");
296
+ setIsAuthenticated(false);
297
+ setIsConnected(false);
298
+ setUser();
299
+ callback?.();
300
+ }, [activeWallet, disconnect, wallets, setIsAuthenticated, setUser, setIsConnected]);
301
+ const { isLoading: useAutoConnectLoading } = (0, react_3.useAutoConnect)({
302
+ client: thirdweb_1.client,
303
+ wallets: [wallet],
304
+ onConnect,
305
+ onTimeout: () => {
306
+ logout().catch(error => {
307
+ debug("@@useAuth:logout on timeout failed", { error });
308
+ });
309
+ },
310
+ });
311
+ /**
312
+ * useAutoConnectLoading starts as false
313
+ */
314
+ (0, react_2.useEffect)(() => {
315
+ if (!useAutoConnectLoading && useAutoConnectLoadingPrevious.current && !hasStartedConnecting) {
316
+ setIsAuthenticating(false);
317
+ }
318
+ useAutoConnectLoadingPrevious.current = useAutoConnectLoading;
319
+ }, [useAutoConnectLoading, hasStartedConnecting, setIsAuthenticating]);
320
+ const isReady = isAuthenticated && !isAuthenticating;
321
+ return {
322
+ authenticate,
323
+ reAuthenticate,
324
+ logout,
325
+ isAuthenticated,
326
+ isReady,
327
+ isConnecting,
328
+ isConnected,
329
+ wallet,
330
+ preAuthenticate: in_app_1.preAuthenticate,
331
+ connect: onConnect,
332
+ isAuthenticating,
333
+ onConnect,
334
+ user,
335
+ refetchUser: authenticateUser,
336
+ setUser,
337
+ };
338
+ }
@@ -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
  };