-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpage.tsx
More file actions
573 lines (524 loc) · 32.2 KB
/
page.tsx
File metadata and controls
573 lines (524 loc) · 32.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
'use client';
import { useState, useEffect } from 'react';
import {
PublicKey,
Transaction
} from '@solana/web3.js';
import Link from 'next/link';
import axios from "axios";
import { DEV_API_URLS } from '@raydium-io/raydium-sdk-v2'
import { useBalances } from '@/hooks/useBalances';
import { useLazorkitWalletConnect } from '@/hooks/useLazorkitWalletConnect';
import { useThemeClasses } from '@/hooks/useThemeClasses';
import { getAssociatedTokenAddressSync, getConnection, formatTransactionError } from '@/lib/solana-utils';
import { processInstructionsForLazorKit } from '@/lib/lazorkit-utils';
const TOKENS = {
SOL: {
symbol: 'SOL',
name: 'Solana',
mint: 'So11111111111111111111111111111111111111112',
decimals: 9,
},
USDC: {
symbol: 'USDC',
name: 'USD Coin',
mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',
decimals: 6,
},
};
interface SwapCompute {
id: string
success: true
version: string
openTime?: undefined
msg: undefined
data: {
swapType: 'BaseIn' | 'BaseOut'
inputMint: string
inputAmount: string
outputMint: string
outputAmount: string
otherAmountThreshold: string
slippageBps: number
priceImpactPct: number
routePlan: any
}
}
export default function Recipe04() {
const { isConnected, wallet, connect, connecting, signAndSendTransaction } = useLazorkitWalletConnect();
const theme = useThemeClasses();
const [inputToken, setInputToken] = useState<'SOL' | 'USDC'>('SOL');
const [outputToken, setOutputToken] = useState<'SOL' | 'USDC'>('USDC');
const [inputAmount, setInputAmount] = useState('');
const [outputAmount, setOutputAmount] = useState('');
const [quoteError, setQuoteError] = useState('');
const [swapping, setSwapping] = useState(false);
const [lastTxSignature, setLastTxSignature] = useState('');
const {
solBalance,
usdcBalance,
loading: refreshing,
fetchBalances,
} = useBalances(isConnected ? wallet?.smartWallet : null);
// Create a balances object for easy access by token symbol
const balances = {
SOL: solBalance ?? 0,
USDC: usdcBalance ?? 0,
};
// Calculate output amount (price quote)
const calculateOutputAmount = async () => {
if (!wallet || !inputAmount || parseFloat(inputAmount) <= 0) {
setOutputAmount('');
setQuoteError('');
return;
}
setQuoteError('');
try {
const inputMint = TOKENS[inputToken as keyof typeof TOKENS].mint;
const outputMint = TOKENS[outputToken as keyof typeof TOKENS].mint;
const amount = parseFloat(inputAmount) * Math.pow(10, TOKENS[inputToken as keyof typeof TOKENS].decimals);
const quoteResponse = await fetch(
`${DEV_API_URLS.SWAP_HOST}/compute/swap-base-in?` +
`inputMint=${inputMint}&` +
`outputMint=${outputMint}&` +
`amount=${Math.floor(amount)}&` +
`slippageBps=50&` +
`txVersion=LEGACY`
);
if (!quoteResponse.ok) {
throw new Error('Failed to get quote from Raydium API');
}
const quoteData = await quoteResponse.json();
if (!quoteData.success || !quoteData.data) {
throw new Error('No liquidity available for this pair');
}
const outputAmountRaw = parseFloat(quoteData.data.outputAmount);
const formattedOutput = (outputAmountRaw / Math.pow(10, TOKENS[outputToken as keyof typeof TOKENS].decimals)).toFixed(6);
setOutputAmount(formattedOutput);
} catch (err: any) {
console.error('Quote error:', err);
setQuoteError(err.message || 'Failed to get quote');
setOutputAmount('');
}
};
useEffect(() => {
const timeoutId = setTimeout(calculateOutputAmount, 500);
return () => clearTimeout(timeoutId);
}, [inputAmount, inputToken, outputToken]);
const handleSwap = async () => {
if (!wallet || !inputAmount) {
alert('Please enter an amount');
return;
}
const amount = parseFloat(inputAmount);
if (isNaN(amount) || amount <= 0) {
alert('Invalid amount');
return;
}
if (amount > (balances[inputToken] || 0)) {
alert(`Insufficient ${inputToken} balance. You have ${balances[inputToken]?.toFixed(4) || '0'} ${inputToken}.`);
return;
}
setSwapping(true);
try {
const inputMint = TOKENS[inputToken as keyof typeof TOKENS].mint;
const outputMint = TOKENS[outputToken as keyof typeof TOKENS].mint;
const amountIn = Math.floor(amount * Math.pow(10, TOKENS[inputToken as keyof typeof TOKENS].decimals));
// Get quote
let { data: swapResponse } = await axios.get<SwapCompute>(
`${DEV_API_URLS.SWAP_HOST}/compute/swap-base-in?inputMint=${inputMint}&outputMint=${outputMint}&amount=${amountIn}&slippageBps=50&txVersion=LEGACY`
);
const { data: priorityFeeData } = await axios.get<{
id: string
success: boolean
data: { default: { vh: number; h: number; m: number } }
}>(`${DEV_API_URLS.BASE_HOST}${DEV_API_URLS.PRIORITY_FEE}`);
// Request LEGACY transaction from Raydium
const { data: swapData } = await axios.post<{
id: string
version: string
success: boolean
data: { transaction: string }[]
}>(`${DEV_API_URLS.SWAP_HOST}/transaction/swap-base-in`, {
computeUnitPriceMicroLamports: String(priorityFeeData.data.default.h),
swapResponse,
txVersion: 'LEGACY',
wallet: wallet.smartWallet,
wrapSol: inputMint === TOKENS.SOL.mint,
unwrapSol: outputMint === TOKENS.SOL.mint,
inputAccount: inputMint === TOKENS.SOL.mint ? undefined : getAssociatedTokenAddressSync(new PublicKey(inputMint), new PublicKey(wallet.smartWallet)).toBase58(),
outputAccount: outputMint === TOKENS.SOL.mint ? undefined : getAssociatedTokenAddressSync(new PublicKey(outputMint), new PublicKey(wallet.smartWallet)).toBase58(),
});
// Deserialize as Legacy Transaction
const txBuffer = Buffer.from(swapData.data[0].transaction, 'base64');
const legacyTx = Transaction.from(txBuffer);
// Process instructions for LazorKit:
// 1. Remove ComputeBudget instructions (LazorKit handles compute)
// 2. Add smart wallet to all instructions (LazorKit validation requirement)
const instructions = processInstructionsForLazorKit(
legacyTx.instructions,
wallet.smartWallet
);
// Send to LazorKit
const signature = await signAndSendTransaction({
instructions,
transactionOptions: {
computeUnitLimit: 600_000
}
});
setLastTxSignature(signature);
alert(
`✅ Swap successful!\n\n` +
`Swapped: ${amount} ${inputToken}\n` +
`For: ~${outputAmount} ${outputToken}\n\n` +
`💰 No gas fees paid!`
);
setInputAmount('');
setOutputAmount('');
setQuoteError('');
await fetchBalances();
} catch (err: any) {
console.error('Swap error:', err);
let errorMessage = err.message || 'Unknown error occurred';
if (errorMessage.includes('0x1')) {
errorMessage = 'Insufficient SOL for rent. Get SOL from Solana Devnet faucet.';
} else if (errorMessage.includes('slippage')) {
errorMessage = 'Slippage exceeded. Try again or increase slippage tolerance.';
} else if (errorMessage.includes('No liquidity')) {
errorMessage = 'No liquidity pool found on Devnet.';
} else if (errorMessage.includes('transaction too large') || errorMessage.includes('Transaction too large')) {
errorMessage = 'Transaction too large. Try a simpler swap with fewer routing hops.';
} else if (errorMessage.includes('SBF program panicked') || errorMessage.includes('Option::unwrap()') || errorMessage.includes('Program failed to complete')) {
errorMessage = `Devnet pool error for ${inputToken}→${outputToken}. The pool may be imbalanced or have insufficient liquidity in this direction. Try swapping ${outputToken}→${inputToken} instead, or try a smaller amount.`;
}
alert(`Swap failed: ${errorMessage}`);
} finally {
setSwapping(false);
}
};
const handleFlipTokens = () => {
setInputToken(outputToken);
setOutputToken(inputToken);
setInputAmount('');
setOutputAmount('');
setQuoteError('');
};
return (
<div className={`min-h-screen ${theme.bgPage}`}>
<div className="container mx-auto px-4 py-8 max-w-7xl">
{/* Header */}
<div className="mb-8">
<Link
href="/"
className={`${theme.textAccent} hover:opacity-80 mb-4 inline-block`}
>
← Back to Home
</Link>
<div className="flex items-start gap-3 mb-2">
<span className="text-4xl">🔄</span>
<div>
<h1 className={`text-4xl font-bold ${theme.textPrimary}`}>
Gasless Token Swaps with Raydium
</h1>
</div>
</div>
<p className={theme.textMuted}>
Swap tokens on Raydium DEX without paying gas fees
</p>
</div>
{/* Devnet Warning */}
<div className={`mb-6 ${theme.infoYellow} rounded-xl p-4`}>
<div className="flex items-start gap-3">
<span className="text-2xl">⚠️</span>
<div>
<h3 className={`${theme.infoYellowTitle} font-semibold mb-2`}>
Devnet Limitations
</h3>
<div className={`text-sm ${theme.infoYellowText} space-y-2`}>
<p>
Currently supporting <strong>SOL ↔ USDC</strong> pair on Devnet. Devnet liquidity pools can be
unreliable - some swap directions may fail due to imbalanced pools or missing pool state.
</p>
<p className="mt-2">
<strong>Note:</strong> If USDC→SOL fails, try SOL→USDC instead. This is a devnet pool limitation, not a code issue.
</p>
<p className="mt-2">
💡 The same code works reliably on Mainnet where pools are properly maintained.
</p>
</div>
</div>
</div>
</div>
<div className="grid lg:grid-cols-2 gap-8">
{/* Left Panel - Info */}
<div className="space-y-6">
{/* Integration Highlight */}
<div className={`${theme.bgCardAlt} rounded-2xl p-6`}>
<h2 className={`text-2xl font-bold ${theme.textPrimary} mb-4 flex items-center gap-2`}>
<span>🤝</span> Raydium x LazorKit
</h2>
<p className={`text-sm ${theme.textSecondary} mb-4`}>
Integrating with an existing Solana protocol while maintaining gasless UX.
</p>
<div className="space-y-2 text-sm">
<div className="flex items-start gap-2">
<span className={theme.infoBlueTitle}>✓</span>
<span className={theme.textSecondary}>Raydium Trade API for swap routing</span>
</div>
<div className="flex items-start gap-2">
<span className={theme.infoBlueTitle}>✓</span>
<span className={theme.textSecondary}>LazorKit paymaster covers all gas fees</span>
</div>
<div className="flex items-start gap-2">
<span className={theme.infoBlueTitle}>✓</span>
<span className={theme.textSecondary}>Works on Solana Devnet (SOL-USDC pair)</span>
</div>
<div className="flex items-start gap-2">
<span className={theme.infoBlueTitle}>✓</span>
<span className={theme.textSecondary}>Swap more pairs on Mainnet</span>
</div>
</div>
</div>
{/* Integration Challenges & Solutions */}
<div className={`${theme.bgCard} rounded-2xl p-6`}>
<h2 className={`text-xl font-bold ${theme.textPrimary} mb-4`}>Making Raydium Work with LazorKit</h2>
<div className={`space-y-4 text-sm ${theme.textSecondary}`}>
<div>
<div className="flex items-start gap-2 mb-2">
<span className={theme.infoYellowTitle}>1.</span>
<span className={`font-semibold ${theme.textPrimary}`}>Use Legacy Transactions</span>
</div>
<p className={`ml-5 ${theme.textMuted}`}>
Request <code className={`${theme.codeBlock} px-1 rounded`}>txVersion: 'LEGACY'</code> from Raydium API to keep instructions simpler than versioned transactions.
</p>
</div>
<div>
<div className="flex items-start gap-2 mb-2">
<span className={theme.infoYellowTitle}>2.</span>
<span className={`font-semibold ${theme.textPrimary}`}>Skip ComputeBudget Instructions</span>
</div>
<p className={`ml-5 ${theme.textMuted} mb-2`}>
LazorKit manages compute budget automatically. Filter them out:
</p>
<code className={`ml-5 block ${theme.codeBlock} p-2 rounded text-xs`}>
instructions.filter(ix => !ix.programId.equals(COMPUTE_BUDGET_PROGRAM))
</code>
</div>
<div>
<div className="flex items-start gap-2 mb-2">
<span className={theme.infoYellowTitle}>3.</span>
<span className={`font-semibold ${theme.textPrimary}`}>Fix SyncNative Validation</span>
</div>
<p className={`ml-5 ${theme.textMuted} mb-2`}>
LazorKit's <code className={`${theme.codeBlock} px-1 rounded`}>execute_cpi</code> expects smart wallet in ALL instructions. Some (like SyncNative) don't need it. Workaround:
</p>
<code className={`ml-5 block ${theme.codeBlock} p-2 rounded text-xs`}>
if (!hasSmartWallet) {<br />
ix.keys.push({ pubkey: smartWallet, isSigner: false, isWritable: false })<br />
}
</code>
</div>
<div className={`mt-4 pt-4 ${theme.border} border-t`}>
<p className={`text-xs ${theme.textMuted}`}>
💡 These patterns can be applied to most Solana protocols when integrating with LazorKit
</p>
</div>
</div>
</div>
{/* What You'll Learn */}
<div className={`${theme.bgCard} rounded-2xl p-6`}>
<h2 className={`text-xl font-bold ${theme.textPrimary} mb-4`}>What You'll Learn</h2>
<ul className={`space-y-3 text-sm ${theme.textSecondary}`}>
<li className="flex items-start gap-3">
<span className="text-green-500 mt-1 flex-shrink-0">✓</span>
<span>Use Raydium Trade API for quotes & swaps</span>
</li>
<li className="flex items-start gap-3">
<span className="text-green-500 mt-1 flex-shrink-0">✓</span>
<span>Handling legacy transactions</span>
</li>
<li className="flex items-start gap-3">
<span className="text-green-500 mt-1 flex-shrink-0">✓</span>
<span>Work around LazorKit validation quirks</span>
</li>
<li className="flex items-start gap-3">
<span className="text-green-500 mt-1 flex-shrink-0">✓</span>
<span>Manage token accounts & balances</span>
</li>
</ul>
</div>
</div>
{/* Right Panel - Swap Interface */}
<div className="space-y-6">
<div className={`${theme.bgCard} rounded-2xl p-8`}>
{!isConnected ? (
<div className="text-center space-y-6">
<div>
<h3 className={`text-2xl font-bold ${theme.textPrimary} mb-2`}>Connect Your Wallet</h3>
<p className={`${theme.textMuted} text-sm`}>
Use LazorKit smart wallet for gasless swaps
</p>
</div>
<button
onClick={connect}
disabled={connecting}
className={theme.btnPrimary}
>
{connecting ? 'Connecting...' : '🔑 Connect Wallet'}
</button>
</div>
) : (
<div className="space-y-6">
<div>
<h3 className={`text-2xl font-bold ${theme.textPrimary} mb-2`}>Swap Tokens</h3>
<p className={`${theme.textMuted} text-sm`}>
{wallet?.smartWallet.slice(0, 4)}...{wallet?.smartWallet.slice(-4)}
</p>
</div>
{/* Balances with Refresh */}
<div className={`${theme.bgCardAlt} rounded-xl p-4`}>
<div className="flex justify-between items-center mb-3">
<span className={`text-sm ${theme.textSecondary} font-semibold`}>Balances</span>
<button
onClick={fetchBalances}
disabled={refreshing}
className={`text-xs ${theme.textAccent} hover:opacity-80 disabled:opacity-50 flex items-center gap-1`}
>
<span className={refreshing ? 'animate-spin' : ''}>🔄</span>
{refreshing ? 'Refreshing...' : 'Refresh'}
</button>
</div>
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className={theme.textMuted}>SOL:</span>
<span className={`${theme.textPrimary} font-semibold`}>
{balances.SOL?.toFixed(4) || '0.0000'}
</span>
</div>
<div className="flex justify-between text-sm">
<span className={theme.textMuted}>USDC:</span>
<span className={`${theme.textPrimary} font-semibold`}>
{balances.USDC?.toFixed(2) || '0.00'}
</span>
</div>
</div>
</div>
{/* Input Token */}
<div className="space-y-2">
<label className={`text-sm ${theme.textMuted}`}>You Pay</label>
<div className={`${theme.bgCardAlt} rounded-xl p-4`}>
<div className="flex justify-between items-center gap-4">
<input
type="number"
placeholder="0.0"
value={inputAmount}
onChange={(e) => setInputAmount(e.target.value)}
className={`bg-transparent ${theme.textPrimary} text-2xl font-semibold outline-none w-full`}
step="0.000001"
min="0"
/>
<select
value={inputToken}
onChange={(e) => setInputToken(e.target.value as 'SOL' | 'USDC')}
className={`px-4 py-2 rounded-lg font-semibold cursor-pointer border-2 transition-colors text-white ${theme.isLazorkit
? 'bg-[#7857FF] border-[#674BF7] hover:bg-[#674BF7]'
: 'bg-purple-600 border-purple-500 hover:bg-purple-700'
}`}
style={{
WebkitAppearance: 'none',
MozAppearance: 'none',
appearance: 'none',
backgroundImage: `url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e")`,
backgroundRepeat: 'no-repeat',
backgroundPosition: 'right 0.5rem center',
backgroundSize: '1.5em 1.5em',
paddingRight: '2.5rem'
}}
>
<option value="SOL" style={{ backgroundColor: theme.isLazorkit ? '#7857FF' : '#6B21A8', color: 'white' }}>SOL</option>
<option value="USDC" style={{ backgroundColor: theme.isLazorkit ? '#7857FF' : '#6B21A8', color: 'white' }}>USDC</option>
</select>
</div>
</div>
</div>
{/* Flip Button */}
<div className="flex justify-center">
<button
onClick={handleFlipTokens}
className="bg-white/10 hover:bg-white/20 p-3 rounded-xl transition-all"
>
<span className="text-2xl">⇅</span>
</button>
</div>
{/* Output Token */}
<div className="space-y-2">
<label className={`text-sm ${theme.textMuted}`}>You Receive</label>
<div className={`${theme.bgCardAlt} rounded-xl p-4`}>
<div className="flex justify-between items-center gap-4">
<div className={`${theme.textPrimary} text-2xl font-semibold`}>
{outputAmount || '0.0'}
</div>
<select
value={outputToken}
onChange={(e) => setOutputToken(e.target.value as 'SOL' | 'USDC')}
className={`px-4 py-2 rounded-lg font-semibold cursor-pointer border-2 transition-colors text-white ${theme.isLazorkit
? 'bg-[#7857FF] border-[#674BF7] hover:bg-[#674BF7]'
: 'bg-purple-600 border-purple-500 hover:bg-purple-700'
}`}
style={{
WebkitAppearance: 'none',
MozAppearance: 'none',
appearance: 'none',
backgroundImage: `url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e")`,
backgroundRepeat: 'no-repeat',
backgroundPosition: 'right 0.5rem center',
backgroundSize: '1.5em 1.5em',
paddingRight: '2.5rem'
}}
>
<option value="SOL" style={{ backgroundColor: theme.isLazorkit ? '#7857FF' : '#6B21A8', color: 'white' }}>SOL</option>
<option value="USDC" style={{ backgroundColor: theme.isLazorkit ? '#7857FF' : '#6B21A8', color: 'white' }}>USDC</option>
</select>
</div>
</div>
</div>
{/* Error Message */}
{quoteError && (
<div className={`${theme.statusError} rounded-xl p-3 text-sm`}>
{quoteError}
</div>
)}
{/* Swap Button */}
<button
onClick={handleSwap}
disabled={swapping || !inputAmount || !!quoteError}
className="w-full bg-gradient-to-r from-green-500 to-emerald-500 hover:from-green-600 hover:to-emerald-600 text-white font-semibold py-4 px-6 rounded-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed"
>
{swapping ? 'Swapping...' : 'Swap (Gas-Free)'}
</button>
<div className={`text-xs ${theme.textMuted} text-center`}>
No gas fees • Powered by LazorKit
</div>
</div>
)}
</div>
{/* Last Transaction */}
{lastTxSignature && (
<div className={theme.statusSuccess + " rounded-2xl p-6"}>
<h2 className={`text-xl font-bold ${theme.textPrimary} mb-3`}>Last Transaction</h2>
<a
href={`https://explorer.solana.com/tx/${lastTxSignature}?cluster=devnet`}
target="_blank"
rel="noopener noreferrer"
className={`${theme.textAccent} hover:opacity-80 text-sm break-all`}
>
{lastTxSignature}
</a>
</div>
)}
</div>
</div>
</div>
</div>
);
}