@b3dotfun/sdk 0.0.83-test.0 → 0.0.84-alpha.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 (176) hide show
  1. package/dist/cjs/anyspend/constants/index.d.ts +1 -1
  2. package/dist/cjs/anyspend/constants/index.js +2 -2
  3. package/dist/cjs/anyspend/react/components/AnySpend.js +21 -12
  4. package/dist/cjs/anyspend/react/components/AnySpendCollectorClubPurchase.js +1 -1
  5. package/dist/cjs/anyspend/react/components/AnySpendCustom.js +4 -6
  6. package/dist/cjs/anyspend/react/components/common/CryptoPaySection.js +2 -4
  7. package/dist/cjs/anyspend/react/components/common/CryptoPaymentMethod.js +47 -177
  8. package/dist/cjs/anyspend/react/components/common/CryptoPaymentMethodDisplay.d.ts +15 -0
  9. package/dist/cjs/anyspend/react/components/common/CryptoPaymentMethodDisplay.js +28 -0
  10. package/dist/cjs/anyspend/react/components/common/InsufficientDepositPayment.js +1 -1
  11. package/dist/cjs/anyspend/react/components/common/OrderDetails.js +5 -4
  12. package/dist/cjs/anyspend/react/components/common/OrderToken.js +2 -2
  13. package/dist/cjs/anyspend/react/components/common/OrderTokenAmount.js +1 -1
  14. package/dist/cjs/anyspend/react/components/common/OrderTokenAmountFiat.js +1 -1
  15. package/dist/cjs/anyspend/react/components/common/OrderTokenAmountNew.js +2 -2
  16. package/dist/cjs/anyspend/react/components/common/PaymentStripeWeb2.js +4 -6
  17. package/dist/cjs/anyspend/react/components/common/PaymentVendorUI.js +41 -2
  18. package/dist/cjs/anyspend/react/components/common/TransferCryptoDetails.js +1 -1
  19. package/dist/cjs/anyspend/react/components/webview/WebviewOnrampPayment.js +2 -3
  20. package/dist/cjs/anyspend/react/hooks/index.d.ts +1 -0
  21. package/dist/cjs/anyspend/react/hooks/index.js +1 -0
  22. package/dist/cjs/anyspend/react/hooks/useAnyspendFlow.js +0 -3
  23. package/dist/cjs/anyspend/react/hooks/useConnectedUserProfile.d.ts +2 -1
  24. package/dist/cjs/anyspend/react/hooks/useConnectedUserProfile.js +5 -8
  25. package/dist/cjs/anyspend/react/hooks/useConnectedWalletDisplay.d.ts +0 -2
  26. package/dist/cjs/anyspend/react/hooks/useConnectedWalletDisplay.js +2 -12
  27. package/dist/cjs/anyspend/react/hooks/useHyperliquidTransfer.d.ts +37 -0
  28. package/dist/cjs/anyspend/react/hooks/useHyperliquidTransfer.js +133 -0
  29. package/dist/cjs/anyspend/react/providers/AnyspendProvider.js +1 -13
  30. package/dist/cjs/anyspend/types/chain.d.ts +10 -2
  31. package/dist/cjs/anyspend/types/chain.js +1 -0
  32. package/dist/cjs/anyspend/utils/address.d.ts +11 -0
  33. package/dist/cjs/anyspend/utils/address.js +15 -0
  34. package/dist/cjs/anyspend/utils/chain.d.ts +58 -1
  35. package/dist/cjs/anyspend/utils/chain.js +94 -4
  36. package/dist/cjs/anyspend/utils/token.d.ts +4 -0
  37. package/dist/cjs/anyspend/utils/token.js +35 -6
  38. package/dist/cjs/global-account/react/components/B3Provider/B3Provider.js +1 -1
  39. package/dist/cjs/global-account/react/components/SignInWithB3/SignIn.js +3 -4
  40. package/dist/cjs/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +12 -57
  41. package/dist/cjs/global-account/react/components/SignInWithB3/steps/LoginStep.js +1 -1
  42. package/dist/cjs/global-account/react/hooks/index.d.ts +0 -2
  43. package/dist/cjs/global-account/react/hooks/index.js +1 -5
  44. package/dist/cjs/global-account/react/hooks/useAccountWallet.js +11 -10
  45. package/dist/cjs/global-account/react/hooks/useAuthentication.d.ts +2 -2
  46. package/dist/cjs/global-account/react/hooks/useAuthentication.js +63 -72
  47. package/dist/cjs/global-account/react/hooks/useTWAuth.d.ts +0 -3
  48. package/dist/cjs/global-account/react/hooks/useTWAuth.js +0 -8
  49. package/dist/cjs/global-account/react/hooks/useTurnkeyAuth.js +24 -54
  50. package/dist/cjs/global-account/react/hooks/useUserQuery.d.ts +1 -1
  51. package/dist/cjs/shared/utils/payment.utils.d.ts +1 -0
  52. package/dist/cjs/shared/utils/payment.utils.js +9 -0
  53. package/dist/esm/anyspend/constants/index.d.ts +1 -1
  54. package/dist/esm/anyspend/constants/index.js +1 -1
  55. package/dist/esm/anyspend/react/components/AnySpend.js +22 -13
  56. package/dist/esm/anyspend/react/components/AnySpendCollectorClubPurchase.js +1 -1
  57. package/dist/esm/anyspend/react/components/AnySpendCustom.js +5 -7
  58. package/dist/esm/anyspend/react/components/common/CryptoPaySection.js +4 -6
  59. package/dist/esm/anyspend/react/components/common/CryptoPaymentMethod.js +45 -175
  60. package/dist/esm/anyspend/react/components/common/CryptoPaymentMethodDisplay.d.ts +15 -0
  61. package/dist/esm/anyspend/react/components/common/CryptoPaymentMethodDisplay.js +25 -0
  62. package/dist/esm/anyspend/react/components/common/InsufficientDepositPayment.js +2 -2
  63. package/dist/esm/anyspend/react/components/common/OrderDetails.js +6 -5
  64. package/dist/esm/anyspend/react/components/common/OrderToken.js +3 -3
  65. package/dist/esm/anyspend/react/components/common/OrderTokenAmount.js +2 -2
  66. package/dist/esm/anyspend/react/components/common/OrderTokenAmountFiat.js +2 -2
  67. package/dist/esm/anyspend/react/components/common/OrderTokenAmountNew.js +3 -3
  68. package/dist/esm/anyspend/react/components/common/PaymentStripeWeb2.js +2 -4
  69. package/dist/esm/anyspend/react/components/common/PaymentVendorUI.js +9 -3
  70. package/dist/esm/anyspend/react/components/common/TransferCryptoDetails.js +2 -2
  71. package/dist/esm/anyspend/react/components/webview/WebviewOnrampPayment.js +3 -4
  72. package/dist/esm/anyspend/react/hooks/index.d.ts +1 -0
  73. package/dist/esm/anyspend/react/hooks/index.js +1 -0
  74. package/dist/esm/anyspend/react/hooks/useAnyspendFlow.js +0 -3
  75. package/dist/esm/anyspend/react/hooks/useConnectedUserProfile.d.ts +2 -1
  76. package/dist/esm/anyspend/react/hooks/useConnectedUserProfile.js +6 -9
  77. package/dist/esm/anyspend/react/hooks/useConnectedWalletDisplay.d.ts +0 -2
  78. package/dist/esm/anyspend/react/hooks/useConnectedWalletDisplay.js +2 -12
  79. package/dist/esm/anyspend/react/hooks/useHyperliquidTransfer.d.ts +37 -0
  80. package/dist/esm/anyspend/react/hooks/useHyperliquidTransfer.js +127 -0
  81. package/dist/esm/anyspend/react/providers/AnyspendProvider.js +1 -13
  82. package/dist/esm/anyspend/types/chain.d.ts +10 -2
  83. package/dist/esm/anyspend/types/chain.js +1 -0
  84. package/dist/esm/anyspend/utils/address.d.ts +11 -0
  85. package/dist/esm/anyspend/utils/address.js +14 -0
  86. package/dist/esm/anyspend/utils/chain.d.ts +58 -1
  87. package/dist/esm/anyspend/utils/chain.js +91 -4
  88. package/dist/esm/anyspend/utils/token.d.ts +4 -0
  89. package/dist/esm/anyspend/utils/token.js +32 -6
  90. package/dist/esm/global-account/react/components/B3Provider/B3Provider.js +2 -2
  91. package/dist/esm/global-account/react/components/SignInWithB3/SignIn.js +4 -5
  92. package/dist/esm/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +12 -57
  93. package/dist/esm/global-account/react/components/SignInWithB3/steps/LoginStep.js +1 -1
  94. package/dist/esm/global-account/react/hooks/index.d.ts +0 -2
  95. package/dist/esm/global-account/react/hooks/index.js +0 -2
  96. package/dist/esm/global-account/react/hooks/useAccountWallet.js +11 -10
  97. package/dist/esm/global-account/react/hooks/useAuthentication.d.ts +2 -2
  98. package/dist/esm/global-account/react/hooks/useAuthentication.js +63 -72
  99. package/dist/esm/global-account/react/hooks/useTWAuth.d.ts +0 -3
  100. package/dist/esm/global-account/react/hooks/useTWAuth.js +0 -8
  101. package/dist/esm/global-account/react/hooks/useTurnkeyAuth.js +24 -54
  102. package/dist/esm/global-account/react/hooks/useUserQuery.d.ts +1 -1
  103. package/dist/esm/shared/utils/payment.utils.d.ts +1 -0
  104. package/dist/esm/shared/utils/payment.utils.js +9 -1
  105. package/dist/styles/index.css +1 -1
  106. package/dist/types/anyspend/constants/index.d.ts +1 -1
  107. package/dist/types/anyspend/react/components/common/CryptoPaymentMethodDisplay.d.ts +15 -0
  108. package/dist/types/anyspend/react/hooks/index.d.ts +1 -0
  109. package/dist/types/anyspend/react/hooks/useConnectedUserProfile.d.ts +2 -1
  110. package/dist/types/anyspend/react/hooks/useConnectedWalletDisplay.d.ts +0 -2
  111. package/dist/types/anyspend/react/hooks/useHyperliquidTransfer.d.ts +37 -0
  112. package/dist/types/anyspend/types/chain.d.ts +10 -2
  113. package/dist/types/anyspend/utils/address.d.ts +11 -0
  114. package/dist/types/anyspend/utils/chain.d.ts +58 -1
  115. package/dist/types/anyspend/utils/token.d.ts +4 -0
  116. package/dist/types/global-account/react/hooks/index.d.ts +0 -2
  117. package/dist/types/global-account/react/hooks/useAuthentication.d.ts +2 -2
  118. package/dist/types/global-account/react/hooks/useTWAuth.d.ts +0 -3
  119. package/dist/types/global-account/react/hooks/useUserQuery.d.ts +1 -1
  120. package/dist/types/shared/utils/payment.utils.d.ts +1 -0
  121. package/package.json +1 -1
  122. package/src/anyspend/constants/index.ts +1 -1
  123. package/src/anyspend/react/components/AnySpend.tsx +31 -13
  124. package/src/anyspend/react/components/AnySpendCollectorClubPurchase.tsx +1 -1
  125. package/src/anyspend/react/components/AnySpendCustom.tsx +9 -29
  126. package/src/anyspend/react/components/common/CryptoPaySection.tsx +7 -30
  127. package/src/anyspend/react/components/common/CryptoPaymentMethod.tsx +22 -253
  128. package/src/anyspend/react/components/common/CryptoPaymentMethodDisplay.tsx +64 -0
  129. package/src/anyspend/react/components/common/InsufficientDepositPayment.tsx +2 -2
  130. package/src/anyspend/react/components/common/OrderDetails.tsx +6 -5
  131. package/src/anyspend/react/components/common/OrderToken.tsx +5 -5
  132. package/src/anyspend/react/components/common/OrderTokenAmount.tsx +3 -3
  133. package/src/anyspend/react/components/common/OrderTokenAmountFiat.tsx +3 -3
  134. package/src/anyspend/react/components/common/OrderTokenAmountNew.tsx +6 -6
  135. package/src/anyspend/react/components/common/PaymentStripeWeb2.tsx +3 -5
  136. package/src/anyspend/react/components/common/PaymentVendorUI.tsx +26 -2
  137. package/src/anyspend/react/components/common/TransferCryptoDetails.tsx +2 -2
  138. package/src/anyspend/react/components/webview/WebviewOnrampPayment.tsx +3 -5
  139. package/src/anyspend/react/hooks/index.ts +1 -0
  140. package/src/anyspend/react/hooks/useAnyspendFlow.ts +0 -4
  141. package/src/anyspend/react/hooks/useConnectedUserProfile.ts +7 -10
  142. package/src/anyspend/react/hooks/useConnectedWalletDisplay.ts +2 -15
  143. package/src/anyspend/react/hooks/useHyperliquidTransfer.ts +152 -0
  144. package/src/anyspend/react/providers/AnyspendProvider.tsx +7 -22
  145. package/src/anyspend/types/chain.ts +10 -1
  146. package/src/anyspend/utils/address.ts +15 -0
  147. package/src/anyspend/utils/chain.ts +115 -5
  148. package/src/anyspend/utils/token.ts +36 -7
  149. package/src/global-account/react/components/B3Provider/B3Provider.tsx +6 -2
  150. package/src/global-account/react/components/SignInWithB3/SignIn.tsx +4 -6
  151. package/src/global-account/react/components/SignInWithB3/SignInWithB3Flow.tsx +22 -77
  152. package/src/global-account/react/components/SignInWithB3/steps/LoginStep.tsx +1 -1
  153. package/src/global-account/react/hooks/index.ts +0 -2
  154. package/src/global-account/react/hooks/useAccountWallet.tsx +12 -11
  155. package/src/global-account/react/hooks/useAuthentication.ts +85 -88
  156. package/src/global-account/react/hooks/useTWAuth.tsx +0 -10
  157. package/src/global-account/react/hooks/useTurnkeyAuth.ts +26 -59
  158. package/src/shared/utils/payment.utils.ts +10 -1
  159. package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +0 -10
  160. package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +0 -73
  161. package/dist/cjs/global-account/react/hooks/useAuth.d.ts +0 -76
  162. package/dist/cjs/global-account/react/hooks/useAuth.js +0 -338
  163. package/dist/cjs/global-account/react/hooks/useBestTransactionPath.d.ts +0 -41
  164. package/dist/cjs/global-account/react/hooks/useBestTransactionPath.js +0 -148
  165. package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +0 -10
  166. package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +0 -70
  167. package/dist/esm/global-account/react/hooks/useAuth.d.ts +0 -76
  168. package/dist/esm/global-account/react/hooks/useAuth.js +0 -332
  169. package/dist/esm/global-account/react/hooks/useBestTransactionPath.d.ts +0 -41
  170. package/dist/esm/global-account/react/hooks/useBestTransactionPath.js +0 -145
  171. package/dist/types/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +0 -10
  172. package/dist/types/global-account/react/hooks/useAuth.d.ts +0 -76
  173. package/dist/types/global-account/react/hooks/useBestTransactionPath.d.ts +0 -41
  174. package/src/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.ts +0 -80
  175. package/src/global-account/react/hooks/useAuth.ts +0 -380
  176. package/src/global-account/react/hooks/useBestTransactionPath.tsx +0 -201
@@ -1,41 +0,0 @@
1
- import { components } from "../../../anyspend/types/api";
2
- export type TransactionType = "send" | "swap" | "bridge";
3
- export interface SprinterOption {
4
- chainId: number;
5
- balance: bigint;
6
- formattedBalance: string;
7
- }
8
- export interface TransactionPath {
9
- type: "native" | "sprinter" | "anyspend";
10
- hasNativePath: boolean;
11
- hasSprinterPath: boolean;
12
- availableBalance: bigint;
13
- totalCrossChainBalance: number;
14
- sprinterOptions?: SprinterOption[];
15
- }
16
- export interface TransactionPathResult extends TransactionPath {
17
- loading: boolean;
18
- }
19
- interface UseBestTransactionPathProps {
20
- amount: bigint;
21
- token: components["schemas"]["Token"];
22
- address?: string;
23
- transactionType?: TransactionType;
24
- }
25
- /**
26
- * Hook to determine the optimal transaction path based on user's balances across chains
27
- *
28
- * @param props.amount - Amount to transact
29
- * @param props.token - Token (a Token object)
30
- * @param props.address - Target address (optional, defaults to self)
31
- * @param props.transactionType - Type of transaction (optional, defaults to 'send')
32
- *
33
- * - type: The recommended path type ('native', 'sprinter', or 'anyspend')
34
- * - hasNativePath: Whether direct native token transfer is possible (1st best path)
35
- * - hasSprinterPath: Whether bridging via Sprinter is possible (2nd best path)
36
- * - availableBalance: The user's balance of this asset
37
- * - sprinterOptions: Available chains and balances for bridging
38
- * @returns TransactionPathResult object containing path information and loading state
39
- */
40
- export declare function useBestTransactionPath({ amount, token, address, transactionType: _transactionType, }: UseBestTransactionPathProps): TransactionPathResult;
41
- export {};
@@ -1,148 +0,0 @@
1
- "use strict";
2
- "use client";
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.useBestTransactionPath = useBestTransactionPath;
5
- const anyspend_1 = require("../../../anyspend");
6
- const react_1 = require("../../../global-account/react");
7
- const react_2 = require("react");
8
- const viem_1 = require("viem");
9
- const supportedSprinterTokenSymbols = ["ETH", "USDC", "WETH"];
10
- /**
11
- * Hook to determine the optimal transaction path based on user's balances across chains
12
- *
13
- * @param props.amount - Amount to transact
14
- * @param props.token - Token (a Token object)
15
- * @param props.address - Target address (optional, defaults to self)
16
- * @param props.transactionType - Type of transaction (optional, defaults to 'send')
17
- *
18
- * - type: The recommended path type ('native', 'sprinter', or 'anyspend')
19
- * - hasNativePath: Whether direct native token transfer is possible (1st best path)
20
- * - hasSprinterPath: Whether bridging via Sprinter is possible (2nd best path)
21
- * - availableBalance: The user's balance of this asset
22
- * - sprinterOptions: Available chains and balances for bridging
23
- * @returns TransactionPathResult object containing path information and loading state
24
- */
25
- function useBestTransactionPath({ amount, token, address, transactionType: _transactionType = "send", }) {
26
- const account = (0, react_1.useAccountWallet)();
27
- const effectiveAddress = address || account?.address;
28
- const isSupportedSprinterToken = supportedSprinterTokenSymbols.includes(token.symbol.toUpperCase());
29
- // Get balances across all chains
30
- const { aggregatedBalances, aggregatedTokenBalances, loading: oneBalanceLoading } = (0, react_1.useOneBalance)();
31
- // Get the token balance using our new hook
32
- const { rawBalance, isLoading: tokenBalanceLoading } = (0, react_1.useTokenBalance)({
33
- token,
34
- address: effectiveAddress,
35
- });
36
- // Check if amount is available natively on destination chain
37
- const hasNativeBalance = (0, react_2.useMemo)(() => {
38
- if (!rawBalance || !amount)
39
- return false;
40
- return rawBalance >= amount;
41
- }, [amount, rawBalance]);
42
- // Calculate non-native token balance using the same logic as hasNativeBalance
43
- const nonNativeTokenBalance = (0, react_2.useMemo)(() => {
44
- if ((0, anyspend_1.isNativeToken)(token.address))
45
- return BigInt(0);
46
- // For sprinter supported tokens, use aggregated balances
47
- if (isSupportedSprinterToken && !oneBalanceLoading && aggregatedBalances) {
48
- const asset = aggregatedBalances.find(asset => asset.symbol === token.symbol);
49
- if (asset) {
50
- const chainBalance = asset.chainBalances.find(cb => cb.chainId === token.chainId);
51
- if (chainBalance) {
52
- return BigInt(chainBalance.balance);
53
- }
54
- }
55
- return BigInt(0);
56
- }
57
- // For non-sprinter tokens, use token balance from our new hook
58
- return rawBalance;
59
- }, [
60
- token.address,
61
- token.symbol,
62
- token.chainId,
63
- isSupportedSprinterToken,
64
- oneBalanceLoading,
65
- aggregatedBalances,
66
- rawBalance,
67
- ]);
68
- const totalCrossChainBalance = (0, react_2.useMemo)(() => {
69
- if (oneBalanceLoading || !aggregatedTokenBalances || !token.symbol)
70
- return 0;
71
- return aggregatedTokenBalances[token.symbol] || 0;
72
- }, [aggregatedTokenBalances, token.symbol, oneBalanceLoading]);
73
- // Calculate available sprinter options and determine if sprinter path is available
74
- const { hasSprinterPath, sprinterOptions } = (0, react_2.useMemo)(() => {
75
- if (!isSupportedSprinterToken || oneBalanceLoading || !aggregatedBalances || !token.symbol || !amount) {
76
- return { hasSprinterPath: false, sprinterOptions: [] };
77
- }
78
- const asset = aggregatedBalances.find(asset => asset.symbol === token.symbol);
79
- if (!asset) {
80
- return { hasSprinterPath: false, sprinterOptions: [] };
81
- }
82
- const options = [];
83
- // Get all chains where user has sufficient balance
84
- for (const chainBalance of asset.chainBalances) {
85
- const balanceBi = BigInt(chainBalance.balance);
86
- if (balanceBi >= amount && chainBalance.chainId !== token.chainId) {
87
- options.push({
88
- chainId: chainBalance.chainId,
89
- balance: balanceBi,
90
- formattedBalance: (0, viem_1.formatUnits)(balanceBi, chainBalance.tokenDecimals),
91
- });
92
- }
93
- }
94
- return {
95
- hasSprinterPath: options.length > 0,
96
- sprinterOptions: options,
97
- };
98
- }, [isSupportedSprinterToken, oneBalanceLoading, aggregatedBalances, token.symbol, token.chainId, amount]);
99
- // Determine the best path
100
- const path = (0, react_2.useMemo)(() => {
101
- const availableBalance = ((0, anyspend_1.isNativeToken)(token.address) ? rawBalance : nonNativeTokenBalance) || BigInt(0);
102
- // Case 1: Native path if available
103
- if (hasNativeBalance) {
104
- return {
105
- type: "native",
106
- hasNativePath: true,
107
- hasSprinterPath,
108
- availableBalance,
109
- totalCrossChainBalance,
110
- sprinterOptions,
111
- };
112
- }
113
- // Case 2: Sprinter path if available
114
- if (hasSprinterPath) {
115
- return {
116
- type: "sprinter",
117
- hasNativePath: false,
118
- hasSprinterPath: true,
119
- availableBalance,
120
- totalCrossChainBalance,
121
- sprinterOptions,
122
- };
123
- }
124
- // Case 3: Fallback to anyspend
125
- return {
126
- type: "anyspend",
127
- hasNativePath: false,
128
- hasSprinterPath: false,
129
- availableBalance,
130
- totalCrossChainBalance,
131
- sprinterOptions: [],
132
- };
133
- }, [
134
- token.address,
135
- rawBalance,
136
- nonNativeTokenBalance,
137
- hasNativeBalance,
138
- hasSprinterPath,
139
- totalCrossChainBalance,
140
- sprinterOptions,
141
- ]);
142
- // Combine all loading states
143
- const loading = oneBalanceLoading || tokenBalanceLoading;
144
- return {
145
- ...path,
146
- loading,
147
- };
148
- }
@@ -1,10 +0,0 @@
1
- /**
2
- * Hook that automatically sets the active thirdweb wallet when a wagmi wallet connects.
3
- *
4
- * This is useful for syncing wagmi wallet connections with thirdweb's wallet system,
5
- * ensuring that when users connect via wagmi, the active wallet is properly set.
6
- *
7
- * Place this hook in components that stay mounted throughout the user flow
8
- * (not in components that unmount during navigation).
9
- */
10
- export declare function useAutoSetActiveWalletFromWagmi(): void;
@@ -1,70 +0,0 @@
1
- import { client } from "../../../shared/utils/thirdweb.js";
2
- import { useCallback, useEffect, useRef } from "react";
3
- import { useSetActiveWallet } from "thirdweb/react";
4
- import { createWallet } from "thirdweb/wallets";
5
- import { useAccount } from "wagmi";
6
- /**
7
- * Hook that automatically sets the active thirdweb wallet when a wagmi wallet connects.
8
- *
9
- * This is useful for syncing wagmi wallet connections with thirdweb's wallet system,
10
- * ensuring that when users connect via wagmi, the active wallet is properly set.
11
- *
12
- * Place this hook in components that stay mounted throughout the user flow
13
- * (not in components that unmount during navigation).
14
- */
15
- export function useAutoSetActiveWalletFromWagmi() {
16
- const { address: wagmiAddress, connector: wagmiConnector } = useAccount();
17
- const setActiveWallet = useSetActiveWallet();
18
- const prevWagmiAddress = useRef(undefined);
19
- // Map wagmi connector names to thirdweb wallet IDs
20
- const getThirdwebWalletId = useCallback((connectorName) => {
21
- const walletMap = {
22
- MetaMask: "io.metamask",
23
- "Coinbase Wallet": "com.coinbase.wallet",
24
- Rainbow: "me.rainbow",
25
- WalletConnect: "walletConnect",
26
- Phantom: "app.phantom",
27
- };
28
- return walletMap[connectorName] || null;
29
- }, []);
30
- // Create thirdweb wallet from wagmi connector
31
- const createThirdwebWalletFromConnector = useCallback(async (connectorName) => {
32
- const walletId = getThirdwebWalletId(connectorName);
33
- if (!walletId) {
34
- console.warn(`No thirdweb wallet ID found for connector: ${connectorName}`);
35
- return null;
36
- }
37
- try {
38
- const thirdwebWallet = createWallet(walletId);
39
- await thirdwebWallet.connect({ client });
40
- return thirdwebWallet;
41
- }
42
- catch (error) {
43
- console.error(`Failed to create thirdweb wallet for ${connectorName}:`, error);
44
- return null;
45
- }
46
- }, [getThirdwebWalletId]);
47
- // Listen for wagmi wallet connections and automatically set active wallet
48
- useEffect(() => {
49
- const isNewConnection = wagmiAddress && wagmiAddress !== prevWagmiAddress.current;
50
- if (isNewConnection && wagmiConnector?.name) {
51
- prevWagmiAddress.current = wagmiAddress;
52
- const setupThirdwebWallet = async () => {
53
- try {
54
- const thirdwebWallet = await createThirdwebWalletFromConnector(wagmiConnector.name);
55
- if (thirdwebWallet) {
56
- setActiveWallet(thirdwebWallet);
57
- console.log(`Auto-set active wallet for ${wagmiConnector.name}`);
58
- }
59
- }
60
- catch (error) {
61
- console.error("Failed to auto-set active wallet:", error);
62
- }
63
- };
64
- setupThirdwebWallet();
65
- }
66
- if (!wagmiAddress) {
67
- prevWagmiAddress.current = undefined;
68
- }
69
- }, [wagmiAddress, wagmiConnector?.name, setActiveWallet, createThirdwebWalletFromConnector]);
70
- }
@@ -1,76 +0,0 @@
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
- };
@@ -1,332 +0,0 @@
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
- }