@b3dotfun/sdk 0.0.62 → 0.0.63-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 (91) hide show
  1. package/dist/cjs/anyspend/react/components/AnySpend.js +61 -23
  2. package/dist/cjs/anyspend/react/components/AnySpendCustom.js +3 -0
  3. package/dist/cjs/anyspend/react/components/AnySpendStakeB3.js +5 -4
  4. package/dist/cjs/anyspend/react/components/AnyspendDepositHype.js +4 -4
  5. package/dist/cjs/anyspend/react/components/common/CryptoPaySection.js +4 -6
  6. package/dist/cjs/anyspend/react/components/common/CryptoPaymentMethod.js +9 -17
  7. package/dist/cjs/anyspend/react/components/common/CryptoReceiveSection.d.ts +6 -1
  8. package/dist/cjs/anyspend/react/components/common/CryptoReceiveSection.js +11 -1
  9. package/dist/cjs/anyspend/react/components/common/OrderDetails.js +56 -145
  10. package/dist/cjs/anyspend/react/components/common/OrderTokenAmount.d.ts +2 -1
  11. package/dist/cjs/anyspend/react/components/common/OrderTokenAmount.js +39 -15
  12. package/dist/cjs/anyspend/react/components/common/PaySection.js +1 -1
  13. package/dist/cjs/anyspend/react/components/common/TokenBalance.js +1 -1
  14. package/dist/cjs/anyspend/react/hooks/useAnyspendFlow.js +12 -11
  15. package/dist/cjs/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.d.ts +26 -0
  16. package/dist/cjs/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.js +56 -0
  17. package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
  18. package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +73 -0
  19. package/dist/cjs/anyspend/react/hooks/useConnectedWalletDisplay.d.ts +14 -0
  20. package/dist/cjs/anyspend/react/hooks/useConnectedWalletDisplay.js +57 -0
  21. package/dist/cjs/anyspend/react/hooks/usePhantomTransfer.d.ts +36 -0
  22. package/dist/cjs/anyspend/react/hooks/usePhantomTransfer.js +211 -0
  23. package/dist/cjs/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +3 -1
  24. package/dist/cjs/global-account/react/hooks/index.d.ts +2 -1
  25. package/dist/cjs/global-account/react/hooks/index.js +5 -3
  26. package/dist/cjs/global-account/react/hooks/useSimBalance.d.ts +1 -1
  27. package/dist/cjs/global-account/react/hooks/useSimBalance.js +6 -5
  28. package/dist/cjs/global-account/react/hooks/useTokenBalanceDirect.d.ts +12 -0
  29. package/dist/cjs/global-account/react/hooks/useTokenBalanceDirect.js +62 -0
  30. package/dist/cjs/global-account/react/hooks/useTokenFromUrl.js +4 -3
  31. package/dist/esm/anyspend/react/components/AnySpend.js +62 -24
  32. package/dist/esm/anyspend/react/components/AnySpendCustom.js +3 -0
  33. package/dist/esm/anyspend/react/components/AnySpendStakeB3.js +7 -6
  34. package/dist/esm/anyspend/react/components/AnyspendDepositHype.js +4 -4
  35. package/dist/esm/anyspend/react/components/common/CryptoPaySection.js +5 -7
  36. package/dist/esm/anyspend/react/components/common/CryptoPaymentMethod.js +9 -17
  37. package/dist/esm/anyspend/react/components/common/CryptoReceiveSection.d.ts +6 -1
  38. package/dist/esm/anyspend/react/components/common/CryptoReceiveSection.js +11 -1
  39. package/dist/esm/anyspend/react/components/common/OrderDetails.js +57 -146
  40. package/dist/esm/anyspend/react/components/common/OrderTokenAmount.d.ts +2 -1
  41. package/dist/esm/anyspend/react/components/common/OrderTokenAmount.js +40 -16
  42. package/dist/esm/anyspend/react/components/common/PaySection.js +1 -1
  43. package/dist/esm/anyspend/react/components/common/TokenBalance.js +2 -2
  44. package/dist/esm/anyspend/react/hooks/useAnyspendFlow.js +12 -11
  45. package/dist/esm/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.d.ts +26 -0
  46. package/dist/esm/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.js +53 -0
  47. package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
  48. package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +70 -0
  49. package/dist/esm/anyspend/react/hooks/useConnectedWalletDisplay.d.ts +14 -0
  50. package/dist/esm/anyspend/react/hooks/useConnectedWalletDisplay.js +54 -0
  51. package/dist/esm/anyspend/react/hooks/usePhantomTransfer.d.ts +36 -0
  52. package/dist/esm/anyspend/react/hooks/usePhantomTransfer.js +208 -0
  53. package/dist/esm/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +3 -1
  54. package/dist/esm/global-account/react/hooks/index.d.ts +2 -1
  55. package/dist/esm/global-account/react/hooks/index.js +2 -1
  56. package/dist/esm/global-account/react/hooks/useSimBalance.d.ts +1 -1
  57. package/dist/esm/global-account/react/hooks/useSimBalance.js +6 -5
  58. package/dist/esm/global-account/react/hooks/useTokenBalanceDirect.d.ts +12 -0
  59. package/dist/esm/global-account/react/hooks/useTokenBalanceDirect.js +59 -0
  60. package/dist/esm/global-account/react/hooks/useTokenFromUrl.js +4 -3
  61. package/dist/types/anyspend/react/components/common/CryptoReceiveSection.d.ts +6 -1
  62. package/dist/types/anyspend/react/components/common/OrderTokenAmount.d.ts +2 -1
  63. package/dist/types/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.d.ts +26 -0
  64. package/dist/types/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
  65. package/dist/types/anyspend/react/hooks/useConnectedWalletDisplay.d.ts +14 -0
  66. package/dist/types/anyspend/react/hooks/usePhantomTransfer.d.ts +36 -0
  67. package/dist/types/global-account/react/hooks/index.d.ts +2 -1
  68. package/dist/types/global-account/react/hooks/useSimBalance.d.ts +1 -1
  69. package/dist/types/global-account/react/hooks/useTokenBalanceDirect.d.ts +12 -0
  70. package/package.json +3 -2
  71. package/src/anyspend/react/components/AnySpend.tsx +73 -22
  72. package/src/anyspend/react/components/AnySpendCustom.tsx +4 -0
  73. package/src/anyspend/react/components/AnySpendStakeB3.tsx +8 -11
  74. package/src/anyspend/react/components/AnyspendDepositHype.tsx +7 -3
  75. package/src/anyspend/react/components/common/CryptoPaySection.tsx +5 -7
  76. package/src/anyspend/react/components/common/CryptoPaymentMethod.tsx +9 -18
  77. package/src/anyspend/react/components/common/CryptoReceiveSection.tsx +22 -0
  78. package/src/anyspend/react/components/common/OrderDetails.tsx +66 -188
  79. package/src/anyspend/react/components/common/OrderTokenAmount.tsx +48 -17
  80. package/src/anyspend/react/components/common/PaySection.tsx +1 -0
  81. package/src/anyspend/react/components/common/TokenBalance.tsx +2 -2
  82. package/src/anyspend/react/hooks/useAnyspendFlow.ts +13 -10
  83. package/src/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.ts +72 -0
  84. package/src/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.ts +80 -0
  85. package/src/anyspend/react/hooks/useConnectedWalletDisplay.ts +69 -0
  86. package/src/anyspend/react/hooks/usePhantomTransfer.ts +301 -0
  87. package/src/global-account/react/components/SignInWithB3/SignInWithB3Flow.tsx +3 -1
  88. package/src/global-account/react/hooks/index.ts +2 -1
  89. package/src/global-account/react/hooks/useSimBalance.ts +6 -5
  90. package/src/global-account/react/hooks/useTokenBalanceDirect.tsx +84 -0
  91. package/src/global-account/react/hooks/useTokenFromUrl.tsx +6 -5
@@ -0,0 +1,69 @@
1
+ import { useAccountWallet } from "@b3dotfun/sdk/global-account/react";
2
+ import { useAccount } from "wagmi";
3
+ import { CryptoPaymentMethodType } from "../components/common/CryptoPaymentMethod";
4
+
5
+ interface UseConnectedWalletDisplayResult {
6
+ walletAddress: string | undefined;
7
+ shouldShowConnectedEOA: boolean;
8
+ shouldShowWagmiWallet: boolean;
9
+ isWalletDuplicated: boolean;
10
+ suggestedPaymentMethod: CryptoPaymentMethodType;
11
+ }
12
+
13
+ /**
14
+ * Custom hook to determine which wallet to display and its address
15
+ * Handles logic for showing EOA wallet, wagmi wallet, or global wallet based on payment method
16
+ */
17
+ export function useConnectedWalletDisplay(
18
+ selectedCryptoPaymentMethod?: CryptoPaymentMethodType,
19
+ ): UseConnectedWalletDisplayResult {
20
+ const { connectedEOAWallet, connectedSmartWallet } = useAccountWallet();
21
+ const { address: wagmiAddress, isConnected: wagmiWalletIsConnected } = useAccount();
22
+
23
+ // Helper function to check if two addresses are the same
24
+ const isSameAddress = (addr1?: string, addr2?: string): boolean => {
25
+ if (!addr1 || !addr2) return false;
26
+ return addr1.toLowerCase() === addr2.toLowerCase();
27
+ };
28
+
29
+ // Check if connectedEOAWallet and wagmi wallet represent the same wallet
30
+ const connectedEOAAddress = connectedEOAWallet?.getAccount()?.address;
31
+ const isWalletDuplicated = isSameAddress(connectedEOAAddress, wagmiAddress);
32
+
33
+ // Determine which wallet to show (prefer connectedEOAWallet if both exist and are the same)
34
+ const shouldShowConnectedEOA = !!connectedEOAWallet;
35
+ const shouldShowWagmiWallet = wagmiWalletIsConnected && (!isWalletDuplicated || !connectedEOAWallet);
36
+
37
+ // Determine which address to use based on payment method
38
+ let walletAddress: string | undefined;
39
+
40
+ if (selectedCryptoPaymentMethod === CryptoPaymentMethodType.GLOBAL_WALLET) {
41
+ walletAddress = connectedSmartWallet?.getAccount()?.address;
42
+ } else if (selectedCryptoPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET) {
43
+ // Prefer connectedEOAWallet, fallback to wagmi wallet
44
+ walletAddress = connectedEOAAddress || wagmiAddress;
45
+ } else {
46
+ // Default behavior: use connectedEOAWallet if available, otherwise wagmi
47
+ walletAddress = connectedEOAAddress || wagmiAddress;
48
+ }
49
+
50
+ // Suggest a payment method based on available wallets
51
+ // Priority: Connected EOA/Wagmi wallet > Global wallet > None
52
+ let suggestedPaymentMethod = CryptoPaymentMethodType.NONE;
53
+
54
+ if (connectedEOAAddress || wagmiAddress) {
55
+ // If there's a connected EOA or wagmi wallet, suggest CONNECT_WALLET
56
+ suggestedPaymentMethod = CryptoPaymentMethodType.CONNECT_WALLET;
57
+ } else if (connectedSmartWallet?.getAccount()?.address) {
58
+ // If only global wallet is available, suggest that
59
+ suggestedPaymentMethod = CryptoPaymentMethodType.GLOBAL_WALLET;
60
+ }
61
+
62
+ return {
63
+ walletAddress,
64
+ shouldShowConnectedEOA,
65
+ shouldShowWagmiWallet,
66
+ isWalletDuplicated,
67
+ suggestedPaymentMethod,
68
+ };
69
+ }
@@ -0,0 +1,301 @@
1
+ import {
2
+ createAssociatedTokenAccountInstruction,
3
+ createTransferCheckedInstruction,
4
+ getAssociatedTokenAddressSync,
5
+ } from "@solana/spl-token";
6
+ import { ComputeBudgetProgram, Connection, PublicKey, SystemProgram, Transaction } from "@solana/web3.js";
7
+ import { useCallback, useMemo } from "react";
8
+ import { toast } from "sonner";
9
+
10
+ interface UsePhantomTransferParams {
11
+ /** RPC endpoint URL for Solana network */
12
+ rpcEndpoint?: string;
13
+ }
14
+
15
+ interface PhantomTransferParams {
16
+ /** Amount in lamports (for SOL) or smallest token unit (for SPL tokens) */
17
+ amountLamports: string;
18
+ /** Token address (use "11111111111111111111111111111111" for native SOL) */
19
+ tokenAddress: string;
20
+ /** Recipient address */
21
+ recipientAddress: string;
22
+ }
23
+
24
+ /**
25
+ * Custom hook for handling Phantom wallet transfers on Solana.
26
+ * Supports both native SOL and SPL token transfers with automatic priority fee calculation.
27
+ *
28
+ * @example
29
+ * ```tsx
30
+ * const { initiateTransfer, isPhantomAvailable } = usePhantomTransfer();
31
+ *
32
+ * await initiateTransfer({
33
+ * amountLamports: "1000000000", // 1 SOL
34
+ * tokenAddress: "11111111111111111111111111111111",
35
+ * recipientAddress: "..."
36
+ * });
37
+ * ```
38
+ */
39
+ export function usePhantomTransfer({ rpcEndpoint }: UsePhantomTransferParams = {}) {
40
+ // Default RPC endpoint
41
+ const defaultRpcEndpoint = "https://mainnet.helius-rpc.com/?api-key=efafd9b3-1807-4cf8-8aa4-3d984f56d8fb";
42
+ const effectiveRpcEndpoint = rpcEndpoint || defaultRpcEndpoint;
43
+
44
+ // Check for Phantom wallet availability
45
+ const isPhantomMobile = useMemo(() => navigator.userAgent.includes("Phantom"), []);
46
+ const isPhantomBrowser = useMemo(() => (window as any).phantom?.solana?.isPhantom, []);
47
+ const isPhantomAvailable = isPhantomMobile || isPhantomBrowser;
48
+
49
+ /**
50
+ * Get the connected Phantom wallet address if available
51
+ */
52
+ const getConnectedAddress = useCallback(() => {
53
+ const phantom = (window as any).phantom?.solana;
54
+ if (phantom?.isConnected && phantom?.publicKey) {
55
+ return phantom.publicKey.toString();
56
+ }
57
+ return null;
58
+ }, []);
59
+
60
+ /**
61
+ * Calculate optimal priority fee based on recent network activity
62
+ */
63
+ const calculatePriorityFee = useCallback(async (connection: Connection, fromPubkey: PublicKey): Promise<number> => {
64
+ let priorityFee = 10000; // Default fallback (10,000 micro-lamports)
65
+
66
+ try {
67
+ const recentFees = await connection.getRecentPrioritizationFees({
68
+ lockedWritableAccounts: [fromPubkey],
69
+ });
70
+
71
+ if (recentFees && recentFees.length > 0) {
72
+ // Use 75th percentile of recent fees for good priority
73
+ const sortedFees = recentFees.map(fee => fee.prioritizationFee).sort((a, b) => a - b);
74
+ const percentile75Index = Math.floor(sortedFees.length * 0.75);
75
+ priorityFee = Math.max(sortedFees[percentile75Index] || 10000, 10000);
76
+ }
77
+ } catch (feeError) {
78
+ console.warn("Failed to fetch recent priority fees, using default:", feeError);
79
+ }
80
+
81
+ return priorityFee;
82
+ }, []);
83
+
84
+ /**
85
+ * Create a native SOL transfer transaction with priority fees
86
+ */
87
+ const createNativeTransferTransaction = useCallback(
88
+ async (
89
+ _connection: Connection,
90
+ fromPubkey: PublicKey,
91
+ toPubkey: PublicKey,
92
+ amount: bigint,
93
+ priorityFee: number,
94
+ ): Promise<Transaction> => {
95
+ const computeUnitLimit = 1000; // SOL transfer + compute budget instructions need ~600-800 CU
96
+ const computeUnitPrice = Math.min(priorityFee, 100000); // Cap at 100k micro-lamports for safety
97
+
98
+ const transaction = new Transaction()
99
+ .add(
100
+ // Set compute unit limit first (must come before other instructions)
101
+ ComputeBudgetProgram.setComputeUnitLimit({
102
+ units: computeUnitLimit,
103
+ }),
104
+ )
105
+ .add(
106
+ // Set priority fee
107
+ ComputeBudgetProgram.setComputeUnitPrice({
108
+ microLamports: computeUnitPrice,
109
+ }),
110
+ )
111
+ .add(
112
+ // Actual transfer instruction
113
+ SystemProgram.transfer({
114
+ fromPubkey,
115
+ toPubkey,
116
+ lamports: Number(amount),
117
+ }),
118
+ );
119
+
120
+ console.log(`Using priority fee: ${computeUnitPrice} micro-lamports per CU, limit: ${computeUnitLimit} CU`);
121
+
122
+ return transaction;
123
+ },
124
+ [],
125
+ );
126
+
127
+ /**
128
+ * Create an SPL token transfer transaction with priority fees
129
+ */
130
+ const createSPLTransferTransaction = useCallback(
131
+ async (
132
+ connection: Connection,
133
+ fromPubkey: PublicKey,
134
+ toPubkey: PublicKey,
135
+ mintPubkey: PublicKey,
136
+ amount: bigint,
137
+ priorityFee: number,
138
+ ): Promise<Transaction> => {
139
+ // Get associated token accounts
140
+ const fromTokenAccount = getAssociatedTokenAddressSync(mintPubkey, fromPubkey);
141
+ const toTokenAccount = getAssociatedTokenAddressSync(mintPubkey, toPubkey);
142
+
143
+ // Check if destination token account exists
144
+ const toTokenAccountInfo = await connection.getAccountInfo(toTokenAccount);
145
+ const needsDestinationAccount = !toTokenAccountInfo;
146
+
147
+ // Get mint info to determine decimals
148
+ const mintInfo = await connection.getParsedAccountInfo(mintPubkey);
149
+ const decimals = (mintInfo.value?.data as any)?.parsed?.info?.decimals || 9;
150
+
151
+ // SPL transfers need more compute units than SOL transfers
152
+ // Add extra CU if we need to create destination account
153
+ const computeUnitLimit = needsDestinationAccount ? 40000 : 20000;
154
+ const computeUnitPrice = Math.min(priorityFee, 100000);
155
+
156
+ // Create transfer instruction
157
+ const transferInstruction = createTransferCheckedInstruction(
158
+ fromTokenAccount,
159
+ mintPubkey,
160
+ toTokenAccount,
161
+ fromPubkey,
162
+ Number(amount),
163
+ decimals,
164
+ );
165
+
166
+ const transaction = new Transaction()
167
+ .add(
168
+ ComputeBudgetProgram.setComputeUnitLimit({
169
+ units: computeUnitLimit,
170
+ }),
171
+ )
172
+ .add(
173
+ ComputeBudgetProgram.setComputeUnitPrice({
174
+ microLamports: computeUnitPrice,
175
+ }),
176
+ );
177
+
178
+ // Add create destination account instruction if needed
179
+ if (needsDestinationAccount) {
180
+ transaction.add(
181
+ createAssociatedTokenAccountInstruction(
182
+ fromPubkey, // payer
183
+ toTokenAccount, // ata
184
+ toPubkey, // owner
185
+ mintPubkey, // mint
186
+ ),
187
+ );
188
+ }
189
+
190
+ // Add the transfer instruction
191
+ transaction.add(transferInstruction);
192
+
193
+ console.log(
194
+ `SPL Token transfer: ${computeUnitPrice} micro-lamports per CU, limit: ${computeUnitLimit} CU, creating destination: ${needsDestinationAccount}`,
195
+ );
196
+
197
+ return transaction;
198
+ },
199
+ [],
200
+ );
201
+
202
+ /**
203
+ * Initiate a Phantom wallet transfer for SOL or SPL tokens
204
+ */
205
+ const initiateTransfer = useCallback(
206
+ async ({ amountLamports, tokenAddress, recipientAddress }: PhantomTransferParams): Promise<void> => {
207
+ try {
208
+ // Step 1: Check if Phantom is installed
209
+ if (!isPhantomAvailable) {
210
+ toast.error("Phantom wallet not installed. Please install Phantom wallet to continue.");
211
+ return;
212
+ }
213
+
214
+ // Step 2: Ensure Phantom is connected/unlocked
215
+ const phantom = (window as any).phantom?.solana;
216
+ if (!phantom) {
217
+ toast.error("Phantom wallet not accessible");
218
+ return;
219
+ }
220
+
221
+ // Connect and unlock wallet if needed
222
+ let publicKey;
223
+ try {
224
+ const connection = await phantom.connect();
225
+ publicKey = connection.publicKey;
226
+ } catch (connectError) {
227
+ toast.error("Failed to connect to Phantom wallet");
228
+ return;
229
+ }
230
+
231
+ // Step 3: Setup connection and public keys
232
+ const connection = new Connection(effectiveRpcEndpoint);
233
+ const fromPubkey = new PublicKey(publicKey.toString());
234
+ const toPubkey = new PublicKey(recipientAddress);
235
+ const amount = BigInt(amountLamports);
236
+
237
+ // Step 4: Calculate optimal priority fee
238
+ const priorityFee = await calculatePriorityFee(connection, fromPubkey);
239
+
240
+ // Step 5: Create transaction based on token type
241
+ let transaction: Transaction;
242
+
243
+ if (tokenAddress === "11111111111111111111111111111111") {
244
+ // Native SOL transfer
245
+ transaction = await createNativeTransferTransaction(connection, fromPubkey, toPubkey, amount, priorityFee);
246
+ } else {
247
+ // SPL Token transfer
248
+ const mintPubkey = new PublicKey(tokenAddress);
249
+ transaction = await createSPLTransferTransaction(
250
+ connection,
251
+ fromPubkey,
252
+ toPubkey,
253
+ mintPubkey,
254
+ amount,
255
+ priorityFee,
256
+ );
257
+ }
258
+
259
+ // Step 6: Get latest blockhash and set fee payer
260
+ const { blockhash } = await connection.getLatestBlockhash("confirmed");
261
+ transaction.recentBlockhash = blockhash;
262
+ transaction.feePayer = fromPubkey;
263
+
264
+ // Step 7: Sign and send transaction
265
+ const signedTransaction = await phantom.signAndSendTransaction(transaction);
266
+
267
+ toast.success(`Transaction successful! Signature: ${signedTransaction.signature}`);
268
+ console.log("Transaction sent with priority fees. Signature:", signedTransaction.signature);
269
+ } catch (error: unknown) {
270
+ console.error("Transfer error:", error);
271
+ const errorMessage = error instanceof Error ? error.message : String(error);
272
+
273
+ if (errorMessage.includes("User rejected")) {
274
+ toast.error("Transaction was cancelled by user");
275
+ } else if (errorMessage.includes("insufficient")) {
276
+ toast.error("Insufficient balance for this transaction");
277
+ } else if (errorMessage.includes("blockhash not found")) {
278
+ toast.error("Network congestion detected. Please try again in a moment.");
279
+ } else {
280
+ toast.error(`Transfer failed: ${errorMessage}`);
281
+ }
282
+ }
283
+ },
284
+ [
285
+ isPhantomAvailable,
286
+ effectiveRpcEndpoint,
287
+ calculatePriorityFee,
288
+ createNativeTransferTransaction,
289
+ createSPLTransferTransaction,
290
+ ],
291
+ );
292
+
293
+ return {
294
+ /** Function to initiate a transfer */
295
+ initiateTransfer,
296
+ /** Whether Phantom wallet is available (installed) */
297
+ isPhantomAvailable,
298
+ /** Get the currently connected Phantom wallet address */
299
+ getConnectedAddress,
300
+ };
301
+ }
@@ -39,6 +39,7 @@ export function SignInWithB3Flow({
39
39
  const { setB3ModalContentType, setB3ModalOpen, isOpen } = useModalStore();
40
40
  const account = useActiveAccount();
41
41
  const isAuthenticating = useAuthStore(state => state.isAuthenticating);
42
+ const isAuthenticated = useAuthStore(state => state.isAuthenticated);
42
43
  const isConnected = useAuthStore(state => state.isConnected);
43
44
  const [refetchCount, setRefetchCount] = useState(0);
44
45
  const [refetchError, setRefetchError] = useState<string | null>(null);
@@ -92,7 +93,7 @@ export function SignInWithB3Flow({
92
93
  source,
93
94
  });
94
95
 
95
- if (isConnected) {
96
+ if (isConnected && isAuthenticated) {
96
97
  // Check if we already have a signer for this partner
97
98
  const hasExistingSigner = signers?.some(signer => signer.partner.id === partnerId);
98
99
  if (hasExistingSigner) {
@@ -139,6 +140,7 @@ export function SignInWithB3Flow({
139
140
  signersEnabled,
140
141
  isConnected,
141
142
  isAuthenticating,
143
+ isAuthenticated,
142
144
  isOpen,
143
145
  ]);
144
146
 
@@ -38,11 +38,12 @@ export { useSearchParamsSSR } from "./useSearchParamsSSR";
38
38
  export { useSimBalance } from "./useSimBalance";
39
39
  export { useSiwe } from "./useSiwe";
40
40
  export { useTokenBalance } from "./useTokenBalance";
41
+ export { useTokenBalanceDirect } from "./useTokenBalanceDirect";
41
42
  export { useTokenBalancesByChain } from "./useTokenBalancesByChain";
42
43
  export { useTokenData } from "./useTokenData";
43
44
  export { useTokenFromUrl } from "./useTokenFromUrl";
44
45
  export { useTokenPrice } from "./useTokenPrice";
45
46
  export { useTokenPriceWithFallback } from "./useTokenPriceWithFallback";
46
47
  export { useTokensFromAddress } from "./useTokensFromAddress";
47
- export { useUnifiedChainSwitchAndExecute } from "./useUnifiedChainSwitchAndExecute";
48
48
  export { useURLParams } from "./useURLParams";
49
+ export { useUnifiedChainSwitchAndExecute } from "./useUnifiedChainSwitchAndExecute";
@@ -26,10 +26,11 @@ export interface SimBalanceResponse {
26
26
  balances: SimBalanceItem[];
27
27
  }
28
28
 
29
- async function fetchSimBalance(address: string): Promise<SimBalanceResponse> {
29
+ async function fetchSimBalance(address: string, chainIdsParam: number[]): Promise<SimBalanceResponse> {
30
30
  if (!address) throw new Error("Address is required");
31
31
 
32
- let url = `https://simdune-api.sean-430.workers.dev/?url=https://api.sim.dune.com/v1/evm/balances/${address}?metadata=logo&chain_ids=mainnet`;
32
+ const chainIds = chainIdsParam.length === 0 ? "mainnet" : chainIdsParam.join(",");
33
+ let url = `https://simdune-api.sean-430.workers.dev/?url=https://api.sim.dune.com/v1/evm/balances/${address}?metadata=logo&chain_ids=${chainIds}`;
33
34
  if (process.env.NEXT_PUBLIC_LOCAL_KEY) {
34
35
  url += `&localkey=${process.env.NEXT_PUBLIC_LOCAL_KEY}`;
35
36
  }
@@ -44,12 +45,12 @@ async function fetchSimBalance(address: string): Promise<SimBalanceResponse> {
44
45
  return balanceData;
45
46
  }
46
47
 
47
- export function useSimBalance(address?: string) {
48
+ export function useSimBalance(address?: string, chainIdsParam?: number[]) {
48
49
  return useQuery({
49
- queryKey: ["simBalance", address],
50
+ queryKey: ["simBalance", address, chainIdsParam],
50
51
  queryFn: () => {
51
52
  if (!address) throw new Error("Address is required");
52
- return fetchSimBalance(address);
53
+ return fetchSimBalance(address, chainIdsParam || []);
53
54
  },
54
55
  enabled: Boolean(address),
55
56
  });
@@ -0,0 +1,84 @@
1
+ "use client";
2
+
3
+ import { isNativeToken } from "@b3dotfun/sdk/anyspend";
4
+ import { components } from "@b3dotfun/sdk/anyspend/types/api";
5
+ import { useAccountWallet } from "@b3dotfun/sdk/global-account/react";
6
+ import { formatTokenAmount } from "@b3dotfun/sdk/shared/utils/number";
7
+ import { getERC20Balances, getNativeTokenBalance } from "@b3dotfun/sdk/shared/utils/thirdweb-insights";
8
+ import { useQuery } from "@tanstack/react-query";
9
+ import { useEffect } from "react";
10
+
11
+ interface UseTokenBalanceProps {
12
+ token: components["schemas"]["Token"];
13
+ address?: string;
14
+ }
15
+
16
+ export interface TokenBalanceResult {
17
+ rawBalance: bigint | null;
18
+ formattedBalance: string;
19
+ isLoading: boolean;
20
+ }
21
+
22
+ export function useTokenBalanceDirect({ token, address }: UseTokenBalanceProps): TokenBalanceResult {
23
+ const account = useAccountWallet();
24
+
25
+ const effectiveAddress = address || account?.address;
26
+
27
+ const {
28
+ data: tokenBalance,
29
+ isLoading,
30
+ isFetching,
31
+ refetch,
32
+ } = useQuery({
33
+ queryKey: ["tokenBalance", effectiveAddress, token.chainId, token.address],
34
+ queryFn: async (): Promise<{ formatted: string; raw: bigint | null }> => {
35
+ if (!effectiveAddress) return { formatted: "0", raw: null };
36
+
37
+ if (isNativeToken(token.address)) {
38
+ const nativeToken = await getNativeTokenBalance(effectiveAddress, token.chainId);
39
+ if (nativeToken && nativeToken.balance) {
40
+ const rawBalance = nativeToken.balance;
41
+ return {
42
+ formatted: formatTokenAmount(BigInt(rawBalance), Number(nativeToken.decimals || 18)),
43
+ raw: BigInt(rawBalance),
44
+ };
45
+ }
46
+ return { formatted: "0", raw: null };
47
+ }
48
+
49
+ const response = await getERC20Balances(effectiveAddress, {
50
+ chainIds: [token.chainId],
51
+ includeSpam: false,
52
+ });
53
+ const tokenBalance = response.data?.find(t => t.token_address === token.address);
54
+ if (tokenBalance?.balance) {
55
+ return {
56
+ formatted: formatTokenAmount(BigInt(tokenBalance.balance), Number(tokenBalance.decimals || 18)),
57
+ raw: BigInt(tokenBalance.balance),
58
+ };
59
+ }
60
+ return { formatted: "0", raw: null };
61
+ },
62
+ enabled: !!effectiveAddress,
63
+ staleTime: 30000,
64
+ gcTime: 5 * 60 * 1000,
65
+ retry: 2,
66
+ structuralSharing: false,
67
+ });
68
+
69
+ // Force a refetch when the wallet or token changes
70
+ useEffect(() => {
71
+ if (effectiveAddress) {
72
+ refetch();
73
+ }
74
+ }, [effectiveAddress, token.address, token.chainId, token.symbol, refetch]);
75
+
76
+ // Determine if we're actually loading
77
+ const isActuallyLoading = !effectiveAddress || isLoading || (isFetching && !tokenBalance);
78
+
79
+ return {
80
+ rawBalance: tokenBalance?.raw || BigInt(0),
81
+ formattedBalance: tokenBalance?.formatted || "0",
82
+ isLoading: isActuallyLoading,
83
+ };
84
+ }
@@ -1,9 +1,9 @@
1
1
  "use client";
2
2
 
3
+ import { components } from "@b3dotfun/sdk/anyspend/types/api";
3
4
  import { getCoingeckoChainInfo } from "@b3dotfun/sdk/shared/constants/chains/supported";
4
5
  import { useSearchParams } from "@b3dotfun/sdk/shared/react/hooks";
5
6
  import { useQuery } from "@tanstack/react-query";
6
- import { components } from "@b3dotfun/sdk/anyspend/types/api";
7
7
 
8
8
  interface UseTokenFromUrlOptions {
9
9
  /**
@@ -59,14 +59,15 @@ export function useTokenFromUrl({ defaultToken, prefix }: UseTokenFromUrlOptions
59
59
  const currencyParam = searchParams.get(`${prefix}Currency`);
60
60
  const chainIdParam = searchParams.get(`${prefix}ChainId`);
61
61
 
62
+ // Determine network based on chainId
63
+ const chainInfo = chainIdParam ? getCoingeckoChainInfo(Number(chainIdParam)) : null;
64
+ const network = chainInfo?.coingecko_id || "";
65
+
62
66
  // Determine if we should fetch token info
63
67
  const shouldFetchToken = Boolean(
64
- currencyParam && chainIdParam && currencyParam.toLowerCase() !== defaultToken.address.toLowerCase(),
68
+ currencyParam && chainIdParam && chainInfo && currencyParam.toLowerCase() !== defaultToken.address.toLowerCase(),
65
69
  );
66
70
 
67
- // Determine network based on chainId
68
- const network = chainIdParam ? getCoingeckoChainInfo(Number(chainIdParam)).coingecko_id : "";
69
-
70
71
  const { data: tokenInfo, isError } = useQuery({
71
72
  queryKey: ["tokenInfo", network, currencyParam],
72
73
  queryFn: () => fetchTokenInfo(network, currencyParam || ""),