-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpage.tsx
More file actions
526 lines (480 loc) · 18.3 KB
/
page.tsx
File metadata and controls
526 lines (480 loc) · 18.3 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
'use client';
import { useMemo } from 'react';
import Link from 'next/link';
import Image from "next/image";
import { useThemeClasses } from '@/hooks/useThemeClasses';
import {
createSolanaDevnet,
createWalletUiConfig,
WalletUi,
WalletUiDropdown,
useWalletUi,
useWalletUiSigner,
} from '@wallet-ui/react';
import {
address,
createSolanaClient,
createTransaction,
} from 'gill';
import {
getTransferTokensInstructions,
getAssociatedTokenAccountAddress,
TOKEN_PROGRAM_ADDRESS,
} from 'gill/programs/token';
import { getSignatureFromBytes, signAndSendTransactionMessageWithSigners } from 'gill';
import { useBalances } from '@/hooks/useBalances';
import { useTransferForm } from '@/hooks/useTransferForm';
import {
USDC_MINT,
withRetry,
formatTransactionError,
validateTransferAmount,
createTransferSuccessMessage,
} from '@/lib/solana-utils';
const USDC_DECIMALS = 6;
const config = createWalletUiConfig({
clusters: [createSolanaDevnet()],
});
// Signer hook requires an account, so we split this out
function TransferDemoWithSigner({ account }: { account: NonNullable<ReturnType<typeof useWalletUi>['account']> }) {
const signer = useWalletUiSigner({ account });
const { usdcBalance, loading: balanceLoading, fetchBalances } = useBalances(account.address);
const {
recipient, setRecipient,
amount, setAmount,
sending,
retryCount, setRetryCount,
lastTxSignature, setLastTxSignature,
resetForm, startSending, stopSending,
} = useTransferForm();
const solanaClient = useMemo(() => {
return createSolanaClient({ urlOrMoniker: 'devnet' });
}, []);
const handleSend = async () => {
if (!signer || !recipient || !amount) {
alert('Please fill in all fields');
return;
}
// Wallet-UI uses gill's address() for validation
let recipientAddress;
try {
recipientAddress = address(recipient);
} catch {
alert('Invalid recipient address');
return;
}
const amountValidation = validateTransferAmount(amount, usdcBalance);
if (!amountValidation.valid) {
alert(amountValidation.error);
return;
}
startSending();
try {
const signature = await withRetry(
async () => {
const mint = address(USDC_MINT.toBase58());
const authority = address(account.address);
// Get ATA addresses
const sourceAta = await getAssociatedTokenAccountAddress(mint, authority, TOKEN_PROGRAM_ADDRESS);
const destinationAta = await getAssociatedTokenAccountAddress(mint, recipientAddress, TOKEN_PROGRAM_ADDRESS);
// Convert to raw amount (6 decimals for USDC)
const rawAmount = BigInt(Math.floor(amountValidation.amountNum! * Math.pow(10, USDC_DECIMALS)));
// Build transfer instructions
const instructions = getTransferTokensInstructions({
feePayer: signer,
mint,
authority: signer,
sourceAta,
destination: recipientAddress,
destinationAta,
amount: rawAmount,
tokenProgram: TOKEN_PROGRAM_ADDRESS,
});
// Fresh blockhash for each attempt
const { value: latestBlockhash } = await solanaClient.rpc.getLatestBlockhash().send();
const transaction = createTransaction({
version: 'legacy',
feePayer: signer,
instructions,
latestBlockhash,
});
console.log('Sending transaction via wallet-ui + gill...');
const signatureBytes = await signAndSendTransactionMessageWithSigners(transaction);
const sig = getSignatureFromBytes(signatureBytes);
console.log('Transaction signature:', sig);
return sig;
},
{
maxRetries: 3,
initialDelayMs: 1000,
onRetry: (attempt, error) => {
console.log(`Retry attempt ${attempt} after error:`, error);
setRetryCount(attempt);
}
}
);
setLastTxSignature(signature);
alert(createTransferSuccessMessage(amountValidation.amountNum!, recipient));
resetForm();
await fetchBalances();
} catch (err: unknown) {
console.error('Transfer error:', err);
alert(formatTransactionError(err, 'Transfer'));
} finally {
stopSending();
}
};
const theme = useThemeClasses();
return (
<div className={`${theme.bgCard} rounded-2xl p-6`}>
<h2 className={`text-xl font-bold ${theme.textPrimary} mb-6`}>Try Gasless Transfer</h2>
<div className="space-y-4">
<div className={`flex items-center justify-between p-4 ${theme.statusSuccess} rounded-xl`}>
<div>
<p className={`text-sm ${theme.textMuted}`}>Connected Wallet</p>
<p className={`${theme.textPrimary} font-mono text-sm`}>
{account.address.slice(0, 8)}...{account.address.slice(-8)}
</p>
</div>
<div className="relative z-100">
<WalletUiDropdown />
</div>
</div>
{/* Balance Display */}
<div className={`${theme.statusSuccess} rounded-xl p-4`}>
<div className="flex items-center justify-between mb-2">
<span className={`text-sm ${theme.textMuted}`}>Your USDC Balance</span>
<button
onClick={fetchBalances}
disabled={balanceLoading}
className={`text-xs ${theme.textAccent} hover:opacity-80 disabled:opacity-50 flex items-center gap-1`}
>
<span className={balanceLoading ? 'animate-spin' : ''}>🔄</span>
{balanceLoading ? 'Refreshing...' : 'Refresh'}
</button>
</div>
<div className={`text-3xl font-bold ${theme.textPrimary}`}>
{usdcBalance !== null ? `${usdcBalance.toFixed(2)} USDC` : 'Loading...'}
</div>
{usdcBalance === 0 && (
<p className={`text-xs ${theme.infoYellowTitle} mt-2`}>
No USDC? Get some from{' '}
<a href="https://faucet.circle.com/" target="_blank" className="underline">
Circle Faucet
</a>
</p>
)}
</div>
{/* Transfer Form */}
<div className="space-y-4">
<div>
<label className={`block text-sm ${theme.textMuted} mb-2`}>
Recipient Address
</label>
<input
type="text"
value={recipient}
onChange={(e) => setRecipient(e.target.value)}
placeholder="Enter Solana address..."
className={`w-full px-4 py-3 ${theme.bgInput} rounded-lg ${theme.textPrimary} placeholder-gray-500 focus:outline-none focus:border-purple-500 text-sm font-mono`}
/>
</div>
<div>
<label className={`block text-sm ${theme.textMuted} mb-2`}>
Amount (USDC)
</label>
<input
type="number"
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="0.00"
step="0.01"
min="0"
className={`w-full px-4 py-3 ${theme.bgInput} rounded-lg ${theme.textPrimary} placeholder-gray-500 focus:outline-none focus:border-purple-500 text-sm`}
/>
{usdcBalance !== null && usdcBalance > 0 && (
<button
onClick={() => setAmount(usdcBalance.toString())}
className={`text-xs ${theme.textAccent} hover:opacity-80 mt-1`}
>
Use Max ({usdcBalance.toFixed(2)})
</button>
)}
</div>
<button
onClick={handleSend}
disabled={sending || !recipient || !amount || usdcBalance === 0}
className="w-full px-6 py-4 bg-gradient-to-r from-green-500 to-emerald-500 hover:from-green-600 hover:to-emerald-600 text-white rounded-xl font-bold transition-all shadow-lg shadow-green-500/50 disabled:opacity-50 disabled:cursor-not-allowed text-sm md:text-base"
>
{sending
? retryCount > 0
? `Retrying... (${retryCount}/3)`
: 'Sending...'
: 'Send USDC'}
</button>
</div>
{/* Gasless Info */}
<div className={`${theme.infoBlue} rounded-lg p-4`}>
<div className="flex items-start gap-2">
<span className="text-xl">ℹ️</span>
<div>
<p className={`text-sm ${theme.infoBlueTitle} font-semibold mb-1`}>
Gasless with LazorKit
</p>
<p className={`text-xs ${theme.infoBlueText}`}>
When connected via LazorKit (passkey), the paymaster covers transaction fees.
Other wallets will pay standard SOL fees.
</p>
</div>
</div>
</div>
{/* Last Transaction */}
{lastTxSignature && (
<div className={`${theme.bgCard} rounded-lg p-4`}>
<p className={`text-xs ${theme.textMuted} mb-2`}>Last Transaction:</p>
<a
href={`https://explorer.solana.com/tx/${lastTxSignature}?cluster=devnet`}
target="_blank"
rel="noopener noreferrer"
className={`text-xs ${theme.textAccent} hover:opacity-80 break-all`}
>
{lastTxSignature.slice(0, 20)}...{lastTxSignature.slice(-20)} ↗
</a>
</div>
)}
</div>
</div>
);
}
function TransferDemo() {
const { account } = useWalletUi();
const theme = useThemeClasses();
if (!account) {
return (
<div className={`${theme.bgCard} rounded-2xl p-6`}>
<h2 className={`text-xl font-bold ${theme.textPrimary} mb-6`}>Try Gasless Transfer</h2>
<div className="text-center py-8">
<div className="text-6xl mb-6">💸</div>
<h3 className={`text-xl font-semibold ${theme.textPrimary} mb-4`}>
Connect Your Wallet
</h3>
<p className={`text-sm ${theme.textMuted} mb-6`}>
Click the button below to select a wallet. LazorKit will appear alongside other installed wallets.
</p>
<div className="flex justify-center relative z-100">
<WalletUiDropdown />
</div>
</div>
</div>
);
}
return <TransferDemoWithSigner account={account} />;
}
export default function WalletUIAdapterPage() {
const theme = useThemeClasses();
return (
<WalletUi config={config}>
<div className={`min-h-screen ${theme.bgPage} overflow-x-hidden`}>
<div className="container mx-auto px-4 py-8 max-w-7xl">
<div className="mb-8">
<Link
href="/examples/05-wallet-adapter-integration"
className={`${theme.textAccent} hover:opacity-80 mb-4 inline-block`}
>
← Back to Wallet Adapters
</Link>
<div className="flex items-center gap-3 mb-2">
<Image
src='/icons/walletui.png'
alt='Wallet-UI'
width={32}
height={32}
className="rounded-md"
/>
<div className="flex-1 min-w-0">
<h1 className={`text-3xl md:text-4xl font-bold ${theme.textPrimary} break-words`}>
Wallet-UI Adapter
</h1>
</div>
</div>
<p className={`${theme.textMuted} text-sm md:text-base`}>
Modern wallet UI with gill transaction building
</p>
</div>
<div className="grid lg:grid-cols-2 gap-6 lg:gap-8">
{/* Left Panel - Code Example */}
<div className="space-y-6 w-full min-w-0">
{/* Installation */}
<div className={`${theme.bgCard} rounded-2xl p-6`}>
<h2 className={`text-xl font-bold ${theme.textPrimary} mb-4`}>Installation</h2>
<div className={`${theme.codeBlock} rounded-lg p-4 overflow-x-auto`}>
<pre className="text-xs text-gray-100">
{`npm install @wallet-ui/react gill \\
@lazorkit/wallet`}
</pre>
</div>
</div>
{/* Provider Setup */}
<div className={`${theme.bgCard} rounded-2xl p-6`}>
<h2 className={`text-xl font-bold ${theme.textPrimary} mb-4`}>Provider Setup</h2>
<div className={`${theme.codeBlock} rounded-lg p-4 overflow-x-auto`}>
<pre className="text-xs text-gray-100">
{`import { useEffect } from 'react';
import {
createSolanaDevnet,
createWalletUiConfig,
WalletUi,
} from '@wallet-ui/react';
import { registerLazorkitWallet } from '@lazorkit/wallet';
const config = createWalletUiConfig({
clusters: [createSolanaDevnet()],
});
function AppProvider({ children }) {
// Register LazorKit on mount
useEffect(() => {
registerLazorkitWallet({
rpcUrl: 'https://api.devnet.solana.com',
portalUrl: 'https://portal.lazor.sh',
paymasterConfig: {
paymasterUrl: 'https://kora.devnet.lazorkit.com',
},
clusterSimulation: 'devnet',
});
}, []);
return (
<WalletUi config={config}>
{children}
</WalletUi>
);
}`}
</pre>
</div>
</div>
{/* Using the Hooks */}
<div className={`${theme.bgCard} rounded-2xl p-6`}>
<h2 className={`text-xl font-bold ${theme.textPrimary} mb-4`}>Using the Hooks</h2>
<div className={`${theme.codeBlock} rounded-lg p-4 overflow-x-auto`}>
<pre className="text-xs text-gray-100">
{`import {
useWalletUi,
useWalletUiSigner,
WalletUiDropdown
} from '@wallet-ui/react';
import {
address,
createSolanaClient,
createTransaction
} from 'gill';
import {
getTransferTokensInstructions,
getAssociatedTokenAccountAddress,
} from 'gill/programs/token';
function MyComponent() {
const { account } = useWalletUi();
const signer = useWalletUiSigner({ account });
const client = createSolanaClient({ urlOrMoniker: 'devnet' });
const handleSend = async () => {
const instructions = getTransferTokensInstructions({
feePayer: signer,
mint: address('...'),
authority: signer,
sourceAta: await getAssociatedTokenAccountAddress(...),
destination: address('...'),
destinationAta: await getAssociatedTokenAccountAddress(...),
amount: 1000000n, // 1 USDC (6 decimals)
});
const { value: latestBlockhash } = await client.rpc
.getLatestBlockhash().send();
const tx = createTransaction({
version: 'legacy',
feePayer: signer,
instructions,
latestBlockhash,
});
const sig = await client.sendAndConfirmTransaction(tx);
};
return (
<div>
<WalletUiDropdown />
{account && (
<button onClick={handleSend}>Send TX</button>
)}
</div>
);
}`}
</pre>
</div>
</div>
{/* Key Points */}
<div className={`${theme.infoBlue} rounded-2xl p-6`}>
<h2 className={`text-xl font-bold ${theme.textPrimary} mb-4`}>Key Points</h2>
<ul className={`space-y-3 text-sm ${theme.textSecondary}`}>
<li className="flex items-start gap-3">
<span className="text-green-500 mt-0.5 flex-shrink-0">✓</span>
<span><strong>Gill Integration:</strong> Modern transaction building with Solana Kit</span>
</li>
<li className="flex items-start gap-3">
<span className="text-green-500 mt-0.5 flex-shrink-0">✓</span>
<span><strong>useWalletUiSigner:</strong> Returns a TransactionSendingSigner for signing</span>
</li>
<li className="flex items-start gap-3">
<span className="text-green-500 mt-0.5 flex-shrink-0">✓</span>
<span><strong>Wallet-Standard:</strong> LazorKit auto-discovered after registration</span>
</li>
<li className="flex items-start gap-3">
<span className="text-green-500 mt-0.5 flex-shrink-0">✓</span>
<span><strong>Gasless for LazorKit:</strong> Paymaster auto-handles gas when using LazorKit</span>
</li>
</ul>
</div>
</div>
{/* Right Panel - Demo */}
<div className="space-y-6 w-full min-w-0 lg:sticky lg:top-8 lg:self-start">
<div className="relative z-100">
<TransferDemo />
</div>
{/* Links */}
<div className={`${theme.bgCard} rounded-2xl p-6`}>
<h3 className={`text-lg font-semibold ${theme.textPrimary} mb-4`}>Resources</h3>
<div className="space-y-2">
<a
href="https://wallet-ui.dev"
target="_blank"
rel="noopener noreferrer"
className={`flex items-center gap-2 ${theme.textAccent} hover:opacity-80 text-sm`}
>
<span>📚</span> Wallet-UI Documentation
</a>
<a
href="https://github.com/wallet-ui/wallet-ui"
target="_blank"
rel="noopener noreferrer"
className={`flex items-center gap-2 ${theme.textAccent} hover:opacity-80 text-sm`}
>
<span>💻</span> Wallet-UI GitHub
</a>
<a
href="https://github.com/solana-developers/gill"
target="_blank"
rel="noopener noreferrer"
className={`flex items-center gap-2 ${theme.textAccent} hover:opacity-80 text-sm`}
>
<span>🐟</span> Gill Documentation
</a>
<a
href="https://docs.lazorkit.com/"
target="_blank"
rel="noopener noreferrer"
className={`flex items-center gap-2 ${theme.textAccent} hover:opacity-80 text-sm`}
>
<span>🔑</span> LazorKit Documentation
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</WalletUi>
);
}