-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
616 lines (594 loc) · 38.9 KB
/
index.html
File metadata and controls
616 lines (594 loc) · 38.9 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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Gatefunfun</title>
<link rel="icon" type="image/png" href="https://www.woofswap.finance/image/tokens/gdog.png">
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script>
tailwind.config = {
theme: {
extend: {
colors: {
primary: '#0068FF',
secondary: '#18E5A0',
accent: '#FFD700',
dark: '#070808',
'light-gray': '#E5E7EB'
},
fontFamily: {
sans: ['Inter', 'system-ui', 'sans-serif'],
display: ['Changa One', 'system-ui', 'sans-serif']
},
animation: {
'float': 'float 3s ease-in-out infinite'
},
keyframes: {
float: {
'0%, 100%': { transform: 'translateY(0)' },
'50%': { transform: 'translateY(-8px)' }
}
}
}
}
}
</script>
<style type="text/tailwindcss">
.text-shadow-glow {
text-shadow: 0 0 10px rgba(0, 104, 255, 0.5);
}
.glow-border {
box-shadow: 0 0 12px rgba(24, 229, 160, 0.3);
}
.bg-grid {
background-image: url('data:image/svg+xml,%3Csvg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"%3E%3Ccircle cx="1" cy="1" r="1" fill="%230068FF" fill-opacity="0.1"/%3E%3C/svg%3E');
background-size: 20px 20px;
}
.token-table th, .token-table td {
padding: 12px;
text-align: center;
border-bottom: 1px solid rgba(24, 229, 160, 0.2);
vertical-align: middle;
}
.token-table tr:hover {
background-color: rgba(24, 229, 160, 0.1);
}
</style>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&family=Changa+One&display=swap" rel="stylesheet">
</head>
<body class="bg-dark text-white font-sans overflow-x-hidden">
<header class="fixed w-full z-50 bg-dark/90 backdrop-blur-md transition-all duration-300" id="navbar">
<div class="container mx-auto px-4 py-4 flex justify-between items-center">
<div class="flex items-center space-x-3 cursor-pointer hover:text-primary transition-colors">
<div class="w-10 h-10 rounded-full overflow-hidden">
<img src="https://www.woofswap.finance/image/tokens/gdog.png" alt="GDOG Logo" class="w-full h-full object-cover">
</div>
<span class="font-display text-3xl text-primary text-shadow-glow">Gatefunfun</span>
</div>
<button id="menuToggle" class="md:hidden text-2xl text-primary">
<i class="fa fa-bars"></i>
</button>
</div>
<div id="mobileMenu" class="md:hidden bg-dark/95 absolute w-full top-full py-4 px-4 hidden">
<div class="flex flex-col space-y-4">
<a href="#community" class="hover:text-primary transition-colors py-2 text-white">社区</a>
</div>
</div>
</header>
<section id="community" class="min-h-screen pt-24 pb-16 bg-grid relative overflow-hidden flex items-center justify-center">
<div class="absolute inset-0 bg-gradient-to-b from-primary/10 to-dark pointer-events-none"></div>
<div class="absolute top-0 left-0 w-80 h-80 bg-primary/10 rounded-full blur-3xl"></div>
<div class="absolute bottom-0 right-0 w-80 h-80 bg-secondary/10 rounded-full blur-3xl"></div>
<div class="container mx-auto px-4 text-center relative z-10">
<div class="w-48 h-48 mx-auto mb-8 animate-float">
<img src="https://www.woofswap.finance/image/tokens/gdog.png" alt="GDOG Logo" class="w-full h-full object-cover rounded-full border-4 border-secondary/50 glow-border">
</div>
<h1 class="font-display text-5xl md:text-7xl mb-6 text-primary text-shadow-glow">Gatefunfun</h1>
<p class="text-xl md:text-2xl text-light-gray max-w-3xl mx-auto mb-10">
创建代币,参与认购,随时退款!加入Gatefunfun,在Gatefun上启动,满500 GT 100%!4亿令牌公平预售!
</p>
<div class="bg-dark/50 p-6 rounded-lg border border-primary/30 max-w-2xl mx-auto mb-8">
<div class="flex flex-col space-y-4">
<button id="connectWalletButton" class="px-6 py-3 bg-primary text-white rounded-full font-medium hover:bg-primary/80 transition-all">连接钱包</button>
<p id="networkStatus" class="text-light-gray text-sm">点击连接钱包...</p>
<div class="flex items-center bg-dark/80 p-3 rounded-lg border border-primary/20">
<i class="fa fa-link text-accent mr-3"></i>
<span class="font-mono text-sm text-white truncate">0x7e021071526F6B30703C330BFe6fFf948d2D8c61</span>
<button class="ml-3 text-light-gray hover:text-secondary transition-colors" onclick="copyContract()">
<i class="fa fa-copy"></i>
</button>
</div>
<div class="bg-dark/80 p-3 rounded-lg border border-primary/20">
<p id="balanceStatus" class="text-light-gray text-sm">GT余额: 0</p>
</div>
<div class="flex flex-col space-y-2">
<label class="block text-left text-light-gray mb-2">创建代币</label>
<input type="text" id="symbolInput" placeholder="代币符号(如 GDOG)" class="px-4 py-2 bg-dark/80 border border-primary/20 rounded-lg text-white focus:outline-none focus:border-secondary">
<input type="text" id="fullNameInput" placeholder="代币全称(如 GDOG Token)" class="px-4 py-2 bg-dark/80 border border-primary/20 rounded-lg text-white focus:outline-none focus:border-secondary">
<input type="text" id="telegramInput" placeholder="Telegram链接(https://t.me/username)" class="px-4 py-2 bg-dark/80 border border-primary/20 rounded-lg text-white focus:outline-none focus:border-secondary">
<button id="createButton" class="mt-2 px-6 py-3 bg-primary text-white rounded-full font-medium hover:bg-primary/80 transition-all disabled:bg-dark/50 disabled:cursor-not-allowed" disabled>创建代币</button>
</div>
<div class="flex flex-col space-y-2">
<label class="block text-left text-light-gray mb-2">认购代币</label>
<input type="text" id="depositTokenId" placeholder="输入代币编号" class="px-4 py-2 bg-dark/80 border border-primary/20 rounded-lg text-white focus:outline-none focus:border-secondary">
<input type="text" id="depositAmount" placeholder="认购金额(GT,0.1的倍数)" class="px-4 py-2 bg-dark/80 border border-primary/20 rounded-lg text-white focus:outline-none focus:border-secondary">
<p id="depositInfo" class="text-light-gray text-sm">代币信息:请先输入编号查询</p>
<button id="depositButton" class="mt-2 px-6 py-3 bg-primary text-white rounded-full font-medium hover:bg-primary/80 transition-all disabled:bg-dark/50 disabled:cursor-not-allowed" disabled>认购</button>
</div>
<div class="flex flex-col space-y-2">
<label class="block text-left text-light-gray mb-2">退款</label>
<input type="text" id="withdrawTokenId" placeholder="输入代币编号" class="px-4 py-2 bg-dark/80 border border-primary/20 rounded-lg text-white focus:outline-none focus:border-secondary">
<p id="withdrawInfo" class="text-light-gray text-sm">代币信息:请先输入编号查询</p>
<button id="withdrawButton" class="mt-2 px-6 py-3 bg-primary text-white rounded-full font-medium hover:bg-primary/80 transition-all disabled:bg-dark/50 disabled:cursor-not-allowed" disabled>退款</button>
</div>
<div class="flex flex-col space-y-2">
<label class="block text-left text-light-gray mb-2">我创建的代币</label>
<div id="creatorTokens" class="bg-dark/80 p-3 rounded-lg border border-primary/20 max-h-96 overflow-y-auto">
<p class="text-light-gray text-sm">暂无代币数据</p>
</div>
</div>
<div class="mt-4">
<img src="https://www.woofswap.finance/image/tokens/gdog.png" alt="GDOG Logo" class="w-16 h-16 mx-auto animate-float">
</div>
</div>
</div>
</div>
</section>
<footer class="bg-dark/95 py-12 border-t border-primary/20">
<div class="container mx-auto px-4 text-center">
<p class="text-light-gray text-sm">© 2025 GDOG社区。保留所有权利。请自行研究并谨慎投资。</p>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/web3@1.7.0/dist/web3.min.js"></script>
<script>
const CONTRACT_ADDRESS = '0x7e021071526F6B30703C330BFe6fFf948d2D8c61';
const contractAbi = [
{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},
{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},
{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"creator","type":"address"},{"indexed":false,"internalType":"string","name":"symbol","type":"string"},{"indexed":false,"internalType":"string","name":"fullName","type":"string"},{"indexed":false,"internalType":"string","name":"telegram","type":"string"}],"name":"TokenCreated","type":"event"},
{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Deposit","type":"event"},
{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"UserWithdrawal","type":"event"},
{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"OwnerWithdrawal","type":"event"},
{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalAmount","type":"uint256"}],"name":"TokenFull","type":"event"},
{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"TokenClosed","type":"event"},
{"inputs":[{"internalType":"string","name":"symbol","type":"string"},{"internalType":"string","name":"fullName","type":"string"},{"internalType":"string","name":"telegram","type":"string"}],"name":"createToken","outputs":[],"stateMutability":"nonpayable","type":"function"},
{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"deposit","outputs":[],"stateMutability":"payable","type":"function"},
{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"withdrawUser","outputs":[],"stateMutability":"nonpayable","type":"function"},
{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"withdrawOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},
{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getTokenInfo","outputs":[{"internalType":"string","name":"symbol","type":"string"},{"internalType":"string","name":"fullName","type":"string"},{"internalType":"string","name":"telegram","type":"string"},{"internalType":"address","name":"creator","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"enum TokenRegistry.Status","name":"status","type":"uint8"}],"stateMutability":"view","type":"function"},
{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getUserDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},
{"inputs":[{"internalType":"address","name":"creator","type":"address"}],"name":"getCreatorTokens","outputs":[{"internalType":"uint256[20]","name":"","type":"uint256[20]"}],"stateMutability":"view","type":"function"},
{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},
{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},
{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"tokenInfo","outputs":[{"internalType":"string","name":"symbol","type":"string"},{"internalType":"string","name":"fullName","type":"string"},{"internalType":"string","name":"telegram","type":"string"},{"internalType":"address","name":"creator","type":"address"}],"stateMutability":"view","type":"function"},
{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"tokenBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},
{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"userDeposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},
{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"tokenStatus","outputs":[{"internalType":"enum TokenRegistry.Status","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},
{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"creatorTokens","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},
{"inputs":[],"name":"tokenIdCounter","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}
];
const chains = {
GateLayer: {
chainId: 10088,
chainName: 'Gate Layer',
rpcUrl: 'https://gatelayer-mainnet.gatenode.cc',
blockExplorer: 'https://www.gatescan.org/gatelayer/',
nativeCurrency: { name: 'GT', symbol: 'GT', decimals: 18 }
}
};
let web3, account, contract;
async function waitForTransaction(txHash) {
let receipt = null;
const maxAttempts = 30;
let attempts = 0;
while (attempts < maxAttempts) {
receipt = await web3.eth.getTransactionReceipt(txHash);
if (receipt) {
if (receipt.status) return receipt;
throw new Error(`交易 ${txHash} 失败`);
}
await new Promise(resolve => setTimeout(resolve, 2000));
attempts++;
}
throw new Error(`交易 ${txHash} 未在 ${maxAttempts} 次尝试后确认`);
}
async function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function retryContractCall(fn, maxRetries = 12, delayMs = 3000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await Promise.race([
fn(),
new Promise((_, reject) => setTimeout(() => reject(new Error('查询超时')), 15000))
]);
} catch (error) {
console.error(`尝试 ${attempt}/${maxRetries} 失败: ${error.message}`);
if (attempt === maxRetries) throw error;
await delay(delayMs);
}
}
}
async function initializeWeb3() {
if (window.ethereum) {
web3 = new Web3(window.ethereum);
try {
await window.ethereum.request({ method: 'eth_requestAccounts' });
account = (await web3.eth.getAccounts())[0];
document.getElementById('connectWalletButton').innerText = `已连接: ${account.slice(0, 6)}...${account.slice(-4)}`;
await switchNetwork('GateLayer');
await initializeContracts();
await checkBalances();
await updateCreatorTokens();
document.getElementById('networkStatus').innerText = '已连接到Gate Layer (ID: 10088)';
} catch (error) {
document.getElementById('networkStatus').innerText = '钱包连接失败: ' + (error.message || '未知错误');
}
} else {
document.getElementById('networkStatus').innerText = '请安装MetaMask';
}
}
async function switchNetwork(chain) {
const chainConfig = chains[chain];
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: `0x${chainConfig.chainId.toString(16)}` }]
});
} catch (switchError) {
if (switchError.code === 4902) {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [{
chainId: `0x${chainConfig.chainId.toString(16)}`,
chainName: chainConfig.chainName,
rpcUrls: [chainConfig.rpcUrl],
nativeCurrency: chainConfig.nativeCurrency,
blockExplorerUrls: [chainConfig.blockExplorer]
}]
});
} else {
throw switchError;
}
}
}
async function initializeContracts() {
contract = new web3.eth.Contract(contractAbi, CONTRACT_ADDRESS);
}
async function checkBalances() {
if (!web3 || !account) {
document.getElementById('createButton').disabled = true;
document.getElementById('depositButton').disabled = true;
document.getElementById('withdrawButton').disabled = true;
document.getElementById('balanceStatus').innerHTML = 'GT余额: 0';
return;
}
try {
document.getElementById('networkStatus').innerText = '查询余额...';
const gtBalance = await retryContractCall(() => web3.eth.getBalance(account));
const gtBalanceFormatted = Number(web3.utils.fromWei(gtBalance, 'ether')).toFixed(4);
document.getElementById('balanceStatus').innerHTML = `GT余额: ${gtBalanceFormatted}`;
document.getElementById('networkStatus').innerText = '余额已更新';
} catch (error) {
document.getElementById('networkStatus').innerText = `查询失败: ${error.message || '未知错误'}`;
document.getElementById('createButton').disabled = true;
document.getElementById('depositButton').disabled = true;
document.getElementById('withdrawButton').disabled = true;
}
}
async function createToken() {
const symbol = document.getElementById('symbolInput').value;
const fullName = document.getElementById('fullNameInput').value;
const telegram = document.getElementById('telegramInput').value;
const status = document.getElementById('networkStatus');
const createButton = document.getElementById('createButton');
if (!web3 || !account) {
status.innerText = '请连接钱包';
return;
}
if (!symbol || !fullName) {
status.innerText = '请输入代币符号和全称';
return;
}
if (!telegram.match(/^https:\/\/t\.me\/[A-Za-z0-9_]+$/)) {
status.innerText = '请输入有效的Telegram链接(https://t.me/username)';
return;
}
try {
createButton.disabled = true;
createButton.innerHTML = '创建中... <i class="fa fa-spinner fa-spin ml-2"></i>';
status.innerText = '检查燃气费...';
const gasPrice = await web3.eth.getGasPrice();
const estimatedGas = await contract.methods.createToken(symbol, fullName, telegram).estimateGas({ from: account });
const nativeBalance = await web3.eth.getBalance(account);
const gasCost = web3.utils.toBN(gasPrice).mul(web3.utils.toBN(estimatedGas));
if (web3.utils.toBN(nativeBalance).lt(gasCost)) {
status.innerText = 'GT余额不足以支付燃气费';
return;
}
const tx = await contract.methods.createToken(symbol, fullName, telegram).send({
from: account,
gas: web3.utils.toHex(Math.min(estimatedGas * 2, 3000000))
});
await waitForTransaction(tx.transactionHash);
status.innerText = '代币创建成功!';
document.getElementById('symbolInput').value = '';
document.getElementById('fullNameInput').value = '';
document.getElementById('telegramInput').value = '';
await updateCreatorTokens();
} catch (error) {
status.innerText = error.code === 4001 ? '用户取消交易' : `创建失败: ${error.message}`;
console.error('Create Error:', error);
} finally {
createButton.disabled = false;
createButton.innerHTML = '创建代币';
}
}
async function queryTokenInfo(tokenId, elementId) {
const status = document.getElementById('networkStatus');
const infoElement = document.getElementById(elementId);
if (!web3 || !account) {
infoElement.innerText = '请连接钱包';
return null;
}
try {
const tokenInfo = await retryContractCall(() => contract.methods.getTokenInfo(tokenId).call());
const userDeposit = await retryContractCall(() => contract.methods.getUserDeposit(account, tokenId).call());
const progress = Number(web3.utils.fromWei(tokenInfo.balance, 'ether')).toFixed(1);
const userShare = Number(web3.utils.fromWei(userDeposit, 'ether')).toFixed(4);
const remaining = (500 - Number(progress)).toFixed(1);
const statusText = tokenInfo.status === '0' ? '活跃' : tokenInfo.status === '1' ? '已满' : '已关闭';
infoElement.innerHTML = `代币全称: ${tokenInfo.fullName}<br>符号: ${tokenInfo.symbol}<br>认购进度: ${progress}/500 GT<br>剩余可认购: ${remaining} GT<br>我的认购份额: ${userShare} GT<br>状态: ${statusText}`;
return { status: tokenInfo.status, remaining: remaining };
} catch (error) {
infoElement.innerText = `查询失败: ${error.message || '无效的代币编号'}`;
return null;
}
}
async function deposit() {
const tokenId = document.getElementById('depositTokenId').value;
const amount = document.getElementById('depositAmount').value;
const status = document.getElementById('networkStatus');
const depositButton = document.getElementById('depositButton');
if (!web3 || !account) {
status.innerText = '请连接钱包';
return;
}
if (!tokenId || isNaN(tokenId) || Number(tokenId) <= 0) {
status.innerText = '请输入有效的代币编号';
return;
}
if (!amount || isNaN(amount) || Number(amount) <= 0) {
status.innerText = '请输入有效的认购金额';
return;
}
try {
const amountWei = web3.utils.toWei(amount, 'ether');
const isMultiple = web3.utils.toBN(amountWei).mod(web3.utils.toBN('100000000000000000')).isZero();
if (!isMultiple) {
status.innerText = '请输入0.1 GT的倍数金额';
return;
}
depositButton.disabled = true;
depositButton.innerHTML = '认购中... <i class="fa fa-spinner fa-spin ml-2"></i>';
status.innerText = '检查燃气费和代币状态...';
const tokenInfo = await queryTokenInfo(tokenId, 'depositInfo');
if (!tokenInfo) {
status.innerText = '代币不存在';
return;
}
if (tokenInfo.status !== '0') {
status.innerText = '代币不可认购(非活跃状态)';
return;
}
const remaining = Number(tokenInfo.remaining);
if (Number(amount) > remaining) {
status.innerText = `认购金额超过剩余可认购量(${remaining} GT)`;
return;
}
const gasPrice = await web3.eth.getGasPrice();
const estimatedGas = await contract.methods.deposit(tokenId).estimateGas({ from: account, value: amountWei });
const nativeBalance = await web3.eth.getBalance(account);
const gasCost = web3.utils.toBN(gasPrice).mul(web3.utils.toBN(estimatedGas));
if (web3.utils.toBN(nativeBalance).lt(web3.utils.toBN(amountWei).add(gasCost))) {
status.innerText = 'GT余额不足以支付认购金额和燃气费';
return;
}
const tx = await contract.methods.deposit(tokenId).send({
from: account,
value: amountWei,
gas: web3.utils.toHex(Math.min(estimatedGas * 2, 3000000))
});
await waitForTransaction(tx.transactionHash);
status.innerText = `认购成功!金额: ${amount} GT`;
document.getElementById('depositAmount').value = '';
await queryTokenInfo(tokenId, 'depositInfo');
await checkBalances();
} catch (error) {
status.innerText = error.code === 4001 ? '用户取消交易' : `认购失败: ${error.message}`;
console.error('Deposit Error:', error);
} finally {
depositButton.disabled = false;
depositButton.innerHTML = '认购';
}
}
async function withdraw() {
const tokenId = document.getElementById('withdrawTokenId').value;
const status = document.getElementById('networkStatus');
const withdrawButton = document.getElementById('withdrawButton');
if (!web3 || !account) {
status.innerText = '请连接钱包';
return;
}
if (!tokenId || isNaN(tokenId) || Number(tokenId) <= 0) {
status.innerText = '请输入有效的代币编号';
return;
}
try {
withdrawButton.disabled = true;
withdrawButton.innerHTML = '退款中... <i class="fa fa-spinner fa-spin ml-2"></i>';
status.innerText = '检查燃气费和代币状态...';
const tokenInfo = await queryTokenInfo(tokenId, 'withdrawInfo');
if (!tokenInfo) {
status.innerText = '代币不存在';
return;
}
if (tokenInfo.status !== '0') {
status.innerText = '代币不可退款(非活跃状态)';
return;
}
const userDeposit = await retryContractCall(() => contract.methods.getUserDeposit(account, tokenId).call());
if (web3.utils.toBN(userDeposit).isZero()) {
status.innerText = '无认购金额可退款';
return;
}
const gasPrice = await web3.eth.getGasPrice();
const estimatedGas = await contract.methods.withdrawUser(tokenId).estimateGas({ from: account });
const nativeBalance = await web3.eth.getBalance(account);
const gasCost = web3.utils.toBN(gasPrice).mul(web3.utils.toBN(estimatedGas));
if (web3.utils.toBN(nativeBalance).lt(gasCost)) {
status.innerText = 'GT余额不足以支付燃气费';
return;
}
const tx = await contract.methods.withdrawUser(tokenId).send({
from: account,
gas: web3.utils.toHex(Math.min(estimatedGas * 2, 3000000))
});
await waitForTransaction(tx.transactionHash);
status.innerText = '退款成功!';
await queryTokenInfo(tokenId, 'withdrawInfo');
await checkBalances();
} catch (error) {
status.innerText = error.code === 4001 ? '用户取消交易' : `退款失败: ${error.message}`;
console.error('Withdraw Error:', error);
} finally {
withdrawButton.disabled = false;
withdrawButton.innerHTML = '退款';
}
}
async function updateCreatorTokens() {
const creatorTokensDiv = document.getElementById('creatorTokens');
if (!web3 || !account) {
creatorTokensDiv.innerHTML = '<p class="text-light-gray text-sm">请连接钱包</p>';
return;
}
try {
creatorTokensDiv.innerHTML = '<p class="text-light-gray text-sm">加载中...</p>';
const tokenIds = await retryContractCall(() => contract.methods.getCreatorTokens(account).call());
const validTokens = tokenIds.filter(id => id != 0);
if (validTokens.length === 0) {
creatorTokensDiv.innerHTML = '<p class="text-light-gray text-sm">暂无代币数据</p>';
return;
}
let html = '<table class="w-full text-sm token-table"><thead><tr><th>编号</th><th>符号</th><th>全称</th><th>Telegram</th><th>进度</th><th>状态</th></tr></thead><tbody>';
for (const id of validTokens) {
const tokenInfo = await retryContractCall(() => contract.methods.getTokenInfo(id).call());
const progress = Number(web3.utils.fromWei(tokenInfo.balance, 'ether')).toFixed(1);
const statusText = tokenInfo.status === '0' ? '活跃' : tokenInfo.status === '1' ? '已满' : '已关闭';
html += `<tr><td>${id}</td><td>${tokenInfo.symbol}</td><td>${tokenInfo.fullName}</td><td><a href="${tokenInfo.telegram}" target="_blank" class="text-primary hover:underline">${tokenInfo.telegram}</a></td><td>${progress}/500 GT</td><td>${statusText}</td></tr>`;
}
html += '</tbody></table>';
creatorTokensDiv.innerHTML = html;
} catch (error) {
creatorTokensDiv.innerHTML = `<p class="text-light-gray text-sm">查询失败: ${error.message || '未知错误'}</p>`;
console.error('Creator Tokens Error:', error);
}
}
function copyContract() {
navigator.clipboard.writeText(CONTRACT_ADDRESS).then(() => {
const notification = document.createElement('div');
notification.className = 'fixed bottom-4 right-4 bg-primary text-white px-4 py-2 rounded-lg shadow-lg z-50';
notification.textContent = '合约地址已复制!';
document.body.appendChild(notification);
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transition = 'opacity 0.3s';
setTimeout(() => {
document.body.removeChild(notification);
}, 300);
}, 2000);
});
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('connectWalletButton').addEventListener('click', initializeWeb3);
document.getElementById('createButton').addEventListener('click', createToken);
document.getElementById('depositButton').addEventListener('click', deposit);
document.getElementById('withdrawButton').addEventListener('click', withdraw);
document.getElementById('symbolInput').addEventListener('input', () => {
const symbol = document.getElementById('symbolInput').value;
const fullName = document.getElementById('fullNameInput').value;
const telegram = document.getElementById('telegramInput').value;
document.getElementById('createButton').disabled = !symbol || !fullName || !telegram.match(/^https:\/\/t\.me\/[A-Za-z0-9_]+$/);
});
document.getElementById('fullNameInput').addEventListener('input', () => {
const symbol = document.getElementById('symbolInput').value;
const fullName = document.getElementById('fullNameInput').value;
const telegram = document.getElementById('telegramInput').value;
document.getElementById('createButton').disabled = !symbol || !fullName || !telegram.match(/^https:\/\/t\.me\/[A-Za-z0-9_]+$/);
});
document.getElementById('telegramInput').addEventListener('input', () => {
const symbol = document.getElementById('symbolInput').value;
const fullName = document.getElementById('fullNameInput').value;
const telegram = document.getElementById('telegramInput').value;
document.getElementById('createButton').disabled = !symbol || !fullName || !telegram.match(/^https:\/\/t\.me\/[A-Za-z0-9_]+$/);
});
document.getElementById('depositTokenId').addEventListener('input', async () => {
const tokenId = document.getElementById('depositTokenId').value;
const amount = document.getElementById('depositAmount').value;
if (tokenId && !isNaN(tokenId) && Number(tokenId) > 0) {
await queryTokenInfo(tokenId, 'depositInfo');
} else {
document.getElementById('depositInfo').innerText = '代币信息:请先输入编号查询';
}
const amountWei = amount ? web3.utils.toWei(amount, 'ether') : '0';
const isMultiple = amount ? web3.utils.toBN(amountWei).mod(web3.utils.toBN('100000000000000000')).isZero() : false;
document.getElementById('depositButton').disabled = !tokenId || isNaN(tokenId) || Number(tokenId) <= 0 || !amount || isNaN(amount) || Number(amount) <= 0 || !isMultiple;
});
document.getElementById('depositAmount').addEventListener('input', () => {
const tokenId = document.getElementById('depositTokenId').value;
const amount = document.getElementById('depositAmount').value;
const amountWei = amount ? web3.utils.toWei(amount, 'ether') : '0';
const isMultiple = amount ? web3.utils.toBN(amountWei).mod(web3.utils.toBN('100000000000000000')).isZero() : false;
document.getElementById('depositButton').disabled = !tokenId || isNaN(tokenId) || Number(tokenId) <= 0 || !amount || isNaN(amount) || Number(amount) <= 0 || !isMultiple;
});
document.getElementById('withdrawTokenId').addEventListener('input', async () => {
const tokenId = document.getElementById('withdrawTokenId').value;
if (tokenId && !isNaN(tokenId) && Number(tokenId) > 0) {
await queryTokenInfo(tokenId, 'withdrawInfo');
} else {
document.getElementById('withdrawInfo').innerText = '代币信息:请先输入编号查询';
}
document.getElementById('withdrawButton').disabled = !tokenId || isNaN(tokenId) || Number(tokenId) <= 0;
});
const menuToggle = document.getElementById('menuToggle');
const mobileMenu = document.getElementById('mobileMenu');
menuToggle.addEventListener('click', () => {
mobileMenu.classList.toggle('hidden');
menuToggle.innerHTML = mobileMenu.classList.contains('hidden')
? '<i class="fa fa-bars"></i>'
: '<i class="fa fa-times"></i>';
});
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
mobileMenu.classList.add('hidden');
menuToggle.innerHTML = '<i class="fa fa-bars"></i>';
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
const navbar = document.getElementById('navbar');
window.addEventListener('scroll', () => {
if (window.scrollY > 50) {
navbar.classList.add('bg-dark/95', 'shadow-lg');
} else {
navbar.classList.remove('bg-dark/95', 'shadow-lg');
}
});
});
</script>
</body>
</html>