@b3dotfun/sdk 0.0.62-alpha.1 → 0.0.62-alpha.3
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.
- package/dist/cjs/anyspend/react/components/AnySpend.js +61 -23
- package/dist/cjs/anyspend/react/components/AnySpendCustom.js +3 -0
- package/dist/cjs/anyspend/react/components/AnySpendStakeB3.js +5 -4
- package/dist/cjs/anyspend/react/components/AnyspendDepositHype.js +4 -4
- package/dist/cjs/anyspend/react/components/common/CryptoPaySection.js +4 -6
- package/dist/cjs/anyspend/react/components/common/CryptoPaymentMethod.js +9 -17
- package/dist/cjs/anyspend/react/components/common/CryptoReceiveSection.d.ts +6 -1
- package/dist/cjs/anyspend/react/components/common/CryptoReceiveSection.js +11 -1
- package/dist/cjs/anyspend/react/components/common/OrderDetails.js +56 -145
- package/dist/cjs/anyspend/react/components/common/OrderTokenAmount.d.ts +2 -1
- package/dist/cjs/anyspend/react/components/common/OrderTokenAmount.js +39 -15
- package/dist/cjs/anyspend/react/components/common/PaySection.js +1 -1
- package/dist/cjs/anyspend/react/components/common/TokenBalance.js +1 -1
- package/dist/cjs/anyspend/react/hooks/useAnyspendFlow.js +12 -11
- package/dist/cjs/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.d.ts +26 -0
- package/dist/cjs/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.js +56 -0
- package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
- package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +73 -0
- package/dist/cjs/anyspend/react/hooks/useConnectedWalletDisplay.d.ts +14 -0
- package/dist/cjs/anyspend/react/hooks/useConnectedWalletDisplay.js +57 -0
- package/dist/cjs/anyspend/react/hooks/usePhantomTransfer.d.ts +36 -0
- package/dist/cjs/anyspend/react/hooks/usePhantomTransfer.js +211 -0
- package/dist/cjs/global-account/react/hooks/index.d.ts +2 -1
- package/dist/cjs/global-account/react/hooks/index.js +5 -3
- package/dist/cjs/global-account/react/hooks/useSimBalance.d.ts +1 -1
- package/dist/cjs/global-account/react/hooks/useSimBalance.js +6 -5
- package/dist/cjs/global-account/react/hooks/useTokenBalanceDirect.d.ts +12 -0
- package/dist/cjs/global-account/react/hooks/useTokenBalanceDirect.js +62 -0
- package/dist/cjs/global-account/react/hooks/useTokenFromUrl.js +4 -3
- package/dist/esm/anyspend/react/components/AnySpend.js +62 -24
- package/dist/esm/anyspend/react/components/AnySpendCustom.js +3 -0
- package/dist/esm/anyspend/react/components/AnySpendStakeB3.js +7 -6
- package/dist/esm/anyspend/react/components/AnyspendDepositHype.js +4 -4
- package/dist/esm/anyspend/react/components/common/CryptoPaySection.js +5 -7
- package/dist/esm/anyspend/react/components/common/CryptoPaymentMethod.js +9 -17
- package/dist/esm/anyspend/react/components/common/CryptoReceiveSection.d.ts +6 -1
- package/dist/esm/anyspend/react/components/common/CryptoReceiveSection.js +11 -1
- package/dist/esm/anyspend/react/components/common/OrderDetails.js +57 -146
- package/dist/esm/anyspend/react/components/common/OrderTokenAmount.d.ts +2 -1
- package/dist/esm/anyspend/react/components/common/OrderTokenAmount.js +40 -16
- package/dist/esm/anyspend/react/components/common/PaySection.js +1 -1
- package/dist/esm/anyspend/react/components/common/TokenBalance.js +2 -2
- package/dist/esm/anyspend/react/hooks/useAnyspendFlow.js +12 -11
- package/dist/esm/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.d.ts +26 -0
- package/dist/esm/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.js +53 -0
- package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
- package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +70 -0
- package/dist/esm/anyspend/react/hooks/useConnectedWalletDisplay.d.ts +14 -0
- package/dist/esm/anyspend/react/hooks/useConnectedWalletDisplay.js +54 -0
- package/dist/esm/anyspend/react/hooks/usePhantomTransfer.d.ts +36 -0
- package/dist/esm/anyspend/react/hooks/usePhantomTransfer.js +208 -0
- package/dist/esm/global-account/react/hooks/index.d.ts +2 -1
- package/dist/esm/global-account/react/hooks/index.js +2 -1
- package/dist/esm/global-account/react/hooks/useSimBalance.d.ts +1 -1
- package/dist/esm/global-account/react/hooks/useSimBalance.js +6 -5
- package/dist/esm/global-account/react/hooks/useTokenBalanceDirect.d.ts +12 -0
- package/dist/esm/global-account/react/hooks/useTokenBalanceDirect.js +59 -0
- package/dist/esm/global-account/react/hooks/useTokenFromUrl.js +4 -3
- package/dist/types/anyspend/react/components/common/CryptoReceiveSection.d.ts +6 -1
- package/dist/types/anyspend/react/components/common/OrderTokenAmount.d.ts +2 -1
- package/dist/types/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.d.ts +26 -0
- package/dist/types/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
- package/dist/types/anyspend/react/hooks/useConnectedWalletDisplay.d.ts +14 -0
- package/dist/types/anyspend/react/hooks/usePhantomTransfer.d.ts +36 -0
- package/dist/types/global-account/react/hooks/index.d.ts +2 -1
- package/dist/types/global-account/react/hooks/useSimBalance.d.ts +1 -1
- package/dist/types/global-account/react/hooks/useTokenBalanceDirect.d.ts +12 -0
- package/package.json +1 -1
- package/src/anyspend/react/components/AnySpend.tsx +73 -22
- package/src/anyspend/react/components/AnySpendCustom.tsx +4 -0
- package/src/anyspend/react/components/AnySpendStakeB3.tsx +8 -11
- package/src/anyspend/react/components/AnyspendDepositHype.tsx +7 -3
- package/src/anyspend/react/components/common/CryptoPaySection.tsx +5 -7
- package/src/anyspend/react/components/common/CryptoPaymentMethod.tsx +9 -18
- package/src/anyspend/react/components/common/CryptoReceiveSection.tsx +22 -0
- package/src/anyspend/react/components/common/OrderDetails.tsx +66 -188
- package/src/anyspend/react/components/common/OrderTokenAmount.tsx +48 -17
- package/src/anyspend/react/components/common/PaySection.tsx +1 -0
- package/src/anyspend/react/components/common/TokenBalance.tsx +2 -2
- package/src/anyspend/react/hooks/useAnyspendFlow.ts +13 -10
- package/src/anyspend/react/hooks/useAutoSelectCryptoPaymentMethod.ts +72 -0
- package/src/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.ts +80 -0
- package/src/anyspend/react/hooks/useConnectedWalletDisplay.ts +69 -0
- package/src/anyspend/react/hooks/usePhantomTransfer.ts +301 -0
- package/src/global-account/react/hooks/index.ts +2 -1
- package/src/global-account/react/hooks/useSimBalance.ts +6 -5
- package/src/global-account/react/hooks/useTokenBalanceDirect.tsx +84 -0
- package/src/global-account/react/hooks/useTokenFromUrl.tsx +6 -5
|
@@ -12,8 +12,6 @@ const hooks_1 = require("../../../../shared/react/hooks");
|
|
|
12
12
|
const utils_1 = require("../../../../shared/utils");
|
|
13
13
|
const centerTruncate_1 = __importDefault(require("../../../../shared/utils/centerTruncate"));
|
|
14
14
|
const number_1 = require("../../../../shared/utils/number");
|
|
15
|
-
const spl_token_1 = require("@solana/spl-token");
|
|
16
|
-
const web3_js_1 = require("@solana/web3.js");
|
|
17
15
|
const react_2 = require("@web3icons/react");
|
|
18
16
|
const lucide_react_1 = require("lucide-react");
|
|
19
17
|
const react_3 = require("motion/react");
|
|
@@ -24,6 +22,7 @@ const sonner_1 = require("sonner");
|
|
|
24
22
|
const viem_1 = require("viem");
|
|
25
23
|
const chains_1 = require("viem/chains");
|
|
26
24
|
const wagmi_1 = require("wagmi");
|
|
25
|
+
const usePhantomTransfer_1 = require("../../hooks/usePhantomTransfer");
|
|
27
26
|
const Accordion_1 = require("./Accordion");
|
|
28
27
|
const ConnectWalletPayment_1 = __importDefault(require("./ConnectWalletPayment"));
|
|
29
28
|
const CryptoPaymentMethod_1 = require("./CryptoPaymentMethod");
|
|
@@ -155,6 +154,10 @@ exports.OrderDetails = (0, react_4.memo)(function OrderDetails({ mode = "modal",
|
|
|
155
154
|
const [showQRCode, setShowQRCode] = (0, react_4.useState)(false);
|
|
156
155
|
const { isLoading: txLoading, isSuccess: txSuccess } = (0, wagmi_1.useWaitForTransactionReceipt)({ hash: txHash });
|
|
157
156
|
const { switchChainAndExecuteWithEOA, switchChainAndExecute, isSwitchingOrExecuting } = (0, react_1.useUnifiedChainSwitchAndExecute)();
|
|
157
|
+
// Track if auto-payment was attempted to avoid re-triggering
|
|
158
|
+
const autoPaymentAttempted = (0, react_4.useRef)(false);
|
|
159
|
+
// Track if component is ready for auto-payment (all data loaded)
|
|
160
|
+
const [isComponentReady, setIsComponentReady] = (0, react_4.useState)(false);
|
|
158
161
|
const roundedUpSrcAmount = (0, react_4.useMemo)(() => {
|
|
159
162
|
// Display the full transfer amount without rounding since users need to see the exact value they're transferring.
|
|
160
163
|
// Use 21 significant digits (max allowed by Intl.NumberFormat)
|
|
@@ -210,19 +213,25 @@ exports.OrderDetails = (0, react_4.memo)(function OrderDetails({ mode = "modal",
|
|
|
210
213
|
setTxHash(txHash);
|
|
211
214
|
}
|
|
212
215
|
}, [order, switchChainAndExecuteWithEOA, switchChainAndExecute, depositDeficit, effectiveCryptoPaymentMethod]);
|
|
216
|
+
// Use Phantom transfer hook for Solana payments
|
|
217
|
+
const { initiateTransfer: initiatePhantomTransfer, getConnectedAddress: getPhantomAddress } = (0, usePhantomTransfer_1.usePhantomTransfer)();
|
|
213
218
|
// Main payment handler that triggers chain switch and payment
|
|
214
|
-
const handlePayment = async () => {
|
|
219
|
+
const handlePayment = (0, react_4.useCallback)(async () => {
|
|
215
220
|
console.log("Initiating payment process. Target chain:", order.srcChain, "Current chain:", walletClient?.chain?.id);
|
|
216
221
|
if (order.srcChain === anyspend_1.RELAY_SOLANA_MAINNET_CHAIN_ID) {
|
|
217
222
|
// Use the existing depositDeficit calculation to determine amount to send
|
|
218
223
|
const amountToSend = depositDeficit > BigInt(0) ? depositDeficit.toString() : order.srcAmount;
|
|
219
|
-
await initiatePhantomTransfer(
|
|
224
|
+
await initiatePhantomTransfer({
|
|
225
|
+
amountLamports: amountToSend,
|
|
226
|
+
tokenAddress: order.srcTokenAddress,
|
|
227
|
+
recipientAddress: order.globalAddress,
|
|
228
|
+
});
|
|
220
229
|
}
|
|
221
230
|
else {
|
|
222
231
|
// Use unified payment process for both EOA and AA wallets
|
|
223
232
|
await handleUnifiedPaymentProcess();
|
|
224
233
|
}
|
|
225
|
-
};
|
|
234
|
+
}, [order, walletClient?.chain?.id, depositDeficit, handleUnifiedPaymentProcess, initiatePhantomTransfer]);
|
|
226
235
|
// When waitingForDeposit is true, we show a message to the user to wait for the deposit to be processed.
|
|
227
236
|
const setWaitingForDeposit = (0, react_4.useCallback)(() => {
|
|
228
237
|
if (disableUrlParamManagement)
|
|
@@ -260,16 +269,50 @@ exports.OrderDetails = (0, react_4.memo)(function OrderDetails({ mode = "modal",
|
|
|
260
269
|
setTxHash(undefined);
|
|
261
270
|
}
|
|
262
271
|
}, [setWaitingForDeposit, txSuccess]);
|
|
263
|
-
const isPhantomMobile = (0, react_4.useMemo)(() => navigator.userAgent.includes("Phantom"), []);
|
|
264
|
-
const isPhantomBrowser = (0, react_4.useMemo)(() => window.phantom?.solana?.isPhantom, []);
|
|
265
272
|
// Get connected Phantom wallet address if available
|
|
266
|
-
const phantomWalletAddress = (0, react_4.useMemo)(() =>
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
273
|
+
const phantomWalletAddress = (0, react_4.useMemo)(() => getPhantomAddress(), [getPhantomAddress]);
|
|
274
|
+
// Calculate status display before using it
|
|
275
|
+
const { text: statusText, status: statusDisplay } = (0, anyspend_1.getStatusDisplay)(order);
|
|
276
|
+
// Memoize the payable state calculation to avoid recalculating on every render
|
|
277
|
+
const isPayableState = (0, react_4.useMemo)(() => {
|
|
278
|
+
const waitingForDeposit = new URLSearchParams(window.location.search).get("waitingForDeposit") === "true";
|
|
279
|
+
return (refundTxs.length === 0 &&
|
|
280
|
+
!executeTx &&
|
|
281
|
+
!(relayTxs.length > 0 && relayTxs.every(tx => tx.status === "success")) &&
|
|
282
|
+
!depositTxs?.length &&
|
|
283
|
+
!waitingForDeposit &&
|
|
284
|
+
statusDisplay === "processing" &&
|
|
285
|
+
!order.onrampMetadata &&
|
|
286
|
+
(effectiveCryptoPaymentMethod === CryptoPaymentMethod_1.CryptoPaymentMethodType.CONNECT_WALLET ||
|
|
287
|
+
effectiveCryptoPaymentMethod === CryptoPaymentMethod_1.CryptoPaymentMethodType.GLOBAL_WALLET));
|
|
288
|
+
}, [
|
|
289
|
+
refundTxs.length,
|
|
290
|
+
executeTx,
|
|
291
|
+
relayTxs,
|
|
292
|
+
depositTxs?.length,
|
|
293
|
+
statusDisplay,
|
|
294
|
+
order.onrampMetadata,
|
|
295
|
+
effectiveCryptoPaymentMethod,
|
|
296
|
+
]);
|
|
297
|
+
// Mark component as ready once all critical data is available
|
|
298
|
+
// This ensures we don't trigger payment before the component has fully initialized
|
|
299
|
+
(0, react_4.useEffect)(() => {
|
|
300
|
+
if (!isComponentReady && srcToken && dstToken && statusDisplay) {
|
|
301
|
+
setIsComponentReady(true);
|
|
270
302
|
}
|
|
271
|
-
|
|
272
|
-
|
|
303
|
+
}, [isComponentReady, srcToken, dstToken, statusDisplay]);
|
|
304
|
+
// Auto-trigger payment when component is ready and order is in payable state
|
|
305
|
+
// This effect only runs when isPayableState or isComponentReady changes
|
|
306
|
+
(0, react_4.useEffect)(() => {
|
|
307
|
+
// Only trigger payment if:
|
|
308
|
+
// 1. We haven't attempted payment yet
|
|
309
|
+
// 2. Component is fully ready (all data loaded)
|
|
310
|
+
// 3. Order is in a payable state
|
|
311
|
+
if (!autoPaymentAttempted.current && isComponentReady && isPayableState) {
|
|
312
|
+
autoPaymentAttempted.current = true;
|
|
313
|
+
handlePayment();
|
|
314
|
+
}
|
|
315
|
+
}, [isPayableState, isComponentReady, handlePayment]);
|
|
273
316
|
if (!srcToken || !dstToken) {
|
|
274
317
|
return (0, jsx_runtime_1.jsx)("div", { children: "Loading..." });
|
|
275
318
|
}
|
|
@@ -284,138 +327,6 @@ exports.OrderDetails = (0, react_4.memo)(function OrderDetails({ mode = "modal",
|
|
|
284
327
|
const formattedActualDstAmount = actualDstAmount
|
|
285
328
|
? (0, number_1.formatTokenAmount)(BigInt(actualDstAmount), dstToken.decimals)
|
|
286
329
|
: undefined;
|
|
287
|
-
const { text: statusText, status: statusDisplay } = (0, anyspend_1.getStatusDisplay)(order);
|
|
288
|
-
const initiatePhantomTransfer = async (amountLamports, tokenAddress, recipientAddress) => {
|
|
289
|
-
try {
|
|
290
|
-
if (!isPhantomBrowser && !isPhantomMobile) {
|
|
291
|
-
sonner_1.toast.error("Phantom wallet not installed. Please install Phantom wallet to continue.");
|
|
292
|
-
return;
|
|
293
|
-
}
|
|
294
|
-
// Step 2: Ensure Phantom is connected/unlocked
|
|
295
|
-
const phantom = window.phantom?.solana;
|
|
296
|
-
if (!phantom) {
|
|
297
|
-
sonner_1.toast.error("Phantom wallet not accessible");
|
|
298
|
-
return;
|
|
299
|
-
}
|
|
300
|
-
// Connect and unlock wallet if needed
|
|
301
|
-
let publicKey;
|
|
302
|
-
try {
|
|
303
|
-
const connection = await phantom.connect();
|
|
304
|
-
publicKey = connection.publicKey;
|
|
305
|
-
}
|
|
306
|
-
catch (connectError) {
|
|
307
|
-
sonner_1.toast.error("Failed to connect to Phantom wallet");
|
|
308
|
-
return;
|
|
309
|
-
}
|
|
310
|
-
// Step 3: Create transaction with priority fees
|
|
311
|
-
const connection = new web3_js_1.Connection("https://mainnet.helius-rpc.com/?api-key=efafd9b3-1807-4cf8-8aa4-3d984f56d8fb");
|
|
312
|
-
const fromPubkey = new web3_js_1.PublicKey(publicKey.toString());
|
|
313
|
-
const toPubkey = new web3_js_1.PublicKey(recipientAddress);
|
|
314
|
-
const amount = BigInt(amountLamports);
|
|
315
|
-
// Step 4: Get recent priority fees to determine optimal pricing
|
|
316
|
-
let priorityFee = 10000; // Default fallback (10,000 micro-lamports)
|
|
317
|
-
try {
|
|
318
|
-
const recentFees = await connection.getRecentPrioritizationFees({
|
|
319
|
-
lockedWritableAccounts: [fromPubkey],
|
|
320
|
-
});
|
|
321
|
-
if (recentFees && recentFees.length > 0) {
|
|
322
|
-
// Use 75th percentile of recent fees for good priority
|
|
323
|
-
const sortedFees = recentFees.map(fee => fee.prioritizationFee).sort((a, b) => a - b);
|
|
324
|
-
const percentile75Index = Math.floor(sortedFees.length * 0.75);
|
|
325
|
-
priorityFee = Math.max(sortedFees[percentile75Index] || 10000, 10000);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
catch (feeError) {
|
|
329
|
-
console.warn("Failed to fetch recent priority fees, using default:", feeError);
|
|
330
|
-
}
|
|
331
|
-
let transaction;
|
|
332
|
-
// Check if this is native SOL transfer
|
|
333
|
-
if (tokenAddress === "11111111111111111111111111111111") {
|
|
334
|
-
// Native SOL transfer with priority fees
|
|
335
|
-
const computeUnitLimit = 1000; // SOL transfer + compute budget instructions need ~600-800 CU
|
|
336
|
-
const computeUnitPrice = Math.min(priorityFee, 100000); // Cap at 100k micro-lamports for safety
|
|
337
|
-
transaction = new web3_js_1.Transaction()
|
|
338
|
-
.add(
|
|
339
|
-
// Set compute unit limit first (must come before other instructions)
|
|
340
|
-
web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({
|
|
341
|
-
units: computeUnitLimit,
|
|
342
|
-
}))
|
|
343
|
-
.add(
|
|
344
|
-
// Set priority fee
|
|
345
|
-
web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({
|
|
346
|
-
microLamports: computeUnitPrice,
|
|
347
|
-
}))
|
|
348
|
-
.add(
|
|
349
|
-
// Actual transfer instruction
|
|
350
|
-
web3_js_1.SystemProgram.transfer({
|
|
351
|
-
fromPubkey,
|
|
352
|
-
toPubkey,
|
|
353
|
-
lamports: Number(amount),
|
|
354
|
-
}));
|
|
355
|
-
console.log(`Using priority fee: ${computeUnitPrice} micro-lamports per CU, limit: ${computeUnitLimit} CU`);
|
|
356
|
-
}
|
|
357
|
-
else {
|
|
358
|
-
// SPL Token transfer with priority fees
|
|
359
|
-
const mintPubkey = new web3_js_1.PublicKey(tokenAddress);
|
|
360
|
-
// Get associated token accounts
|
|
361
|
-
const fromTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(mintPubkey, fromPubkey);
|
|
362
|
-
const toTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(mintPubkey, toPubkey);
|
|
363
|
-
// Check if destination token account exists
|
|
364
|
-
const toTokenAccountInfo = await connection.getAccountInfo(toTokenAccount);
|
|
365
|
-
const needsDestinationAccount = !toTokenAccountInfo;
|
|
366
|
-
// Get mint info to determine decimals
|
|
367
|
-
const mintInfo = await connection.getParsedAccountInfo(mintPubkey);
|
|
368
|
-
const decimals = mintInfo.value?.data?.parsed?.info?.decimals || 9;
|
|
369
|
-
// SPL transfers need more compute units than SOL transfers
|
|
370
|
-
// Add extra CU if we need to create destination account
|
|
371
|
-
const computeUnitLimit = needsDestinationAccount ? 40000 : 20000;
|
|
372
|
-
const computeUnitPrice = Math.min(priorityFee, 100000);
|
|
373
|
-
// Create transfer instruction
|
|
374
|
-
const transferInstruction = (0, spl_token_1.createTransferCheckedInstruction)(fromTokenAccount, mintPubkey, toTokenAccount, fromPubkey, Number(amount), decimals);
|
|
375
|
-
transaction = new web3_js_1.Transaction()
|
|
376
|
-
.add(web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({
|
|
377
|
-
units: computeUnitLimit,
|
|
378
|
-
}))
|
|
379
|
-
.add(web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({
|
|
380
|
-
microLamports: computeUnitPrice,
|
|
381
|
-
}));
|
|
382
|
-
// Add create destination account instruction if needed
|
|
383
|
-
if (needsDestinationAccount) {
|
|
384
|
-
transaction.add((0, spl_token_1.createAssociatedTokenAccountInstruction)(fromPubkey, // payer
|
|
385
|
-
toTokenAccount, // ata
|
|
386
|
-
toPubkey, // owner
|
|
387
|
-
mintPubkey));
|
|
388
|
-
}
|
|
389
|
-
// Add the transfer instruction
|
|
390
|
-
transaction.add(transferInstruction);
|
|
391
|
-
console.log(`SPL Token transfer: ${computeUnitPrice} micro-lamports per CU, limit: ${computeUnitLimit} CU, creating destination: ${needsDestinationAccount}`);
|
|
392
|
-
}
|
|
393
|
-
// Step 5: Get latest blockhash and simulate transaction to verify
|
|
394
|
-
const { blockhash } = await connection.getLatestBlockhash("confirmed");
|
|
395
|
-
transaction.recentBlockhash = blockhash;
|
|
396
|
-
transaction.feePayer = fromPubkey;
|
|
397
|
-
// Step 6: Sign and send transaction with priority fees
|
|
398
|
-
const signedTransaction = await phantom.signAndSendTransaction(transaction);
|
|
399
|
-
sonner_1.toast.success(`Transaction successful! Signature: ${signedTransaction.signature}`);
|
|
400
|
-
console.log("Transaction sent with priority fees. Signature:", signedTransaction.signature);
|
|
401
|
-
}
|
|
402
|
-
catch (error) {
|
|
403
|
-
console.error("Transfer error:", error);
|
|
404
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
405
|
-
if (errorMessage.includes("User rejected")) {
|
|
406
|
-
sonner_1.toast.error("Transaction was cancelled by user");
|
|
407
|
-
}
|
|
408
|
-
else if (errorMessage.includes("insufficient")) {
|
|
409
|
-
sonner_1.toast.error("Insufficient balance for this transaction");
|
|
410
|
-
}
|
|
411
|
-
else if (errorMessage.includes("blockhash not found")) {
|
|
412
|
-
sonner_1.toast.error("Network congestion detected. Please try again in a moment.");
|
|
413
|
-
}
|
|
414
|
-
else {
|
|
415
|
-
sonner_1.toast.error(`Transfer failed: ${errorMessage}`);
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
};
|
|
419
330
|
if (refundTxs.length > 0) {
|
|
420
331
|
return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(OrderStatus_1.OrderStatus, { order: order, selectedCryptoPaymentMethod: effectiveCryptoPaymentMethod }), (0, jsx_runtime_1.jsx)(OrderDetailsCollapsible_1.OrderDetailsCollapsible, { order: order, dstToken: dstToken, tournament: tournament, nft: nft, recipientName: recipientName, formattedExpectedDstAmount: formattedExpectedDstAmount, points: points }), (0, jsx_runtime_1.jsx)(Accordion_1.Accordion, { type: "single", collapsible: true, className: "order-details-accordion w-full", children: (0, jsx_runtime_1.jsxs)(Accordion_1.AccordionItem, { value: "refund-details", className: "order-details-refund-item", children: [(0, jsx_runtime_1.jsx)(Accordion_1.AccordionTrigger, { className: "accordion-trigger", children: "Transaction Details" }), (0, jsx_runtime_1.jsx)(Accordion_1.AccordionContent, { className: "accordion-content pl-2", children: (0, jsx_runtime_1.jsxs)("div", { className: "relative flex w-full flex-col gap-4", children: [(0, jsx_runtime_1.jsx)("div", { className: "bg-as-surface-secondary absolute bottom-2 left-4 top-2 z-[5] w-2", children: (0, jsx_runtime_1.jsx)(react_3.motion.div, { className: "bg-as-border-primary absolute left-[2px] top-0 z-10 w-[3px]", initial: { height: "0%" }, animate: { height: "100%" }, transition: { duration: 1.5, ease: "easeInOut" } }) }), depositTxs
|
|
421
332
|
? depositTxs.map(dTx => ((0, jsx_runtime_1.jsx)(TransactionDetails, { title: order.onrampMetadata?.vendor === "stripe-web2"
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { components } from "../../../../anyspend/types/api";
|
|
2
|
-
export declare function OrderTokenAmount({ disabled, inputValue, onChangeInput, context, address, chainId, setChainId, token, setToken, hideTokenSelect, canEditAmount, className, innerClassName, amountClassName, tokenSelectClassName, onTokenSelect, }: {
|
|
2
|
+
export declare function OrderTokenAmount({ disabled, inputValue, onChangeInput, context, address, chainId, setChainId, token, setToken, hideTokenSelect, canEditAmount, className, innerClassName, amountClassName, tokenSelectClassName, onTokenSelect, walletAddress, }: {
|
|
3
3
|
disabled?: boolean;
|
|
4
4
|
inputValue: string;
|
|
5
5
|
onChangeInput: (value: string) => void;
|
|
@@ -18,4 +18,5 @@ export declare function OrderTokenAmount({ disabled, inputValue, onChangeInput,
|
|
|
18
18
|
onTokenSelect?: (token: components["schemas"]["Token"], event: {
|
|
19
19
|
preventDefault: () => void;
|
|
20
20
|
}) => void;
|
|
21
|
+
walletAddress?: string | undefined;
|
|
21
22
|
}): import("react/jsx-runtime").JSX.Element;
|
|
@@ -6,27 +6,55 @@ const jsx_runtime_1 = require("react/jsx-runtime");
|
|
|
6
6
|
const lucide_react_1 = require("lucide-react");
|
|
7
7
|
const react_1 = require("react");
|
|
8
8
|
const react_number_format_1 = require("react-number-format");
|
|
9
|
+
const viem_1 = require("viem");
|
|
9
10
|
const anyspend_1 = require("../../../../anyspend");
|
|
11
|
+
const chain_1 = require("../../../../anyspend/utils/chain");
|
|
12
|
+
const token_1 = require("../../../../anyspend/utils/token");
|
|
10
13
|
const react_2 = require("../../../../global-account/react");
|
|
11
14
|
const utils_1 = require("../../../../shared/utils");
|
|
12
15
|
const relay_kit_ui_1 = require("@relayprotocol/relay-kit-ui");
|
|
13
16
|
const ChainTokenIcon_1 = require("./ChainTokenIcon");
|
|
14
|
-
function OrderTokenAmount({ disabled, inputValue, onChangeInput, context, address, chainId, setChainId, token, setToken, hideTokenSelect = false, canEditAmount = true, className, innerClassName, amountClassName, tokenSelectClassName, onTokenSelect, }) {
|
|
17
|
+
function OrderTokenAmount({ disabled, inputValue, onChangeInput, context, address, chainId, setChainId, token, setToken, hideTokenSelect = false, canEditAmount = true, className, innerClassName, amountClassName, tokenSelectClassName, onTokenSelect, walletAddress, }) {
|
|
15
18
|
// Track previous token to detect changes
|
|
16
19
|
const prevTokenRef = (0, react_1.useRef)(token.address);
|
|
20
|
+
// Track if initial balance has been set
|
|
21
|
+
const initialBalanceSetRef = (0, react_1.useRef)(false);
|
|
22
|
+
// Only get token balance when context is "from" (for setting max amount)
|
|
23
|
+
const { rawBalance } = (0, react_2.useTokenBalance)({
|
|
24
|
+
token,
|
|
25
|
+
address: context === "from" && walletAddress ? walletAddress : undefined,
|
|
26
|
+
});
|
|
27
|
+
// Reset balance ref when token address or chain changes
|
|
17
28
|
(0, react_1.useEffect)(() => {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
29
|
+
initialBalanceSetRef.current = false;
|
|
30
|
+
}, [token.address, token.chainId]);
|
|
31
|
+
(0, react_1.useEffect)(() => {
|
|
32
|
+
// Only handle "from" context
|
|
33
|
+
if (context !== "from")
|
|
34
|
+
return;
|
|
35
|
+
// Check if token changed or if this is the initial load with balance
|
|
36
|
+
const isTokenChanged = prevTokenRef.current !== token.address;
|
|
37
|
+
const isInitialLoad = !initialBalanceSetRef.current && rawBalance;
|
|
38
|
+
if ((isTokenChanged || isInitialLoad) && rawBalance) {
|
|
39
|
+
console.log(`Setting max balance - Token: ${token.address}, Changed: ${isTokenChanged}, Initial: ${isInitialLoad}`);
|
|
40
|
+
// Calculate max amount with gas reserve for native tokens
|
|
41
|
+
let maxAmount;
|
|
42
|
+
if ((0, token_1.isNativeToken)(token.address)) {
|
|
43
|
+
const gasReserve = (0, chain_1.getNativeRequired)(token.chainId);
|
|
44
|
+
// Ensure we don't go negative
|
|
45
|
+
maxAmount = rawBalance > gasReserve ? rawBalance - gasReserve : BigInt(0);
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
// For ERC20 tokens, use full balance
|
|
49
|
+
maxAmount = rawBalance;
|
|
25
50
|
}
|
|
26
|
-
//
|
|
51
|
+
// Set the max amount as input value
|
|
52
|
+
onChangeInput((0, viem_1.formatUnits)(maxAmount, token.decimals));
|
|
53
|
+
// Update refs
|
|
27
54
|
prevTokenRef.current = token.address;
|
|
55
|
+
initialBalanceSetRef.current = true;
|
|
28
56
|
}
|
|
29
|
-
}, [token.address, chainId, context, onChangeInput]);
|
|
57
|
+
}, [token.address, token.chainId, token.decimals, chainId, context, onChangeInput, rawBalance]);
|
|
30
58
|
const handleTokenSelect = (newToken) => {
|
|
31
59
|
const token = {
|
|
32
60
|
address: newToken.address,
|
|
@@ -53,12 +81,8 @@ function OrderTokenAmount({ disabled, inputValue, onChangeInput, context, addres
|
|
|
53
81
|
prevTokenRef.current = "changing"; // Temporary value to force effect
|
|
54
82
|
// Set the chain ID first
|
|
55
83
|
setChainId(newToken.chainId);
|
|
56
|
-
// Then set the new token
|
|
84
|
+
// Then set the new token - the useEffect will handle setting the max balance
|
|
57
85
|
setToken(token);
|
|
58
|
-
// If this is the source token, reset the amount immediately
|
|
59
|
-
if (context === "from") {
|
|
60
|
-
onChangeInput("0.01");
|
|
61
|
-
}
|
|
62
86
|
};
|
|
63
87
|
return ((0, jsx_runtime_1.jsx)("div", { className: (0, utils_1.cn)("border-as-stroke flex w-full flex-col gap-2 rounded-xl", className), children: (0, jsx_runtime_1.jsxs)("div", { className: (0, utils_1.cn)("flex items-center justify-between gap-3", innerClassName), children: [!canEditAmount ? ((0, jsx_runtime_1.jsx)("h2", { className: (0, utils_1.cn)("text-3xl font-medium text-white", amountClassName), children: inputValue || "--" })) : ((0, jsx_runtime_1.jsx)(react_number_format_1.NumericFormat, { decimalSeparator: ".", allowedDecimalSeparators: [","], thousandSeparator: true, inputMode: "decimal", autoComplete: "off", autoCorrect: "off", type: "text", placeholder: "0.00", minLength: 1, maxLength: 30, spellCheck: "false", className: (0, utils_1.cn)("placeholder:text-as-primary/70 disabled:text-as-primary/70 text-as-primary w-full bg-transparent text-4xl font-semibold leading-[42px] outline-none sm:text-[30px]", amountClassName), pattern: "^[0-9]*[.,]?[0-9]*$", disabled: disabled, value: inputValue, allowNegative: false, onChange: e => onChangeInput(e.currentTarget.value) }, `input-${token.address}-${chainId}`)), !hideTokenSelect && ((0, jsx_runtime_1.jsx)(relay_kit_ui_1.TokenSelector, { address: address, chainIdsFilter: Object.values(anyspend_1.ALL_CHAINS).map(chain => chain.id), context: context, fromChainWalletVMSupported: true, isValidAddress: true, lockedChainIds: Object.values(anyspend_1.ALL_CHAINS).map(chain => chain.id), multiWalletSupportEnabled: true, onAnalyticEvent: undefined, popularChainIds: [1, 8453, anyspend_1.RELAY_SOLANA_MAINNET_CHAIN_ID], setToken: handleTokenSelect, supportedWalletVMs: ["evm", "svm"], token: undefined, trigger: (0, jsx_runtime_1.jsxs)(react_2.Button, { variant: "outline", role: "combobox", className: (0, utils_1.cn)("token-selector-button bg-b3-react-background border-as-stroke flex h-auto w-fit shrink-0 items-center justify-center gap-2 rounded-xl border-2 px-2 py-1 pr-2 text-center", tokenSelectClassName), children: [token.metadata.logoURI ? ((0, jsx_runtime_1.jsx)(ChainTokenIcon_1.ChainTokenIcon, { chainUrl: anyspend_1.ALL_CHAINS[chainId].logoUrl, tokenUrl: token.metadata.logoURI, className: "h-8 min-h-8 w-8 min-w-8" })) : ((0, jsx_runtime_1.jsx)("div", { className: "h-8 w-8 rounded-full bg-gray-700" })), (0, jsx_runtime_1.jsxs)("div", { className: "flex flex-col items-start gap-0", children: [(0, jsx_runtime_1.jsx)("div", { className: "text-as-primary font-semibold", children: token.symbol }), (0, jsx_runtime_1.jsx)("div", { className: "text-as-primary/70 text-xs", children: anyspend_1.ALL_CHAINS[chainId].name })] }), (0, jsx_runtime_1.jsx)(lucide_react_1.ChevronsUpDown, { className: "h-4 w-4 shrink-0 opacity-70" })] }) }, `selector-${context}-${token.address}-${chainId}`))] }) }, `${context}-${token.address}-${chainId}`));
|
|
64
88
|
}
|
|
@@ -42,7 +42,7 @@ function CryptoPaySection({ selectedSrcChainId, setSelectedSrcChainId, selectedS
|
|
|
42
42
|
(0, react_3.useEffect)(() => {
|
|
43
43
|
appliedSrcMetadataRef.current = false;
|
|
44
44
|
}, [selectedSrcToken.address, selectedSrcToken.chainId]);
|
|
45
|
-
return ((0, jsx_runtime_1.jsxs)(react_2.motion.div, { initial: { opacity: 0, y: 20, filter: "blur(10px)" }, animate: { opacity: 1, y: 0, filter: "blur(0px)" }, transition: { duration: 0.3, delay: 0, ease: "easeInOut" }, className: "pay-section bg-as-surface-secondary border-as-border-secondary relative flex w-full flex-col gap-2 rounded-2xl border p-4 sm:p-6", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-between", children: [(0, jsx_runtime_1.jsx)("div", { className: "text-as-primary/50 flex h-7 items-center text-sm", children: "Pay" }), (0, jsx_runtime_1.jsx)("button", { className: "text-as-tertiarry flex h-7 items-center gap-2 text-sm transition-colors focus:!outline-none", onClick: onSelectCryptoPaymentMethod, children: selectedCryptoPaymentMethod === CryptoPaymentMethod_1.CryptoPaymentMethodType.CONNECT_WALLET ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [isConnected ? ((0, jsx_runtime_1.jsx)("div", { className: "flex items-center gap-1", children: connectedName ? (0, utils_1.formatUsername)(connectedName) : (0, formatAddress_1.shortenAddress)(connectedAddress || "") })) : ("Connect wallet"), (0, jsx_runtime_1.jsx)(lucide_react_1.ChevronRight, { className: "h-4 w-4" })] })) : selectedCryptoPaymentMethod === CryptoPaymentMethod_1.CryptoPaymentMethodType.GLOBAL_WALLET ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["Global Account", (0, jsx_runtime_1.jsx)(lucide_react_1.ChevronRight, { className: "h-4 w-4" })] })) : selectedCryptoPaymentMethod === CryptoPaymentMethod_1.CryptoPaymentMethodType.TRANSFER_CRYPTO ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["Transfer crypto", (0, jsx_runtime_1.jsx)(lucide_react_1.ChevronRight, { className: "h-4 w-4" })] })) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["Select payment method", (0, jsx_runtime_1.jsx)(lucide_react_1.ChevronRight, { className: "h-4 w-4" })] })) })] }), (0, jsx_runtime_1.jsx)(OrderTokenAmount_1.OrderTokenAmount, { address: connectedAddress, context: "from", inputValue: srcAmount, onChangeInput: value => {
|
|
45
|
+
return ((0, jsx_runtime_1.jsxs)(react_2.motion.div, { initial: { opacity: 0, y: 20, filter: "blur(10px)" }, animate: { opacity: 1, y: 0, filter: "blur(0px)" }, transition: { duration: 0.3, delay: 0, ease: "easeInOut" }, className: "pay-section bg-as-surface-secondary border-as-border-secondary relative flex w-full flex-col gap-2 rounded-2xl border p-4 sm:p-6", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-between", children: [(0, jsx_runtime_1.jsx)("div", { className: "text-as-primary/50 flex h-7 items-center text-sm", children: "Pay" }), (0, jsx_runtime_1.jsx)("button", { className: "text-as-tertiarry flex h-7 items-center gap-2 text-sm transition-colors focus:!outline-none", onClick: onSelectCryptoPaymentMethod, children: selectedCryptoPaymentMethod === CryptoPaymentMethod_1.CryptoPaymentMethodType.CONNECT_WALLET ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [isConnected ? ((0, jsx_runtime_1.jsx)("div", { className: "flex items-center gap-1", children: connectedName ? (0, utils_1.formatUsername)(connectedName) : (0, formatAddress_1.shortenAddress)(connectedAddress || "") })) : ("Connect wallet"), (0, jsx_runtime_1.jsx)(lucide_react_1.ChevronRight, { className: "h-4 w-4" })] })) : selectedCryptoPaymentMethod === CryptoPaymentMethod_1.CryptoPaymentMethodType.GLOBAL_WALLET ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["Global Account", (0, jsx_runtime_1.jsx)(lucide_react_1.ChevronRight, { className: "h-4 w-4" })] })) : selectedCryptoPaymentMethod === CryptoPaymentMethod_1.CryptoPaymentMethodType.TRANSFER_CRYPTO ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["Transfer crypto", (0, jsx_runtime_1.jsx)(lucide_react_1.ChevronRight, { className: "h-4 w-4" })] })) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["Select payment method", (0, jsx_runtime_1.jsx)(lucide_react_1.ChevronRight, { className: "h-4 w-4" })] })) })] }), (0, jsx_runtime_1.jsx)(OrderTokenAmount_1.OrderTokenAmount, { address: connectedAddress, walletAddress: connectedAddress, context: "from", inputValue: srcAmount, onChangeInput: value => {
|
|
46
46
|
setIsSrcInputDirty(true);
|
|
47
47
|
setSrcAmount(value);
|
|
48
48
|
}, chainId: selectedSrcChainId, setChainId: setSelectedSrcChainId, token: selectedSrcToken, setToken: setSelectedSrcToken }), (0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-between", children: [(0, jsx_runtime_1.jsx)("div", { className: "text-as-primary/50 flex h-5 items-center text-sm", children: (0, number_1.formatDisplayNumber)(anyspendQuote?.data?.currencyIn?.amountUsd, {
|
|
@@ -7,7 +7,7 @@ const token_1 = require("../../../../anyspend/utils/token");
|
|
|
7
7
|
const react_1 = require("../../../../global-account/react");
|
|
8
8
|
const viem_1 = require("viem");
|
|
9
9
|
function TokenBalance({ token, walletAddress, onChangeInput, }) {
|
|
10
|
-
const { rawBalance, formattedBalance, isLoading } = (0, react_1.
|
|
10
|
+
const { rawBalance, formattedBalance, isLoading } = (0, react_1.useTokenBalanceDirect)({
|
|
11
11
|
token,
|
|
12
12
|
address: walletAddress,
|
|
13
13
|
});
|
|
@@ -14,6 +14,8 @@ const chains_1 = require("viem/chains");
|
|
|
14
14
|
const wagmi_1 = require("wagmi");
|
|
15
15
|
const CryptoPaymentMethod_1 = require("../components/common/CryptoPaymentMethod");
|
|
16
16
|
const FiatPaymentMethod_1 = require("../components/common/FiatPaymentMethod");
|
|
17
|
+
const useAutoSelectCryptoPaymentMethod_1 = require("./useAutoSelectCryptoPaymentMethod");
|
|
18
|
+
const useAutoSetActiveWalletFromWagmi_1 = require("./useAutoSetActiveWalletFromWagmi");
|
|
17
19
|
var PanelView;
|
|
18
20
|
(function (PanelView) {
|
|
19
21
|
PanelView[PanelView["MAIN"] = 0] = "MAIN";
|
|
@@ -49,6 +51,8 @@ function useAnyspendFlow({ paymentType = "crypto", recipientAddress, loadOrder,
|
|
|
49
51
|
const [selectedRecipientAddress, setSelectedRecipientAddress] = (0, react_3.useState)(recipientAddress);
|
|
50
52
|
const recipientProfile = (0, react_2.useProfile)({ address: selectedRecipientAddress, fresh: true });
|
|
51
53
|
const recipientName = recipientProfile.data?.name;
|
|
54
|
+
// Auto-set active wallet from wagmi
|
|
55
|
+
(0, useAutoSetActiveWalletFromWagmi_1.useAutoSetActiveWalletFromWagmi)();
|
|
52
56
|
// Set default recipient address when wallet changes
|
|
53
57
|
(0, react_3.useEffect)(() => {
|
|
54
58
|
if (!selectedRecipientAddress && globalAddress) {
|
|
@@ -72,17 +76,14 @@ function useAnyspendFlow({ paymentType = "crypto", recipientAddress, loadOrder,
|
|
|
72
76
|
return false;
|
|
73
77
|
}
|
|
74
78
|
}, [rawBalance, srcAmount, selectedSrcToken.decimals, isBalanceLoading, paymentType]);
|
|
75
|
-
// Auto-
|
|
76
|
-
(0,
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
}, [paymentType, hasEnoughBalance, isBalanceLoading]);
|
|
79
|
+
// Auto-select crypto payment method based on available wallets and balance
|
|
80
|
+
(0, useAutoSelectCryptoPaymentMethod_1.useAutoSelectCryptoPaymentMethod)({
|
|
81
|
+
paymentType,
|
|
82
|
+
selectedCryptoPaymentMethod,
|
|
83
|
+
setSelectedCryptoPaymentMethod,
|
|
84
|
+
hasEnoughBalance,
|
|
85
|
+
isBalanceLoading,
|
|
86
|
+
});
|
|
86
87
|
// Fetch specific token when sourceTokenAddress and sourceTokenChainId are provided
|
|
87
88
|
(0, react_3.useEffect)(() => {
|
|
88
89
|
const fetchSourceToken = async () => {
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { CryptoPaymentMethodType } from "../components/common/CryptoPaymentMethod";
|
|
2
|
+
interface UseAutoSelectCryptoPaymentMethodParams {
|
|
3
|
+
/** Current payment type (crypto or fiat) */
|
|
4
|
+
paymentType?: "crypto" | "fiat";
|
|
5
|
+
/** Currently selected payment method */
|
|
6
|
+
selectedCryptoPaymentMethod: CryptoPaymentMethodType;
|
|
7
|
+
/** Function to update the selected payment method */
|
|
8
|
+
setSelectedCryptoPaymentMethod: (method: CryptoPaymentMethodType) => void;
|
|
9
|
+
/** Whether user has enough balance to pay */
|
|
10
|
+
hasEnoughBalance: boolean;
|
|
11
|
+
/** Whether balance is still loading */
|
|
12
|
+
isBalanceLoading: boolean;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Custom hook to automatically select appropriate crypto payment method
|
|
16
|
+
* based on available wallets and balance.
|
|
17
|
+
*
|
|
18
|
+
* Auto-selection logic:
|
|
19
|
+
* - Only auto-selects when payment method is NONE (doesn't override user choices)
|
|
20
|
+
* - If EOA/Wagmi wallet connected + has balance → CONNECT_WALLET
|
|
21
|
+
* - If EOA/Wagmi wallet connected + insufficient balance → TRANSFER_CRYPTO
|
|
22
|
+
* - If only Global wallet available → GLOBAL_WALLET
|
|
23
|
+
* - If no wallets → remains NONE
|
|
24
|
+
*/
|
|
25
|
+
export declare function useAutoSelectCryptoPaymentMethod({ paymentType, selectedCryptoPaymentMethod, setSelectedCryptoPaymentMethod, hasEnoughBalance, isBalanceLoading, }: UseAutoSelectCryptoPaymentMethodParams): void;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.useAutoSelectCryptoPaymentMethod = useAutoSelectCryptoPaymentMethod;
|
|
4
|
+
const react_1 = require("react");
|
|
5
|
+
const CryptoPaymentMethod_1 = require("../components/common/CryptoPaymentMethod");
|
|
6
|
+
const useConnectedWalletDisplay_1 = require("./useConnectedWalletDisplay");
|
|
7
|
+
/**
|
|
8
|
+
* Custom hook to automatically select appropriate crypto payment method
|
|
9
|
+
* based on available wallets and balance.
|
|
10
|
+
*
|
|
11
|
+
* Auto-selection logic:
|
|
12
|
+
* - Only auto-selects when payment method is NONE (doesn't override user choices)
|
|
13
|
+
* - If EOA/Wagmi wallet connected + has balance → CONNECT_WALLET
|
|
14
|
+
* - If EOA/Wagmi wallet connected + insufficient balance → TRANSFER_CRYPTO
|
|
15
|
+
* - If only Global wallet available → GLOBAL_WALLET
|
|
16
|
+
* - If no wallets → remains NONE
|
|
17
|
+
*/
|
|
18
|
+
function useAutoSelectCryptoPaymentMethod({ paymentType = "crypto", selectedCryptoPaymentMethod, setSelectedCryptoPaymentMethod, hasEnoughBalance, isBalanceLoading, }) {
|
|
19
|
+
// Get suggested payment method based on available wallets
|
|
20
|
+
const { suggestedPaymentMethod } = (0, useConnectedWalletDisplay_1.useConnectedWalletDisplay)(selectedCryptoPaymentMethod);
|
|
21
|
+
(0, react_1.useEffect)(() => {
|
|
22
|
+
// Only auto-select when on crypto payment type and payment method is NONE
|
|
23
|
+
if (paymentType !== "crypto" || selectedCryptoPaymentMethod !== CryptoPaymentMethod_1.CryptoPaymentMethodType.NONE) {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
// If we have a suggested payment method (wallet is connected), use it
|
|
27
|
+
if (suggestedPaymentMethod !== CryptoPaymentMethod_1.CryptoPaymentMethodType.NONE) {
|
|
28
|
+
// If we have balance info and enough balance, use CONNECT_WALLET
|
|
29
|
+
// Otherwise, default to TRANSFER_CRYPTO if balance is insufficient
|
|
30
|
+
if (!isBalanceLoading) {
|
|
31
|
+
if (hasEnoughBalance && suggestedPaymentMethod === CryptoPaymentMethod_1.CryptoPaymentMethodType.CONNECT_WALLET) {
|
|
32
|
+
setSelectedCryptoPaymentMethod(CryptoPaymentMethod_1.CryptoPaymentMethodType.CONNECT_WALLET);
|
|
33
|
+
}
|
|
34
|
+
else if (!hasEnoughBalance && suggestedPaymentMethod === CryptoPaymentMethod_1.CryptoPaymentMethodType.CONNECT_WALLET) {
|
|
35
|
+
// Wallet connected but insufficient balance - suggest transfer
|
|
36
|
+
setSelectedCryptoPaymentMethod(CryptoPaymentMethod_1.CryptoPaymentMethodType.TRANSFER_CRYPTO);
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
// Use suggested method (e.g., GLOBAL_WALLET)
|
|
40
|
+
setSelectedCryptoPaymentMethod(suggestedPaymentMethod);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
// Balance still loading, use suggested method
|
|
45
|
+
setSelectedCryptoPaymentMethod(suggestedPaymentMethod);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}, [
|
|
49
|
+
paymentType,
|
|
50
|
+
selectedCryptoPaymentMethod,
|
|
51
|
+
suggestedPaymentMethod,
|
|
52
|
+
hasEnoughBalance,
|
|
53
|
+
isBalanceLoading,
|
|
54
|
+
setSelectedCryptoPaymentMethod,
|
|
55
|
+
]);
|
|
56
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
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;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.useAutoSetActiveWalletFromWagmi = useAutoSetActiveWalletFromWagmi;
|
|
4
|
+
const thirdweb_1 = require("../../../shared/utils/thirdweb");
|
|
5
|
+
const react_1 = require("react");
|
|
6
|
+
const react_2 = require("thirdweb/react");
|
|
7
|
+
const wallets_1 = require("thirdweb/wallets");
|
|
8
|
+
const wagmi_1 = require("wagmi");
|
|
9
|
+
/**
|
|
10
|
+
* Hook that automatically sets the active thirdweb wallet when a wagmi wallet connects.
|
|
11
|
+
*
|
|
12
|
+
* This is useful for syncing wagmi wallet connections with thirdweb's wallet system,
|
|
13
|
+
* ensuring that when users connect via wagmi, the active wallet is properly set.
|
|
14
|
+
*
|
|
15
|
+
* Place this hook in components that stay mounted throughout the user flow
|
|
16
|
+
* (not in components that unmount during navigation).
|
|
17
|
+
*/
|
|
18
|
+
function useAutoSetActiveWalletFromWagmi() {
|
|
19
|
+
const { address: wagmiAddress, connector: wagmiConnector } = (0, wagmi_1.useAccount)();
|
|
20
|
+
const setActiveWallet = (0, react_2.useSetActiveWallet)();
|
|
21
|
+
const prevWagmiAddress = (0, react_1.useRef)(undefined);
|
|
22
|
+
// Map wagmi connector names to thirdweb wallet IDs
|
|
23
|
+
const getThirdwebWalletId = (0, react_1.useCallback)((connectorName) => {
|
|
24
|
+
const walletMap = {
|
|
25
|
+
MetaMask: "io.metamask",
|
|
26
|
+
"Coinbase Wallet": "com.coinbase.wallet",
|
|
27
|
+
Rainbow: "me.rainbow",
|
|
28
|
+
WalletConnect: "walletConnect",
|
|
29
|
+
Phantom: "app.phantom",
|
|
30
|
+
};
|
|
31
|
+
return walletMap[connectorName] || null;
|
|
32
|
+
}, []);
|
|
33
|
+
// Create thirdweb wallet from wagmi connector
|
|
34
|
+
const createThirdwebWalletFromConnector = (0, react_1.useCallback)(async (connectorName) => {
|
|
35
|
+
const walletId = getThirdwebWalletId(connectorName);
|
|
36
|
+
if (!walletId) {
|
|
37
|
+
console.warn(`No thirdweb wallet ID found for connector: ${connectorName}`);
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
const thirdwebWallet = (0, wallets_1.createWallet)(walletId);
|
|
42
|
+
await thirdwebWallet.connect({ client: thirdweb_1.client });
|
|
43
|
+
return thirdwebWallet;
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
console.error(`Failed to create thirdweb wallet for ${connectorName}:`, error);
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}, [getThirdwebWalletId]);
|
|
50
|
+
// Listen for wagmi wallet connections and automatically set active wallet
|
|
51
|
+
(0, react_1.useEffect)(() => {
|
|
52
|
+
const isNewConnection = wagmiAddress && wagmiAddress !== prevWagmiAddress.current;
|
|
53
|
+
if (isNewConnection && wagmiConnector?.name) {
|
|
54
|
+
prevWagmiAddress.current = wagmiAddress;
|
|
55
|
+
const setupThirdwebWallet = async () => {
|
|
56
|
+
try {
|
|
57
|
+
const thirdwebWallet = await createThirdwebWalletFromConnector(wagmiConnector.name);
|
|
58
|
+
if (thirdwebWallet) {
|
|
59
|
+
setActiveWallet(thirdwebWallet);
|
|
60
|
+
console.log(`Auto-set active wallet for ${wagmiConnector.name}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
console.error("Failed to auto-set active wallet:", error);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
setupThirdwebWallet();
|
|
68
|
+
}
|
|
69
|
+
if (!wagmiAddress) {
|
|
70
|
+
prevWagmiAddress.current = undefined;
|
|
71
|
+
}
|
|
72
|
+
}, [wagmiAddress, wagmiConnector?.name, setActiveWallet, createThirdwebWalletFromConnector]);
|
|
73
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CryptoPaymentMethodType } from "../components/common/CryptoPaymentMethod";
|
|
2
|
+
interface UseConnectedWalletDisplayResult {
|
|
3
|
+
walletAddress: string | undefined;
|
|
4
|
+
shouldShowConnectedEOA: boolean;
|
|
5
|
+
shouldShowWagmiWallet: boolean;
|
|
6
|
+
isWalletDuplicated: boolean;
|
|
7
|
+
suggestedPaymentMethod: CryptoPaymentMethodType;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Custom hook to determine which wallet to display and its address
|
|
11
|
+
* Handles logic for showing EOA wallet, wagmi wallet, or global wallet based on payment method
|
|
12
|
+
*/
|
|
13
|
+
export declare function useConnectedWalletDisplay(selectedCryptoPaymentMethod?: CryptoPaymentMethodType): UseConnectedWalletDisplayResult;
|
|
14
|
+
export {};
|