-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
1288 lines (1096 loc) · 45.7 KB
/
Copy pathscript.js
File metadata and controls
1288 lines (1096 loc) · 45.7 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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 全局变量
let priceChart = null;
let monitorInterval = null;
let currentTokenData = null;
let priceHistory = [];
let phantomWallet = null;
let walletConnected = false;
// const HOSTURL = "https://api.phantom.app"
// 这个地址可以替换为自己的API服务, js参考根目录下的worker.js
const HOSTURL = "https://voyeur.joejoejoe.cc"
// V2EX代币常量
const V2EX_TOKEN_MINT = "9raUVuzeWUk53co63M4WXLWPWE4Xc6Lpn7RS9dnkpump";
const TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
const ASSOCIATED_TOKEN_PROGRAM_ID = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
// 默认接收地址(可以修改)
const DEFAULT_RECIPIENT_ADDRESS = "v2ex_joejoejoe.sol";
// SOL常量
const LAMPORTS_PER_SOL = 1000000000;
// RPC节点列表(按优先级排序)
const RPC_NODES = [
"https://solana-rpc.publicnode.com",
];
// 选择最佳RPC节点的函数
async function selectBestRPC() {
for (const rpc of RPC_NODES) {
try {
const connection = new solanaWeb3.Connection(rpc, "recent");
// 测试连接
await connection.getEpochInfo();
console.log("选择RPC节点:", rpc);
return rpc;
} catch (error) {
console.log("RPC节点不可用:", rpc, error.message);
continue;
}
}
// 如果所有节点都不可用,则使用默认节点
console.log("所有RPC节点都不可用,使用默认节点");
return solanaWeb3.clusterApiUrl('mainnet-beta');
}
// DOM 元素
const elements = {
tokenAddress: document.getElementById('tokenAddress'),
searchBtn: document.getElementById('searchBtn'),
tokenInfo: document.getElementById('tokenInfo'),
currentPrice: document.getElementById('currentPrice'),
lastUpdated: document.getElementById('lastUpdated'),
priceChange24h: document.getElementById('priceChange24h'),
priceChart: document.getElementById('priceChart'),
timeRange: document.getElementById('timeRange'),
buyPrice: document.getElementById('buyPrice'),
sellPrice: document.getElementById('sellPrice'),
buyAmount: document.getElementById('buyAmount'), // 新增买入数量输入框
sellAmount: document.getElementById('sellAmount'), // 新增卖出数量输入框
monitorBuy: document.getElementById('monitorBuy'),
monitorSell: document.getElementById('monitorSell'),
autoTrade: document.getElementById('autoTrade'),
checkInterval: document.getElementById('checkInterval'),
startMonitor: document.getElementById('startMonitor'),
stopMonitor: document.getElementById('stopMonitor'),
monitorStatus: document.getElementById('monitorStatus'),
statusText: document.getElementById('statusText'),
lastCheckTime: document.getElementById('lastCheckTime'),
lastCheckPrice: document.getElementById('lastCheckPrice'),
recipientAddress: document.getElementById('recipientAddress'),
tipToken: document.getElementById('tipToken'),
tipAmount: document.getElementById('tipAmount'),
connectWallet: document.getElementById('connectWallet'),
sendTip: document.getElementById('sendTip'),
tipStatus: document.getElementById('tipStatus'),
tipMessage: document.getElementById('tipMessage'),
notifications: document.getElementById('notifications')
};
// 初始化
document.addEventListener('DOMContentLoaded', function () {
initializeEventListeners();
initializeChart();
});
// 事件监听器初始化
function initializeEventListeners() {
elements.searchBtn.addEventListener('click', searchToken);
elements.startMonitor.addEventListener('click', startMonitoring);
elements.stopMonitor.addEventListener('click', stopMonitoring);
elements.sendTip.addEventListener('click', sendTip);
elements.tipToken.addEventListener('change', updateTipAmount);
elements.connectWallet.addEventListener('click', connectPhantomWallet);
elements.timeRange.addEventListener('change', updateChartTimeRange);
elements.monitorBuy.addEventListener('change', validateMonitorSettings);
elements.monitorSell.addEventListener('change', validateMonitorSettings);
// 回车键搜索
elements.tokenAddress.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
searchToken();
}
});
// 检查Phantom钱包是否已安装
checkPhantomWallet();
}
// 更新打赏金额
function updateTipAmount() {
const selectedToken = elements.tipToken.value;
if (selectedToken === 'V2EX') {
elements.tipAmount.value = '10';
} else if (selectedToken === 'SOL') {
elements.tipAmount.value = '0.002';
}
}
// 初始化图表
function initializeChart() {
const ctx = elements.priceChart.getContext('2d');
priceChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: '价格 (USD)',
data: [],
borderColor: '#3498db',
backgroundColor: 'rgba(52, 152, 219, 0.1)',
borderWidth: 2,
fill: true,
tension: 0.4,
pointRadius: 0,
pointHoverRadius: 4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
label: function (context) {
return '价格: $' + context.parsed.y.toFixed(6).replace(/\.?0+$/, '');
}
}
}
},
scales: {
y: {
beginAtZero: false,
grid: {
color: 'rgba(0,0,0,0.1)'
},
ticks: {
callback: function (value) {
return '$' + value.toFixed(6).replace(/\.?0+$/, '');
}
}
},
x: {
grid: {
display: false
},
ticks: {
maxTicksLimit: 8,
maxRotation: 0
}
}
},
interaction: {
intersect: false,
mode: 'index'
}
}
});
}
// 搜索代币
async function searchToken() {
const tokenAddress = elements.tokenAddress.value.trim();
if (!tokenAddress) {
showNotification('请输入代币地址', 'error');
return;
}
try {
elements.searchBtn.innerHTML = '<span class="loading"></span> 查询中...';
elements.searchBtn.disabled = true;
// 模拟API调用 - 实际项目中需要替换为真实的Solana API
const tokenData = await fetchTokenData(tokenAddress);
if (tokenData) {
currentTokenData = tokenData;
displayTokenInfo(tokenData);
showNotification('代币信息获取成功', 'success');
} else {
showNotification('无法获取代币信息', 'error');
}
} catch (error) {
console.error('搜索代币错误:', error);
showNotification('搜索代币时发生错误', 'error');
} finally {
elements.searchBtn.innerHTML = '查询';
elements.searchBtn.disabled = false;
}
}
// 获取代币数据(真实API)
async function fetchTokenData(tokenAddress) {
console.log('正在查询代币:', tokenAddress);
// 使用Phantom价格API获取代币数据
let priceData = null;
try {
console.log('获取Phantom价格数据...');
const priceRes = await fetch(`${HOSTURL}/price/v1/solana:101/address/${tokenAddress}`, {
headers: {
'Accept': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
if (priceRes.ok) {
priceData = await priceRes.json();
console.log('Phantom价格API响应:', priceData);
}
} catch (e) {
console.error('Phantom价格API失败:', e);
}
// 如果价格API失败,返回null
if (!priceData || !priceData.price) {
console.log('Phantom价格API失败,无法获取代币数据');
return null;
}
// 获取历史价格数据
let historyData = null;
try {
console.log('获取历史价格数据...');
const historyRes = await fetch(`${HOSTURL}/price-history/v1?token=solana:101/address:${tokenAddress}&type=1H`, {
headers: {
'Accept': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
if (historyRes.ok) {
historyData = await historyRes.json();
console.log('Phantom历史价格API响应:', historyData);
}
} catch (e) {
console.error('Phantom历史价格API失败:', e);
}
const result = {
price: priceData.price,
priceChange24h: priceData.priceChange24h,
lastUpdatedAt: priceData.lastUpdatedAt,
address: tokenAddress,
historyData: historyData,
phantomData: {
token: {
price: priceData.price,
priceChange24h: priceData.priceChange24h,
lastUpdatedAt: priceData.lastUpdatedAt
}
}
};
console.log('返回代币数据:', result);
return result;
}
// 显示代币信息
function displayTokenInfo(tokenData) {
// 设置代币基本信息
if (tokenData.tokenInfo) {
// 设置代币名称和符号
document.getElementById('tokenName').textContent = tokenData.tokenInfo.name || 'Unknown Token';
document.getElementById('tokenSymbol').textContent = tokenData.tokenInfo.symbol || '---';
// 设置代币图标
const logoElement = document.getElementById('tokenLogo');
if (tokenData.tokenInfo.logoUri) {
logoElement.src = tokenData.tokenInfo.logoUri;
} else {
logoElement.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjQiIGhlaWdodD0iNjQiIHZpZXdCb3g9IjAgMCA2NCA2NCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iMzIiIGZpbGw9IiNGMEYwRjAiLz4KPHBhdGggZD0iTTQyIDI4TDM0IDIwTDMwIDE2TDI0IDE2TDE4IDIwTDEwIDI4TDEwIDM2TDE4IDQ0TDI0IDQ4TDI4IDUyTDM0IDQ4TDM4IDQ0TDQ2IDM2TDQ2IDI4TDQyIDI4Wk0zOCAzNkwzNCAzMkwyOCAzMkwzMiAzNkwzOCAzNloiIHN0cm9rZT0iIzM0OTg5YiIgc3Ryb2tlLXdpZHRoPSIyIi8+Cjwvc3ZnPgo=';
}
// 设置市值信息
if (tokenData.tokenInfo.marketCap) {
document.getElementById('marketCap').textContent = `$${(tokenData.tokenInfo.marketCap / 1000000).toFixed(2)}M`;
document.getElementById('marketCapContainer').style.display = 'flex';
} else {
document.getElementById('marketCapContainer').style.display = 'none';
}
// 设置24小时交易量
if (tokenData.tokenInfo.volume24hUsd) {
document.getElementById('volume24h').textContent = `$${(tokenData.tokenInfo.volume24hUsd / 1000000).toFixed(2)}M`;
document.getElementById('volume24hContainer').style.display = 'flex';
} else {
document.getElementById('volume24hContainer').style.display = 'none';
}
}
// 设置价格信息
elements.currentPrice.textContent = `$${tokenData.price.toFixed(6)}`;
// 价格变化
if (tokenData.priceChange24h !== undefined) {
const change = tokenData.priceChange24h;
const changeText = `${change >= 0 ? '+' : ''}${change.toFixed(2)}%`;
elements.priceChange24h.textContent = changeText;
elements.priceChange24h.className = `change-value ${change >= 0 ? 'price-up' : 'price-down'}`;
} else {
elements.priceChange24h.textContent = '-';
}
// 最后更新时间
if (tokenData.lastUpdatedAt) {
const lastUpdated = new Date(tokenData.lastUpdatedAt);
elements.lastUpdated.textContent = lastUpdated.toLocaleString('zh-CN');
} else {
elements.lastUpdated.textContent = '-';
}
// 显示代币信息模块
elements.tokenInfo.classList.remove('hidden');
// 初始化历史价格图表
if (tokenData.historyData && tokenData.historyData.history) {
initializeHistoryChart(tokenData.historyData.history);
}
}
// 获取代币数据
async function fetchTokenData(tokenAddress) {
console.log('正在查询代币:', tokenAddress);
// 获取代币基本信息
let tokenInfo = null;
try {
console.log('获取Phantom代币信息...');
const tokenRes = await fetch(`${HOSTURL}/search/v1?query=${tokenAddress}&chainIds=solana:101&platform=extension&pageSize=1&searchTypes=fungible&searchContext=explore`, {
headers: {
'Accept': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
if (tokenRes.ok) {
const tokenData = await tokenRes.json();
if (tokenData.results && tokenData.results.length > 0) {
tokenInfo = tokenData.results[0].data.data;
console.log('Phantom代币信息响应:', tokenInfo);
}
}
} catch (e) {
console.error('Phantom代币信息API失败:', e);
}
// 获取价格数据
let priceData = null;
try {
console.log('获取Phantom价格数据...');
const priceRes = await fetch(`${HOSTURL}/price/v1/solana:101/address/${tokenAddress}`, {
headers: {
'Accept': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
if (priceRes.ok) {
priceData = await priceRes.json();
console.log('Phantom价格API响应:', priceData);
}
} catch (e) {
console.error('Phantom价格API失败:', e);
}
// 如果价格API失败,返回null
if (!priceData || !priceData.price) {
console.log('Phantom价格API失败,无法获取代币数据');
return null;
}
// 获取历史价格数据
let historyData = null;
try {
console.log('获取历史价格数据...');
const historyRes = await fetch(`${HOSTURL}/price-history/v1?token=solana:101/address:${tokenAddress}&type=1H`, {
headers: {
'Accept': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
if (historyRes.ok) {
historyData = await historyRes.json();
console.log('Phantom历史价格API响应:', historyData);
}
} catch (e) {
console.error('Phantom历史价格API失败:', e);
}
const result = {
price: priceData.price,
priceChange24h: priceData.priceChange24h,
lastUpdatedAt: priceData.lastUpdatedAt,
address: tokenAddress,
historyData: historyData,
phantomData: {
token: {
price: priceData.price,
priceChange24h: priceData.priceChange24h,
lastUpdatedAt: priceData.lastUpdatedAt
}
},
tokenInfo: tokenInfo // 添加代币基本信息
};
console.log('返回代币数据:', result);
return result;
}
// 初始化历史价格图表
function initializeHistoryChart(historyData) {
// 清空现有数据
priceHistory = [];
// 转换历史数据格式
const labels = [];
const prices = [];
historyData.forEach(item => {
const date = new Date(item.unixTime * 1000);
const timeLabel = date.toLocaleDateString('zh-CN');
const price = parseFloat(item.value);
labels.push(timeLabel);
prices.push(price);
// 保存到历史记录中
priceHistory.push({
time: timeLabel,
price: price
});
});
// 更新图表
priceChart.data.labels = labels;
priceChart.data.datasets[0].data = prices;
priceChart.update('none');
console.log('历史价格图表初始化完成,数据点数量:', historyData.length);
}
// 更新图表时间范围
async function updateChartTimeRange() {
if (!currentTokenData || !currentTokenData.address) {
showNotification('请先查询代币信息', 'error');
return;
}
const timeRange = elements.timeRange.value;
console.log('更新图表时间范围:', timeRange);
try {
// 获取新的历史数据
const historyRes = await fetch(`${HOSTURL}/price-history/v1?token=solana:101/address:${currentTokenData.address}&type=${timeRange}`, {
headers: {
'Accept': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
if (historyRes.ok) {
const historyData = await historyRes.json();
console.log('新的历史数据响应:', historyData);
if (historyData && historyData.history) {
// 清空现有数据
priceHistory = [];
// 转换历史数据格式
const labels = [];
const prices = [];
historyData.history.forEach(item => {
const date = new Date(item.unixTime * 1000);
let timeLabel;
// 根据时间范围格式化标签
if (timeRange === '1H') {
timeLabel = date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
} else if (timeRange === '1D') {
timeLabel = date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
} else {
timeLabel = date.toLocaleDateString('zh-CN');
}
const price = parseFloat(item.value);
labels.push(timeLabel);
prices.push(price);
// 保存到历史记录中
priceHistory.push({
time: timeLabel,
price: price
});
});
// 更新图表
priceChart.data.labels = labels;
priceChart.data.datasets[0].data = prices;
priceChart.update('none');
console.log('图表时间范围更新完成,数据点数量:', historyData.history.length);
showNotification('图表时间范围更新成功', 'success');
}
} else {
throw new Error(`历史数据请求失败: ${historyRes.status}`);
}
} catch (e) {
console.error('更新图表时间范围失败:', e);
showNotification('更新图表时间范围失败', 'error');
}
}
// 更新图表
function updateChart(price) {
const now = new Date();
const timeLabel = now.toLocaleTimeString();
priceHistory.push({
time: timeLabel,
price: price
});
// 保持最近50个数据点
if (priceHistory.length > 50) {
priceHistory.shift();
}
const labels = priceHistory.map(item => item.time);
const prices = priceHistory.map(item => item.price);
priceChart.data.labels = labels;
priceChart.data.datasets[0].data = prices;
priceChart.update('none');
}
// 验证监控设置
function validateMonitorSettings() {
const monitorBuy = elements.monitorBuy.checked;
const monitorSell = elements.monitorSell.checked;
// 必须至少选择一种监控类型
if (!monitorBuy && !monitorSell) {
showNotification('请至少选择一种监控类型', 'error');
// 自动选中买入监控
elements.monitorBuy.checked = true;
return false;
}
return true;
}
// 开始监控
async function startMonitoring() {
const buyPrice = parseFloat(elements.buyPrice.value);
const sellPrice = parseFloat(elements.sellPrice.value);
const interval = parseInt(elements.checkInterval.value);
const monitorBuy = elements.monitorBuy.checked;
const monitorSell = elements.monitorSell.checked;
const autoTrade = elements.autoTrade.checked;
// 只有在选中自动交易时才要求连接钱包
if (autoTrade && !walletConnected) {
showNotification('自动交易需要先连接Phantom钱包', 'error');
return;
}
if (!currentTokenData) {
showNotification('请先查询代币信息', 'error');
return;
}
// 验证监控设置
if (!validateMonitorSettings()) {
return;
}
// 检查是否填写了必要的价格
if (monitorBuy && !buyPrice) {
showNotification('请填写买入价格', 'error');
return;
}
if (monitorSell && !sellPrice) {
showNotification('请填写卖出价格', 'error');
return;
}
if (!interval) {
showNotification('请填写检查频率', 'error');
return;
}
// 如果同时监控买入和卖出,检查价格关系
if (monitorBuy && monitorSell && buyPrice >= sellPrice) {
showNotification('买入价格必须低于卖出价格', 'error');
return;
}
if (interval < 1) {
showNotification('检查频率不能少于2秒', 'error');
return;
}
// 请求浏览器通知权限(如果不自动交易)
if (!autoTrade) {
const notificationGranted = await requestNotificationPermission();
if (!notificationGranted) {
showNotification('需要通知权限来发送交易提醒', 'warning');
}
}
// 开始监控
monitorInterval = setInterval(() => {
checkPrice();
}, interval * 1000);
elements.startMonitor.classList.add('hidden');
elements.stopMonitor.classList.remove('hidden');
elements.monitorStatus.classList.remove('hidden');
elements.statusText.textContent = '监控中...';
showNotification('价格监控已启动', 'success');
}
// 停止监控
function stopMonitoring() {
if (monitorInterval) {
clearInterval(monitorInterval);
monitorInterval = null;
}
elements.startMonitor.classList.remove('hidden');
elements.stopMonitor.classList.add('hidden');
elements.monitorStatus.classList.add('hidden');
showNotification('价格监控已停止', 'success');
}
// 检查价格
async function checkPrice() {
if (!currentTokenData) return;
// 获取最新价格
let newPrice = currentTokenData.price;
let priceUpdated = false;
try {
// 使用Phantom价格API获取最新价格
if (currentTokenData.address) {
const phantomRes = await fetch(`${HOSTURL}/price/v1/solana:101/address/${currentTokenData.address}`, {
headers: {
'Accept': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
if (phantomRes.ok) {
const phantomData = await phantomRes.json();
if (phantomData && phantomData.price) {
newPrice = phantomData.price;
currentTokenData.price = newPrice;
priceUpdated = true;
console.log('从Phantom获取最新价格:', newPrice);
}
}
}
} catch (e) {
console.error('获取最新价格失败:', e);
}
// 如果Phantom API失败,停止监控
if (!priceUpdated) {
console.log('Phantom API失败,停止价格监控');
stopMonitoring();
showNotification('无法获取最新价格,监控已停止', 'error');
return;
}
// 更新显示
elements.currentPrice.textContent = `$${newPrice.toFixed(6)}`;
updateChart(newPrice);
// 更新最后检查时间和价格
const now = new Date();
elements.lastCheckTime.textContent = now.toLocaleTimeString();
elements.lastCheckPrice.textContent = `$${newPrice.toFixed(6)}`;
elements.lastUpdated.textContent = now.toLocaleString('zh-CN');
// 检查交易信号
const monitorBuy = elements.monitorBuy.checked;
const monitorSell = elements.monitorSell.checked;
const autoTrade = elements.autoTrade.checked;
const buyPrice = parseFloat(elements.buyPrice.value);
const sellPrice = parseFloat(elements.sellPrice.value);
if (monitorBuy && buyPrice && newPrice <= buyPrice) {
const message = `买入信号!当前价格 $${newPrice.toFixed(6)} 低于买入价格 $${buyPrice}`;
showNotification(message, 'success');
if (autoTrade) {
// 触发信号后停止监控
stopMonitoring();
// 自动买入逻辑
try {
showNotification('执行自动买入...', 'info');
await executeBuy(newPrice, buyPrice);
showNotification('自动买入执行完成', 'success');
} catch (error) {
console.error('自动买入失败:', error);
showNotification(`自动买入失败: ${error.message}`, 'error');
}
}
sendBrowserNotification(
'买入信号提醒',
message,
'/favicon.ico'
);
}
if (monitorSell && sellPrice && newPrice >= sellPrice) {
const message = `卖出信号!当前价格 $${newPrice.toFixed(6)} 高于卖出价格 $${sellPrice}`;
showNotification(message, 'success');
if (autoTrade) {
// 触发信号后停止监控
stopMonitoring();
// 自动卖出逻辑
try {
showNotification('执行自动卖出...', 'info');
await executeSell(newPrice, sellPrice);
showNotification('自动卖出执行完成', 'success');
} catch (error) {
console.error('自动卖出失败:', error);
showNotification(`自动卖出失败: ${error.message}`, 'error');
}
}
sendBrowserNotification(
'卖出信号提醒',
message,
'/favicon.ico'
);
}
}
// 自动买入功能
async function executeBuy(currentPrice, targetPrice) {
if (!walletConnected || !phantomWallet) {
throw new Error('钱包未连接');
}
try {
// 获取用户设置的买入数量
const buyAmount = parseFloat(elements.buyAmount.value) || 0.01; // 默认买入0.01 SOL worth的代币
// 使用Jupiter API获取交易报价
const quoteResponse = await fetch(`https://quote-api.jup.ag/v6/quote?inputMint=So11111111111111111111111111111111111111112&outputMint=${currentTokenData.address}&amount=${buyAmount * LAMPORTS_PER_SOL}&slippageBps=50`);
if (!quoteResponse.ok) {
throw new Error('无法获取交易报价');
}
const quote = await quoteResponse.json();
// 获取交易数据
const swapResponse = await fetch('https://quote-api.jup.ag/v6/swap', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
quoteResponse: quote,
userPublicKey: phantomWallet.publicKey.toString(),
wrapAndUnwrapSol: true
})
});
if (!swapResponse.ok) {
throw new Error('无法创建交易');
}
const swapData = await swapResponse.json();
// 使用Phantom钱包签名并发送交易
// 修复:正确处理VersionedTransaction数据
const transactionBuf = Uint8Array.from(atob(swapData.swapTransaction), c => c.charCodeAt(0));
const transaction = solanaWeb3.VersionedTransaction.deserialize(transactionBuf);
const signed = await phantomWallet.signTransaction(transaction);
const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('mainnet-beta'));
const signature = await connection.sendRawTransaction(signed.serialize());
// 等待交易确认
await connection.confirmTransaction(signature);
showNotification(`买入交易成功,交易签名: ${signature.slice(0, 8)}...`, 'success');
} catch (error) {
console.error('买入执行失败:', error);
throw new Error(`买入失败: ${error.message}`);
}
}
// 自动卖出功能
async function executeSell(currentPrice, targetPrice) {
if (!walletConnected || !phantomWallet) {
throw new Error('钱包未连接');
}
try {
// 获取用户设置的卖出数量
const sellAmount = parseFloat(elements.sellAmount.value) || 100; // 默认卖出100个代币
// 使用Jupiter API获取交易报价
const quoteResponse = await fetch(`https://quote-api.jup.ag/v6/quote?inputMint=${currentTokenData.address}&outputMint=So11111111111111111111111111111111111111112&amount=${sellAmount * 1000000}&slippageBps=50`);
if (!quoteResponse.ok) {
throw new Error('无法获取交易报价');
}
const quote = await quoteResponse.json();
// 获取交易数据
const swapResponse = await fetch('https://quote-api.jup.ag/v6/swap', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
quoteResponse: quote,
userPublicKey: phantomWallet.publicKey.toString(),
wrapAndUnwrapSol: true
})
});
if (!swapResponse.ok) {
throw new Error('无法创建交易');
}
const swapData = await swapResponse.json();
// 使用Phantom钱包签名并发送交易
// 修复:正确处理VersionedTransaction数据
const transactionBuf = Uint8Array.from(atob(swapData.swapTransaction), c => c.charCodeAt(0));
const transaction = solanaWeb3.VersionedTransaction.deserialize(transactionBuf);
const signed = await phantomWallet.signTransaction(transaction);
const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('mainnet-beta'));
const signature = await connection.sendRawTransaction(signed.serialize());
// 等待交易确认
await connection.confirmTransaction(signature);
showNotification(`卖出交易成功,交易签名: ${signature.slice(0, 8)}...`, 'success');
} catch (error) {
console.error('卖出执行失败:', error);
throw new Error(`卖出失败: ${error.message}`);
}
}
// 检查Phantom钱包是否已安装
function checkPhantomWallet() {
if (typeof window.solana !== 'undefined' && window.solana.isPhantom) {
phantomWallet = window.solana;
console.log('Phantom钱包已检测到');
// 检查是否已连接
if (phantomWallet.isConnected) {
walletConnected = true;
updateWalletStatus();
}
} else {
console.log('Phantom钱包未安装');
showNotification('请先安装Phantom钱包扩展', 'error');
}
}
// 连接Phantom钱包
async function connectPhantomWallet() {
try {
if (!phantomWallet) {
showNotification('请先安装Phantom钱包扩展', 'error');
return;
}
elements.connectWallet.innerHTML = '<span class="loading"></span> 连接中...';
elements.connectWallet.disabled = true;
// 连接钱包
const response = await phantomWallet.connect();
console.log('钱包连接成功:', response.publicKey.toString());
walletConnected = true;
updateWalletStatus();
showNotification('Phantom钱包连接成功!', 'success');
} catch (error) {
console.error('钱包连接失败:', error);
showNotification('钱包连接失败: ' + error.message, 'error');
// 连接失败时重置按钮状态
elements.connectWallet.innerHTML = '连接Phantom钱包';
elements.connectWallet.disabled = false;
elements.connectWallet.classList.add('btn-wallet-connect');
elements.connectWallet.classList.remove('btn-secondary');
}
}
// 更新钱包状态显示
function updateWalletStatus() {
if (walletConnected) {
elements.sendTip.disabled = false;
elements.connectWallet.innerHTML = '已连接';
elements.connectWallet.disabled = true;
elements.connectWallet.classList.add('btn-success');
elements.connectWallet.classList.remove('btn-secondary', 'btn-wallet-connect');
} else {
elements.sendTip.disabled = true;
elements.connectWallet.innerHTML = '连接Phantom钱包';
elements.connectWallet.disabled = false;
elements.connectWallet.classList.remove('btn-success');
elements.connectWallet.classList.add('btn-wallet-connect');
elements.connectWallet.classList.remove('btn-secondary');
}
}
/// 发送打赏
async function sendTip() {
if (!walletConnected) {
showNotification('请先连接Phantom钱包', 'error');
return;
}
let recipientAddress = elements.recipientAddress.value.trim();
const tipAmount = parseFloat(elements.tipAmount.value);
const tipToken = elements.tipToken.value;
if (!recipientAddress) {
showNotification('请输入接收地址', 'error');
return;
}
if (!tipAmount || tipAmount <= 0) {
showNotification('请输入有效的打赏数量', 'error');
return;
}
try {
// 解析.sol域名(如果需要)
recipientAddress = await resolveSolDomain(recipientAddress);
// 验证Solana地址格式
if (!isValidSolanaAddress(recipientAddress)) {
showNotification('请输入有效的Solana地址', 'error');
return;
}
elements.sendTip.innerHTML = '<span class="loading"></span> 发送中...';
elements.sendTip.disabled = true;
let signature;
if (tipToken === 'SOL') {
// 发送SOL
try {
// 选择最佳RPC节点
const rpcUrl = await selectBestRPC();
console.log("使用RPC节点:", rpcUrl);
// 创建连接到Solana网络
const connection = new solanaWeb3.Connection(rpcUrl);