-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswap-test.html
More file actions
577 lines (576 loc) · 33.2 KB
/
Copy pathswap-test.html
File metadata and controls
577 lines (576 loc) · 33.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
574
575
576
577
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Swap Engine Testbed - All Pairs</title>
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
<script src="https://unpkg.com/@solana/web3.js@1.95.8/lib/index.iife.min.js"></script>
<!-- Shared Swap Utilities -->
<script src="assets/js/webapp/swapUtils.js"></script>
<style>
body { font-family: system-ui, sans-serif; }
select {
background-color: #18181b !important;
color: white !important;
border: 1px solid #3f3f46;
}
select option {
background-color: #18181b;
color: white;
}
.status-dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
}
#diagnostic-console {
background-color: #18181b;
border: 1px solid #3f3f46;
}
.log-entry { font-family: monospace; }
</style>
<script>
// ==================== VITE + RAILWAY CONFIG ====================
const isViteDev = location.port === '5173';
const CONFIG = {
PROD_BASE: "https://giddy-key-swaps-production.up.railway.app",
LOCAL_BASE: "http://localhost:3000",
_base: null,
get BASE() {
if (isViteDev) return '';
return this._base || this.PROD_BASE;
},
set BASE(value) {
this._base = value;
}
};
function getApiUrl(endpoint) {
let clean = endpoint.startsWith('/') ? endpoint : '/' + endpoint;
return CONFIG.BASE + clean;
}
async function testBackendConnection() {
if (isViteDev) {
logger("🟢 Vite dev server detected (port 5173) → Using proxy. Railway & Localhost checks skipped.", false);
CONFIG.BASE = '';
updateServerStatus();
return '';
}
// Normal flow when not using Vite
logger("🔍 Testing Railway Production...", false);
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
const res = await fetch(CONFIG.PROD_BASE + '/api/prices', {
method: 'GET',
cache: 'no-store',
headers: { 'Accept': 'application/json' },
signal: controller.signal
});
clearTimeout(timeout);
if (res.ok) {
logger("✅ Railway Production Connected", false);
CONFIG.BASE = CONFIG.PROD_BASE;
updateServerStatus();
return CONFIG.PROD_BASE;
}
} catch (e) {
logger("⚠️ Railway unreachable", true);
}
logger("🔄 Falling back to Localhost...", false);
CONFIG.BASE = CONFIG.LOCAL_BASE;
updateServerStatus();
return CONFIG.LOCAL_BASE;
}
function updateServerStatus() {
const statusContainer = document.getElementById('serverStatus');
if (!statusContainer) return;
if (isViteDev) {
// Vite mode - unified dark style
statusContainer.innerHTML = `
<div class="bg-black border border-purple-500/30 rounded-2xl p-4 text-xs space-y-2">
<div class="flex items-center gap-2">
<span class="status-dot bg-purple-500"></span>
<span class="font-semibold text-purple-400">Vite Dev Server Active</span>
</div>
<div class="text-[10px] text-zinc-400 pl-5">
Using Vite proxy → <strong>localhost:3000</strong><br>
Railway Production: <span class="text-amber-400">Skipped</span><br>
Localhost: <span class="text-amber-400">Skipped</span>
</div>
</div>`;
return;
}
// Normal mode
const statusHTML = `
<div class="bg-black border border-zinc-700 rounded-2xl p-4 text-xs space-y-2">
<div class="flex items-center gap-2">
<span class="status-dot ${CONFIG.BASE === CONFIG.PROD_BASE ? 'bg-emerald-500' : 'bg-amber-500'}"></span>
<span>Railway Production</span>
<span class="ml-auto">${CONFIG.BASE === CONFIG.PROD_BASE ? '✅ Active' : '⏳ Skipped / Failed'}</span>
</div>
<div class="flex items-center gap-2">
<span class="status-dot ${CONFIG.BASE === CONFIG.LOCAL_BASE ? 'bg-emerald-500' : 'bg-zinc-500'}"></span>
<span>Localhost (Dev)</span>
<span class="ml-auto">${CONFIG.BASE === CONFIG.LOCAL_BASE ? '✅ Active' : '⏳ Skipped / Failed'}</span>
</div>
<div class="pt-2 border-t border-zinc-700 text-purple-400">
Active Backend: <strong>${CONFIG.BASE}</strong>
</div>
</div>`;
statusContainer.innerHTML = statusHTML;
}
</script>
</head>
<body class="bg-zinc-950 text-zinc-100 min-h-screen">
<div class="max-w-7xl mx-auto p-6">
<header class="flex flex-col sm:flex-row justify-between items-start border-b border-zinc-800 pb-6 mb-8 gap-6">
<div>
<h1 class="text-3xl font-bold tracking-tight">Swap Engine Testbed</h1>
<p class="text-zinc-400">Phantom SDK + window.solana • Jupiter Ultra + v1 Proxy</p>
</div>
<div class="flex flex-col items-start gap-3">
<div class="flex flex-wrap gap-2">
<button onclick="connectWithSDK()"
class="flex items-center gap-2 px-5 py-2.5 bg-violet-600 hover:bg-violet-500 font-semibold rounded-2xl transition-all text-sm">
SDK Connect
</button>
<button onclick="connectWithWindowSolana()"
class="flex items-center gap-2 px-5 py-2.5 bg-blue-600 hover:bg-blue-500 font-semibold rounded-2xl transition-all text-sm">
window.solana
</button>
<button onclick="checkConnectionStatus()"
class="flex items-center gap-2 px-5 py-2.5 bg-zinc-700 hover:bg-zinc-600 font-semibold rounded-2xl transition-all text-sm">
Status
</button>
<button onclick="disconnectAll()"
class="flex items-center gap-2 px-5 py-2.5 bg-red-600 hover:bg-red-500 font-semibold rounded-2xl transition-all text-sm">
Disconnect All
</button>
</div>
<div id="walletBadge"
class="hidden flex items-center gap-2 bg-zinc-900 border border-emerald-500 px-4 py-2 rounded-2xl w-fit">
<span class="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></span>
<span id="walletAddressDisplay" class="font-mono text-sm text-purple-400"></span>
<span id="modeDisplay" class="ml-2 text-[10px] uppercase tracking-widest font-mono px-2 py-0.5 rounded-full bg-zinc-800"></span>
</div>
</div>
</header>
<div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
<div class="xl:col-span-4">
<div id="diagnostic-console" class="rounded-3xl p-6 sticky top-6">
<h2 class="font-bold text-lg text-purple-400 mb-4">Jupiter Diagnostic Console</h2>
<div id="serverStatus" class="mb-4"></div>
<div class="flex flex-wrap gap-2 mb-4">
<button onclick="checkEndpoint('ultra')" class="flex-1 bg-zinc-800 hover:bg-zinc-700 py-3 rounded-2xl text-sm font-medium">Test Ultra</button>
<button onclick="checkEndpoint('v1')" class="flex-1 bg-zinc-800 hover:bg-zinc-700 py-3 rounded-2xl text-sm font-medium">Test v1 Proxy</button>
<button onclick="testKinnected()" class="flex-1 bg-zinc-800 hover:bg-zinc-700 py-3 rounded-2xl text-sm font-medium">Test Kinnected</button>
</div>
<div id="logWindow" class="h-80 bg-black rounded-2xl p-4 text-[10px] font-mono overflow-y-auto border border-zinc-700 mb-4"></div>
<div class="text-xs text-zinc-400 space-y-1">
<p><span class="text-purple-400">Ultra:</span> <span id="ultraUrl" class="break-all"></span></p>
<p><span class="text-purple-400">v1 Proxy:</span> <span id="v1Url" class="break-all"></span></p>
</div>
</div>
</div>
<div class="xl:col-span-8 space-y-8">
<div class="bg-zinc-900 border border-zinc-800 rounded-3xl p-6 md:p-8">
<h2 class="text-2xl font-bold mb-2">Quick Swap</h2>
<div class="flex flex-col sm:flex-row items-center gap-2 mb-6 bg-zinc-950 border border-zinc-700 rounded-3xl p-2">
<select id="fromToken" onchange="handleDropdownChange('from')" class="w-full sm:flex-1 bg-zinc-900 text-white font-medium text-lg px-4 py-3 rounded-2xl focus:outline-none"></select>
<div class="text-2xl sm:text-3xl text-purple-400 font-light rotate-90 sm:rotate-0 my-1 sm:my-0">→</div>
<select id="toToken" onchange="handleDropdownChange('to')" class="w-full sm:flex-1 bg-zinc-900 text-white font-medium text-lg px-4 py-3 rounded-2xl focus:outline-none"></select>
</div>
<p id="pairDisplay" class="text-emerald-400 mb-6 text-center font-medium text-sm">eXPB → USDC</p>
<div class="grid grid-cols-2 gap-3 mb-6" id="amountButtons"></div>
<button onclick="executeSelectedSwap()" id="swapBtn"
class="w-full bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 py-5 sm:py-6 rounded-3xl font-bold text-lg sm:text-xl shadow-xl disabled:opacity-50"
disabled>Execute Selected Swap</button>
<div id="result" class="mt-6"></div>
</div>
<div id="walletInfo" class="hidden bg-zinc-900 border border-zinc-800 rounded-3xl p-8">
<div class="flex justify-between items-center mb-6">
<h3 class="text-lg font-bold">Your Live Wallet Balances</h3>
<button onclick="fetchWalletBalances()" class="text-sm bg-zinc-800 hover:bg-zinc-700 px-4 py-2 rounded-xl flex items-center gap-1.5">
<span>🔄</span> Refresh Balances
</button>
</div>
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
<div class="bg-zinc-950 p-4 rounded-xl border border-zinc-800/80"><span class="text-xs text-zinc-500 block font-semibold">SOL Balance</span><span id="bal-SOL" class="text-xl font-black text-purple-300 mt-1 block">Loading...</span></div>
<div class="bg-zinc-950 p-4 rounded-xl border border-zinc-800/80"><span class="text-xs text-zinc-500 block font-semibold">USDC Balance</span><span id="bal-USDC" class="text-xl font-black text-purple-300 mt-1 block">Loading...</span></div>
<div class="bg-zinc-950 p-4 rounded-xl border border-zinc-800/80"><span class="text-xs text-zinc-500 block font-semibold">EXPB Balance</span><span id="bal-EXPB" class="text-xl font-black text-purple-300 mt-1 block">Loading...</span></div>
<div class="bg-zinc-950 p-4 rounded-xl border border-zinc-800/80"><span class="text-xs text-zinc-500 block font-semibold">GIDDY Balance</span><span id="bal-GIDDY" class="text-xl font-black text-purple-300 mt-1 block">Loading...</span></div>
<div class="bg-zinc-950 p-4 rounded-xl border border-yellow-500/30"><span class="text-xs text-yellow-400 block font-semibold">ONE Balance</span><span id="bal-ONE" class="text-xl font-black text-yellow-300 mt-1 block">Loading...</span></div>
<div class="bg-zinc-950 p-4 rounded-xl border border-yellow-500/30"><span class="text-xs text-yellow-400 block font-semibold">KIN Balance</span><span id="bal-KIN" class="text-xl font-black text-yellow-300 mt-1 block">Loading...</span></div>
<div class="bg-zinc-950 p-4 rounded-xl border border-yellow-500/30"><span class="text-xs text-yellow-400 block font-semibold">DOBBY Balance</span><span id="bal-DOBBY" class="text-xl font-black text-yellow-300 mt-1 block">Loading...</span></div>
<div class="bg-zinc-950 p-4 rounded-xl border border-yellow-500/30"><span class="text-xs text-yellow-400 block font-semibold">MYLO Balance</span><span id="bal-MYLO" class="text-xl font-black text-yellow-300 mt-1 block">Loading...</span></div>
<div class="bg-zinc-950 p-4 rounded-xl border border-yellow-500/30"><span class="text-xs text-yellow-400 block font-semibold">DUNO Balance</span><span id="bal-DUNO" class="text-xl font-black text-yellow-300 mt-1 block">Loading...</span></div>
<div class="bg-zinc-950 p-4 rounded-xl border border-yellow-500/30"><span class="text-xs text-yellow-400 block font-semibold">CPT Balance</span><span id="bal-CPT" class="text-xl font-black text-yellow-300 mt-1 block">Loading...</span></div>
<div class="bg-zinc-950 p-4 rounded-xl border border-yellow-500/30"><span class="text-xs text-yellow-400 block font-semibold">SINU Balance</span><span id="bal-SINU" class="text-xl font-black text-yellow-300 mt-1 block">Loading...</span></div>
</div>
</div>
<div>
<h2 class="text-xl font-bold mb-4">Tracked Asset Prices</h2>
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4" id="priceGrid"></div>
</div>
</div>
</div>
</div>
<script>
// Buffer polyfill
if (typeof Buffer === 'undefined') {
window.Buffer = {
from: function (value, encoding) {
if (typeof value === 'string' && encoding === 'base64') {
const binary = atob(value);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
if (value instanceof Uint8Array || value?.buffer instanceof ArrayBuffer) {
return new Uint8Array(value.buffer || value);
}
return value;
}
};
}
// ==================== TOKEN CONFIG ====================
const TOKEN_CONFIG = {
EXPB: { symbol: "eXPB", mint: "GsKuLQsKCEnfQxuk4icTEQjc11Av8WiqW31CxZqZpump", decimals: 6 },
GIDDY: { symbol: "GIDDY", mint: "8kQzvMELBQGSiFmrXqLuDSpYVLKkNoXE4bUQCC14wj3Z", decimals: 6 },
SOL: { symbol: "SOL", mint: "So11111111111111111111111111111111111111112", decimals: 9 },
USDC: { symbol: "USDC", mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", decimals: 6 },
ONE: { symbol: "ONE", mint: "9Fdne837tZp97nDZTUqxv9t8Gwp2BwRf8EF7PGAAfoNe", decimals: 6 },
KIN: { symbol: "KIN", mint: "kinXdEcpDQeHPEuQnqmUgtYykqKGVFq6CeVX5iAHJq6", decimals: 5 },
DOBBY: { symbol: "DOBBY", mint: "CPcf58MNikQw2G23kTVWQevRDeFDpdxMH7KkR7Lhpump", decimals: 6 },
MYLO: { symbol: "MYLO", mint: "G37R1ppRgRiMAhk5a3YMRpcfyLNs5mgJij5j7JJ4Yshn", decimals: 6 },
DUNO: { symbol: "DUNO", mint: "7F8oGQ565GYgV4XtaMVG5NP9vevcKQhsRCaHHPNpvg4e", decimals: 5 },
CPT: { symbol: "CPT", mint: "2umQqRyexgfHcndkULDKStmJJ8xgDz7oBL3EfDJNmoon", decimals: 6 },
SINU: { symbol: "SINU", mint: "DXi3Uu7TC2tzJYmnFAgDKnU3p8t6qSafPcLgGaQipump", decimals: 6 }
};
let currentSigner = null;
let isUsingSDK = false;
let connectedWallet = null;
let provider = null;
let selectedUiAmount = 1000;
let currentInputMint = TOKEN_CONFIG.EXPB.mint;
let currentOutputMint = TOKEN_CONFIG.USDC.mint;
let currentInputSymbol = "eXPB";
let currentInputDecimals = 6;
function logger(msg, isErr = false) {
const log = document.getElementById('logWindow');
const cssClass = isErr ? 'text-red-400' : 'text-emerald-400';
log.innerHTML += `<div class="log-entry ${cssClass}">[${new Date().toLocaleTimeString()}] ${msg}</div>`;
log.scrollTop = log.scrollHeight;
}
// ==================== SDK HELPERS ====================
async function getPhantomSDK() {
if (window.PhantomBrowserSDK) return window.PhantomBrowserSDK;
await new Promise(r => setTimeout(r, 150));
return window.PhantomBrowserSDK;
}
async function connectWithSDK() {
logger("🚀 Connecting with Phantom SDK...", false);
isUsingSDK = true;
try {
const SDKClass = await getPhantomSDK();
if (!SDKClass) throw new Error("SDK library not loaded");
const sdk = new SDKClass({
providers: ["injected"],
addressTypes: ["solana"],
appId: "62ccac9b-8746-42db-8a6d-45e2c97f7f58",
autoConnect: true,
});
window._phantomSDK = sdk;
const result = await sdk.connect({ provider: "injected" });
connectedWallet = result.addresses?.[0]?.address;
currentSigner = sdk.solana;
provider = currentSigner;
updateWalletUI();
logger(`✅ SDK Connected: ${connectedWallet.slice(0,8)}...${connectedWallet.slice(-4)}`, false);
fetchWalletBalances();
} catch (e) {
logger(`❌ SDK Connect failed: ${e.message}`, true);
console.error(e);
}
}
async function connectWithWindowSolana() {
logger("🚀 Connecting with window.solana...", false);
isUsingSDK = false;
try {
provider = window.phantom?.solana || window.solana;
if (!provider?.isPhantom) {
logger("❌ Phantom not detected", true);
return;
}
const resp = await provider.connect();
connectedWallet = resp.publicKey.toString();
currentSigner = provider;
updateWalletUI();
logger(`✅ window.solana Connected: ${connectedWallet.slice(0,8)}...${connectedWallet.slice(-4)}`, false);
fetchWalletBalances();
} catch (e) {
logger(`❌ window.solana failed: ${e.message}`, true);
}
}
function updateWalletUI() {
const badge = document.getElementById('walletBadge');
if (!connectedWallet) return;
badge.classList.remove('hidden');
document.getElementById('walletAddressDisplay').textContent = connectedWallet.slice(0, 8) + "..." + connectedWallet.slice(-4);
const modeEl = document.getElementById('modeDisplay');
modeEl.textContent = isUsingSDK ? "SDK" : "WINDOW";
modeEl.className = `ml-2 text-[10px] uppercase tracking-widest font-mono px-2 py-0.5 rounded-full ${isUsingSDK ? 'bg-violet-500/20 text-violet-400' : 'bg-blue-500/20 text-blue-400'}`;
document.getElementById('swapBtn').disabled = false;
document.getElementById('walletInfo').classList.remove('hidden');
}
async function checkConnectionStatus() {
logger("🔍 Checking connection status...", false);
logger(`Mode: ${isUsingSDK ? 'Phantom SDK' : 'window.solana'}`, false);
logger(`Wallet: ${connectedWallet || 'None'}`, false);
logger(`Signer ready: ${!!currentSigner}`, false);
}
function disconnectAll() {
logger("🔌 Disconnecting all...", false);
if (window._phantomSDK) window._phantomSDK.disconnect().catch(() => {});
if (window.solana) window.solana.disconnect().catch(() => {});
if (window.phantom?.solana) window.phantom.solana.disconnect().catch(() => {});
connectedWallet = null;
currentSigner = null;
provider = null;
isUsingSDK = false;
document.getElementById('walletBadge').classList.add('hidden');
document.getElementById('walletInfo').classList.add('hidden');
document.getElementById('swapBtn').disabled = true;
logger("✅ All disconnected", false);
}
// ==================== TOKEN UI ====================
function populateTokenSelects() {
const from = document.getElementById('fromToken'), to = document.getElementById('toToken');
from.innerHTML = '';
to.innerHTML = '';
Object.keys(TOKEN_CONFIG).forEach(key => {
const t = TOKEN_CONFIG[key];
from.appendChild(new Option(t.symbol, t.mint));
to.appendChild(new Option(t.symbol, t.mint));
});
from.value = TOKEN_CONFIG.EXPB.mint;
to.value = TOKEN_CONFIG.USDC.mint;
}
function handleDropdownChange(changed) {
const from = document.getElementById('fromToken'), to = document.getElementById('toToken');
if (from.value === to.value) {
const keys = Object.keys(TOKEN_CONFIG);
const currentIndex = keys.findIndex(k => TOKEN_CONFIG[k].mint === (changed === 'from' ? from.value : to.value));
const nextIndex = (currentIndex + 1) % keys.length;
if (changed === 'from') to.value = TOKEN_CONFIG[keys[nextIndex]].mint;
else from.value = TOKEN_CONFIG[keys[nextIndex]].mint;
}
updatePair();
}
function updatePair() {
currentInputMint = document.getElementById('fromToken').value;
currentOutputMint = document.getElementById('toToken').value;
const config = Object.values(TOKEN_CONFIG).find(t => t.mint === currentInputMint);
currentInputSymbol = config.symbol;
currentInputDecimals = config.decimals;
document.getElementById('pairDisplay').textContent = `${currentInputSymbol} → ${document.getElementById('toToken').selectedOptions[0].text}`;
updateAmountButtons();
}
function updateAmountButtons() {
const container = document.getElementById('amountButtons');
container.innerHTML = '';
let presets = [];
if (currentInputSymbol === 'SOL') {
presets = [{ ui: 0.001, label: '0.001' }, { ui: 0.01, label: '0.01' }, { ui: 0.1, label: '0.1' }, { ui: 1, label: '1' }];
} else if (['USDC', 'GIDDY', 'ONE'].includes(currentInputSymbol)) {
presets = [{ ui: 0.1, label: '0.1' }, { ui: 1, label: '1' }, { ui: 10, label: '10' }, { ui: 100, label: '100' }];
} else {
presets = [{ ui: 100, label: '100' }, { ui: 1000, label: '1,000' }, { ui: 10000, label: '10,000' }, { ui: 2000, label: '~2,000' }];
}
presets.forEach((p, i) => {
const btn = document.createElement('button');
btn.className = `amount-btn py-4 rounded-2xl font-medium transition-all ${i === 1 ? 'ring-2 ring-purple-500 bg-purple-900/30' : 'bg-zinc-800 hover:bg-zinc-700'}`;
btn.textContent = `${p.label} ${currentInputSymbol}`;
btn.onclick = () => selectUiAmount(btn, p.ui);
container.appendChild(btn);
});
selectedUiAmount = presets[1].ui;
}
function selectUiAmount(btn, amount) {
document.querySelectorAll('.amount-btn').forEach(b => {
b.className = 'amount-btn py-4 rounded-2xl font-medium transition-all bg-zinc-800 hover:bg-zinc-700';
});
btn.className = 'amount-btn py-4 rounded-2xl font-medium transition-all ring-2 ring-purple-500 bg-purple-900/30';
selectedUiAmount = amount;
}
// ==================== SWAP & BALANCES ====================
async function executeSelectedSwap() {
if (!connectedWallet) return alert("Connect wallet first");
await performSwap();
}
async function performSwap() {
const btn = document.getElementById('swapBtn');
btn.disabled = true;
btn.textContent = "Trying Ultra...";
const rawAmount = Math.floor(selectedUiAmount * Math.pow(10, currentInputDecimals));
logger(`🔄 SWAP: ${selectedUiAmount} ${currentInputSymbol} → ${rawAmount} raw`);
try {
const result = await performUltraSwap(
currentInputMint,
currentOutputMint,
rawAmount,
provider || currentSigner,
connectedWallet
);
document.getElementById('result').innerHTML = `
<div class="bg-emerald-900/30 p-5 rounded-2xl">
✅ <strong>Ultra Success</strong> via ${result.router}<br>
<a href="https://solscan.io/tx/${result.txid}" target="_blank" class="text-purple-400 underline">View on Solscan</a>
</div>`;
logger(`✅ Ultra swap sent! Router: ${result.router}`, false);
} catch (e) {
const errorMsg = e.message || '';
if (errorMsg.includes("User rejected") || errorMsg.includes("rejected the request")) {
logger(`❌ User cancelled transaction`, true);
document.getElementById('result').innerHTML = `<div class="bg-yellow-900/30 p-5 rounded-2xl text-yellow-300">Transaction cancelled by user.</div>`;
} else {
logger(`⚠️ Ultra failed: ${errorMsg}`, true);
logger("→ Trying v1 proxy...");
try {
const result = await performV1Swap(
currentInputMint,
currentOutputMint,
rawAmount,
provider || currentSigner,
connectedWallet
);
document.getElementById('result').innerHTML = `
<div class="bg-emerald-900/30 p-5 rounded-2xl">
✅ <strong>v1 Proxy Success</strong><br>
<a href="https://solscan.io/tx/${result.txid}" target="_blank" class="text-purple-400 underline">View on Solscan</a>
</div>`;
} catch (v1Err) {
logger(`❌ v1 proxy failed: ${v1Err.message}`, true);
document.getElementById('result').innerHTML = `<div class="bg-red-900/30 p-5 rounded-2xl">❌ Swap failed on both routes</div>`;
}
}
} finally {
btn.disabled = false;
btn.textContent = "Execute Selected Swap";
}
}
async function testKinnected() {
logger("🧪 Testing Kinnected Redeem API...");
const testPayload = {
linkId: "1234567890123",
destinationWallet: connectedWallet || "11111111111111111111111111111111"
};
const possibleUrls = [
"https://giddy-key-swaps-production.up.railway.app/api/secure-redeem",
"http://127.0.0.1:5000/api/secure-redeem",
"http://localhost:5000/api/secure-redeem"
];
let success = false;
for (const url of possibleUrls) {
try {
logger(`→ Trying ${url.includes('railway') ? 'Railway' : 'Localhost'}`, false);
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(testPayload)
});
const data = await res.json();
logger(`✅ Kinnected Test ${res.status} ${res.ok ? 'OK' : 'Failed'}`, !res.ok);
console.log("Kinnected Response:", data);
success = true;
break;
} catch (e) {
logger(`❌ ${url.includes('railway') ? 'Railway' : 'Localhost'} failed`, true);
}
}
if (!success) {
logger("❌ All Kinnected endpoints failed", true);
}
}
async function checkEndpoint(type) {
logger(`Testing ${type.toUpperCase()}...`);
const rawTestAmount = 1000000;
try {
let url = '';
if (type === 'ultra') {
url = `https://lite-api.jup.ag/ultra/v1/order?inputMint=${currentInputMint}&outputMint=${currentOutputMint}&amount=${rawTestAmount}&taker=${connectedWallet || '11111111111111111111111111111111'}`;
document.getElementById('ultraUrl').textContent = url;
} else {
url = getApiUrl('/api/swap/v1');
document.getElementById('v1Url').textContent = url;
}
const res = await fetch(url, {
method: type === 'ultra' ? 'GET' : 'POST',
headers: type === 'ultra' ? {} : { 'Content-Type': 'application/json' },
body: type === 'ultra' ? null : JSON.stringify({
inputMint: currentInputMint,
outputMint: currentOutputMint,
rawAmount: rawTestAmount,
connectedWallet: connectedWallet || '11111111111111111111111111111111'
})
});
logger(`${type.toUpperCase()} → ${res.status} ${res.ok ? '✅' : '❌'}`, !res.ok);
} catch (e) {
logger(`❌ ${type.toUpperCase()} Failed: ${e.message}`, true);
}
}
async function fetchWalletBalances() {
if (!connectedWallet) {
logger("⚠️ No wallet connected for balance check", true);
return;
}
try {
logger(`🔄 Fetching balances for ${connectedWallet.slice(0,8)}...`);
const res = await fetch(getApiUrl(`/api/balances/${connectedWallet}`));
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
['SOL', 'USDC', 'EXPB', 'GIDDY', 'ONE', 'KIN', 'DOBBY', 'MYLO', 'DUNO', 'CPT', 'SINU'].forEach(t => {
const el = document.getElementById(`bal-${t}`);
if (el) {
el.innerText = `${data[t] || 0} ${t}`;
}
});
logger("✅ Balances updated", false);
} catch (e) {
logger(`❌ Balance fetch failed: ${e.message}`, true);
console.warn("Balance fetch failed", e);
}
}
async function fetchTokenPrices() {
try {
const res = await fetch(getApiUrl('/api/prices'));
if (!res.ok) throw new Error("Price server error");
const data = await res.json();
const grid = document.getElementById('priceGrid');
grid.innerHTML = '';
Object.keys(TOKEN_CONFIG).forEach(s => {
const d = data[s] || {};
const div = document.createElement('div');
div.className = "bg-zinc-900 p-5 rounded-2xl border border-zinc-800";
div.innerHTML = `<div class="text-sm font-semibold text-zinc-400">${s}</div><div class="text-2xl font-black text-emerald-400 mt-2">${d.price ? '$' + Number(d.price).toFixed(6) : 'No Pool'}</div>`;
grid.appendChild(div);
});
} catch (e) {
document.getElementById('priceGrid').innerHTML = `<div class="text-amber-400">Backend not reachable<br><small>${CONFIG.BASE}</small></div>`;
}
}
// INIT
logger("🚀 Swap Testbed + SDK Test Functions Loaded", false);
populateTokenSelects();
updatePair();
(async () => {
await testBackendConnection();
fetchTokenPrices();
setInterval(fetchTokenPrices, 15000);
})();
console.log("%cCurrent full config:", "color: orange; font-weight: bold", CONFIG);
</script>
</body>
</html>