-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1257 lines (1138 loc) · 43.1 KB
/
Copy pathserver.js
File metadata and controls
1257 lines (1138 loc) · 43.1 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
/**
* NeverGuard - shMonad Exchange Rate Server
* 从 Monad 链上获取 shMonad 实时汇率
* 集成 CoinGecko API 获取主流 Token 价格
* DeFi 策略收益预估系统
*/
const express = require('express');
const { ethers } = require('ethers');
const cors = require('cors');
const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.json());
app.use(express.static(__dirname));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// ==================== CoinGecko API 配置 ====================
const COINGECKO_API_BASE = 'https://api.coingecko.com/api/v3';
// Clash 代理配置
const PROXY_URL = process.env.HTTPS_PROXY || process.env.https_proxy || 'http://127.0.0.1:7890';
const httpsAgent = new HttpsProxyAgent(PROXY_URL);
// 创建 axios 实例用于 CoinGecko API
const coingeckoApi = axios.create({
httpsAgent,
timeout: 15000,
headers: {
'User-Agent': 'NeverGuard/1.0'
}
});
// ==================== Token 配置 ====================
// 加载 tokens.json 配置
let tokensConfig = { tokens: {}, strategies: [] };
try {
const configPath = path.join(__dirname, 'tokens.json');
const configData = fs.readFileSync(configPath, 'utf8');
tokensConfig = JSON.parse(configData);
console.log(`✅ 已加载 Token 配置: ${Object.keys(tokensConfig.tokens).length} 个分类`);
} catch (error) {
console.warn(`⚠️ 无法加载 tokens.json: ${error.message}`);
}
/**
* 获取所有 Token 列表(扁平化)
*/
function getAllTokens() {
const tokens = [];
for (const [categoryKey, categoryData] of Object.entries(tokensConfig.tokens)) {
for (const token of categoryData.tokens) {
tokens.push({
...token,
category: categoryKey,
categoryDesc: categoryData.description
});
}
}
return tokens;
}
// 价格缓存 (避免频繁调用 API)
const priceCache = {
store: new Map(),
ttl: 30000 // 30秒缓存
};
/**
* 从 CoinGecko 获取 Token 价格
* @param {string} ids - Coin IDs, 逗号分隔, 如 'bitcoin,ethereum,monad'
* @param {string} vsCurrencies - 计价货币, 默认 'usd'
*/
async function getCoinGeckoPrice(ids = 'bitcoin,ethereum,monad,tether,usd-coin', vsCurrencies = 'usd') {
const cacheKey = `${ids}|${vsCurrencies}`;
try {
// 检查缓存
const now = Date.now();
const cached = priceCache.store.get(cacheKey);
if (cached && (now - cached.timestamp) < priceCache.ttl) {
console.log('📦 使用缓存的价格数据');
return { success: true, data: cached.data, cached: true };
}
const response = await coingeckoApi.get(`${COINGECKO_API_BASE}/simple/price`, {
params: {
ids,
vs_currencies: vsCurrencies,
include_market_cap: true,
include_24hr_vol: true,
include_24hr_change: true
}
});
// 更新缓存
priceCache.store.set(cacheKey, {
data: response.data,
timestamp: now
});
return { success: true, data: response.data, cached: false };
} catch (error) {
console.error(`❌ CoinGecko API 错误: ${error.message}`);
// 如果有缓存,即使过期也返回
const stale = priceCache.store.get(cacheKey);
if (stale?.data) {
console.log('📦 使用过期的缓存数据');
return { success: true, data: stale.data, cached: true, error: error.message };
}
return { success: false, error: error.message };
}
}
/**
* 获取 BTC/ETH 价格 (最常用)
*/
async function getBtcEthPrice() {
const result = await getCoinGeckoPrice('bitcoin,ethereum', 'usd');
if (result.success && result.data) {
return {
btc: {
usd: result.data.bitcoin?.usd || 0,
cny: result.data.bitcoin?.cny || 0,
change24h: result.data.bitcoin?.usd_24h_change || 0,
marketCap: result.data.bitcoin?.usd_market_cap || 0
},
eth: {
usd: result.data.ethereum?.usd || 0,
cny: result.data.ethereum?.cny || 0,
change24h: result.data.ethereum?.usd_24h_change || 0,
marketCap: result.data.ethereum?.usd_market_cap || 0
}
};
}
return null;
}
/**
* 从 CoinGecko 获取 markets 数据(包含 icon)
* @param {string[]} idsList - CoinGecko ids
* @param {string} vsCurrency - 计价货币
*/
async function getCoinGeckoMarkets(idsList = ['bitcoin', 'monad'], vsCurrency = 'usd') {
try {
const response = await coingeckoApi.get(`${COINGECKO_API_BASE}/coins/markets`, {
params: {
vs_currency: vsCurrency,
ids: idsList.join(','),
sparkline: false
}
});
return { success: true, data: response.data || [] };
} catch (error) {
console.error(`❌ CoinGecko markets API 错误: ${error.message}`);
return { success: false, error: error.message };
}
}
function withTimeout(promise, ms, fallbackValue) {
return Promise.race([
promise,
new Promise((resolve) => setTimeout(() => resolve(fallbackValue), ms))
]);
}
/**
* 从 DexScreener 通过代币合约地址获取价格
* @param {string} tokenAddress - 代币合约地址
*/
async function getDexScreenerPriceByTokenAddress(tokenAddress) {
try {
const normalizedAddress = tokenAddress.toLowerCase();
const response = await axios.get(`https://api.dexscreener.com/latest/dex/tokens/${normalizedAddress}`, {
httpsAgent,
timeout: 15000,
headers: {
'User-Agent': 'NeverGuard/1.0'
}
});
const pairs = response?.data?.pairs || [];
const matchedPairs = pairs.filter((pair) =>
pair?.baseToken?.address?.toLowerCase() === normalizedAddress ||
pair?.quoteToken?.address?.toLowerCase() === normalizedAddress
);
const target = matchedPairs.sort((a, b) => (b?.liquidity?.usd || 0) - (a?.liquidity?.usd || 0))[0];
if (!target) {
return { success: false, error: `No DexScreener pair found for token ${normalizedAddress}` };
}
const baseIsTarget = target?.baseToken?.address?.toLowerCase() === normalizedAddress;
const targetSymbol = baseIsTarget ? target?.baseToken?.symbol : target?.quoteToken?.symbol;
const targetName = baseIsTarget ? target?.baseToken?.name : target?.quoteToken?.name;
return {
success: true,
data: {
address: normalizedAddress,
symbol: targetSymbol || null,
name: targetName || null,
price: target?.priceUsd ? Number(target.priceUsd) : null,
change24h: target?.priceChange?.h24 ?? null,
marketCap: target?.marketCap || target?.fdv || null,
volume24h: target?.volume?.h24 || null,
liquidity: target?.liquidity?.usd || null,
pairAddress: target?.pairAddress || null,
chainId: target?.chainId || null,
dexId: target?.dexId || null,
iconUrl:
target?.info?.imageUrl ||
target?.baseToken?.icon ||
target?.quoteToken?.icon ||
null
}
};
} catch (error) {
console.error(`❌ DexScreener API 错误 (${tokenAddress}): ${error.message}`);
return { success: false, error: error.message };
}
}
// ==================== 配置 ====================
// Monad RPC 节点
const MONAD_RPC = "https://rpc.monad.xyz";
// shMonad 合约地址
const SHMONAD_ADDRESS = "0x1b68626dca36c7fe922fd2d55e4f631d962de19c";
const DUST_TOKEN_ADDRESS = "0xad96c3dffcd6374294e2573a7fbba96097cc8d7c";
const NSHMON_ADDRESS = "0x38648958836eA88b368b4ac23b86Ad44B0fe7508";
const NEVERLAND_POOL_ADDRESSES_PROVIDER = "0x49D75170F55C964dfdd6726c74fdEDEe75553A0f";
const NEVERLAND_UI_POOL_DATA_PROVIDER = "0x0733e79171dd5A5E8aF41E387c6299bCfE6a7e55";
const NEVERLAND_REWARDS_CONTROLLER = "0x57ea245cCbFAb074baBb9d01d1F0c60525E52cec";
const SHMON_ICON_URL = "https://shmonad.xyz/favicon.ico";
const BTC_ICON_URL = "https://coin-images.coingecko.com/coins/images/1/large/bitcoin.png?1696501400";
const MON_ICON_URL = "https://coin-images.coingecko.com/coins/images/38927/large/mon.png?1766029057";
const featuredPriceCache = {
data: null,
timestamp: 0,
ttl: 30000
};
const exchangeRateLastKnown = {
rate: '1.0',
method: 'default',
timestamp: 0
};
const neverlandSupplyApyCache = {
data: null,
timestamp: 0,
ttl: 30000
};
// shMonad 合约 ABI (极简版,只包含需要的函数)
const SHMONAD_ABI = [
// ERC-4626 标准函数
"function totalAssets() external view returns (uint256)",
"function totalSupply() external view returns (uint256)",
"function convertToAssets(uint256 shares) external view returns (uint256)",
"function convertToShares(uint256 assets) external view returns (uint256)",
// 自定义函数
"function getExchangeRate() external view returns (uint256)",
// ERC20 函数
"function name() external view returns (string)",
"function symbol() external view returns (string)",
"function decimals() external view returns (uint8)"
];
const ERC20_METADATA_ABI = [
"function totalSupply() external view returns (uint256)",
"function decimals() external view returns (uint8)"
];
const NEVERLAND_REWARDS_CONTROLLER_ABI = [
"function getRewardsData(address asset, address reward) external view returns (uint256,uint256,uint256,uint256)"
];
const NEVERLAND_UI_POOL_DATA_PROVIDER_ABI = [
"function getReservesData(address provider) external view returns ((address underlyingAsset,string name,string symbol,uint256 decimals,uint256 baseLTVasCollateral,uint256 reserveLiquidationThreshold,uint256 reserveLiquidationBonus,uint256 reserveFactor,bool usageAsCollateralEnabled,bool borrowingEnabled,bool stableBorrowRateEnabled,bool isActive,bool isFrozen,uint128 liquidityIndex,uint128 variableBorrowIndex,uint128 liquidityRate,uint128 variableBorrowRate,uint128 stableBorrowRate,uint40 lastUpdateTimestamp,address aTokenAddress,address stableDebtTokenAddress,address variableDebtTokenAddress,address interestRateStrategyAddress,uint256 availableLiquidity,uint256 totalPrincipalStableDebt,uint256 averageStableRate,uint256 stableDebtLastUpdateTimestamp,uint256 totalScaledVariableDebt,uint256 priceInMarketReferenceCurrency,address priceOracle,uint256 variableRateSlope1,uint256 variableRateSlope2,uint256 stableRateSlope1,uint256 stableRateSlope2,uint256 baseStableBorrowRate,uint256 baseVariableBorrowRate,uint256 optimalUsageRatio,bool isPaused,bool isSiloedBorrowing,uint128 accruedToTreasury,uint128 unbacked,uint128 isolationModeTotalDebt)[],(uint256,uint256,int256,int256,uint8))"
];
// ==================== 初始化 ====================
let provider;
let shmonadContract;
let neverlandRewardsContract;
let neverlandUiPoolDataProvider;
let nshmonContract;
function initContract() {
try {
provider = new ethers.JsonRpcProvider(MONAD_RPC);
shmonadContract = new ethers.Contract(SHMONAD_ADDRESS, SHMONAD_ABI, provider);
neverlandRewardsContract = new ethers.Contract(
NEVERLAND_REWARDS_CONTROLLER,
NEVERLAND_REWARDS_CONTROLLER_ABI,
provider
);
neverlandUiPoolDataProvider = new ethers.Contract(
NEVERLAND_UI_POOL_DATA_PROVIDER,
NEVERLAND_UI_POOL_DATA_PROVIDER_ABI,
provider
);
nshmonContract = new ethers.Contract(NSHMON_ADDRESS, ERC20_METADATA_ABI, provider);
console.log(`✅ Connected to Monad RPC: ${MONAD_RPC}`);
console.log(`✅ shMonad Contract: ${SHMONAD_ADDRESS}`);
return true;
} catch (error) {
console.error(`❌ Failed to initialize contract:`, error.message);
return false;
}
}
// ==================== 核心函数 ====================
/**
* 获取实时汇率 (1 shMON = ? MON)
* 优先级: getExchangeRate() > convertToAssets(1e18) > totalAssets/totalSupply
*/
async function getExchangeRate() {
try {
// 方法 1: 尝试调用 getExchangeRate()
try {
const rate = await shmonadContract.getExchangeRate();
const rateFormatted = ethers.formatUnits(rate, 18);
console.log(`📊 Method 1 - getExchangeRate(): ${rateFormatted}`);
return {
rate: rateFormatted,
method: 'getExchangeRate',
timestamp: Date.now()
};
} catch (e) {
console.log(`⚠️ getExchangeRate() not available: ${e.message.substring(0, 50)}...`);
}
// 方法 2: 使用 convertToAssets(1 shMON)
try {
const oneShare = ethers.parseUnits("1", 18);
const assets = await shmonadContract.convertToAssets(oneShare);
const rateFormatted = ethers.formatUnits(assets, 18);
console.log(`📊 Method 2 - convertToAssets(1): ${rateFormatted}`);
return {
rate: rateFormatted,
method: 'convertToAssets',
timestamp: Date.now()
};
} catch (e) {
console.log(`⚠️ convertToAssets() not available: ${e.message.substring(0, 50)}...`);
}
// 方法 3: 计算 totalAssets / totalSupply
try {
const [totalAssets, totalSupply] = await Promise.all([
shmonadContract.totalAssets(),
shmonadContract.totalSupply()
]);
const assetsBigInt = BigInt(totalAssets);
const supplyBigInt = BigInt(totalSupply);
if (supplyBigInt > 0n) {
// 计算汇率: totalAssets / totalSupply * 1e18
const rate = (assetsBigInt * 1000000000000000000n) / supplyBigInt;
const rateFormatted = Number(rate) / 1e18;
console.log(`📊 Method 3 - totalAssets/totalSupply: ${rateFormatted}`);
return {
rate: rateFormatted.toString(),
method: 'totalAssets_div_totalSupply',
timestamp: Date.now()
};
}
} catch (e) {
console.log(`⚠️ totalAssets/totalSupply failed: ${e.message.substring(0, 50)}...`);
}
// 所有方法都失败,返回默认值
console.warn(`⚠️ All methods failed, returning default rate`);
return {
rate: "1.0",
method: 'default',
timestamp: Date.now()
};
} catch (error) {
console.error(`❌ Error getting exchange rate:`, error.message);
return {
rate: "1.0",
method: 'error',
error: error.message,
timestamp: Date.now()
};
}
}
/**
* 获取质押率 (1 MON = ? shMON)
* 这是 getExchangeRate() 的倒数
*/
async function getStakingRate() {
const data = await getExchangeRate();
const rate = parseFloat(data.rate);
const stakingRate = rate > 0 ? (1 / rate) : 1.0;
return {
rate: stakingRate.toString(),
method: data.method + '_inverted',
timestamp: data.timestamp
};
}
const STRATEGY_PROFILES = {
no_leverage: {
id: 'no_leverage',
name: 'No Leverage',
leverage: 1.0,
borrowApy: 0,
riskReserveBps: 0,
risk: 'low'
},
leverage_1_5x: {
id: 'leverage_1_5x',
name: 'Leverage 1.5x',
leverage: 1.5,
borrowApy: 8.0,
riskReserveBps: 40,
risk: 'medium'
},
leverage_1_8x: {
id: 'leverage_1_8x',
name: 'Leverage 1.8x',
leverage: 1.8,
borrowApy: 11.0,
riskReserveBps: 80,
risk: 'high'
}
};
function safeNumber(value, fallback = 0) {
const parsed = Number(value);
if (!Number.isFinite(parsed)) return fallback;
return parsed;
}
function clampNumber(value, min, max) {
return Math.min(Math.max(value, min), max);
}
function round(value, decimals = 6) {
const factor = 10 ** decimals;
return Math.round(value * factor) / factor;
}
async function getNeverlandShmonSupplyApy() {
const now = Date.now();
if (neverlandSupplyApyCache.data && (now - neverlandSupplyApyCache.timestamp) < neverlandSupplyApyCache.ttl) {
return neverlandSupplyApyCache.data;
}
const [reserveResult, rewardsData, nshmonDecimals, nshmonSupplyRaw, dustPriceResult] = await Promise.all([
neverlandUiPoolDataProvider.getReservesData(NEVERLAND_POOL_ADDRESSES_PROVIDER),
neverlandRewardsContract.getRewardsData(NSHMON_ADDRESS, DUST_TOKEN_ADDRESS),
nshmonContract.decimals(),
nshmonContract.totalSupply(),
getDexScreenerPriceByTokenAddress(DUST_TOKEN_ADDRESS)
]);
const [reserves, baseCurrencyInfo] = reserveResult;
const shmonReserve = reserves.find((reserve) =>
reserve.underlyingAsset?.toLowerCase() === SHMONAD_ADDRESS.toLowerCase()
);
if (!shmonReserve) {
throw new Error('shMON reserve not found in Neverland');
}
const marketReferenceCurrencyUnit = safeNumber(baseCurrencyInfo?.[0]?.toString(), 0);
const marketReferenceCurrencyPriceInUsd = safeNumber(baseCurrencyInfo?.[1]?.toString(), 0) / 1e8;
const shmonPriceInReference = safeNumber(shmonReserve.priceInMarketReferenceCurrency?.toString(), 0);
const shmonPriceUsd = marketReferenceCurrencyUnit > 0
? (shmonPriceInReference / marketReferenceCurrencyUnit) * marketReferenceCurrencyPriceInUsd
: 0;
const baseSupplyApyPct = safeNumber(ethers.formatUnits(shmonReserve.liquidityRate || 0, 25), 0);
const emissionPerSecond = safeNumber(ethers.formatUnits(rewardsData?.[1] || 0, 18), 0);
const distributionEnd = safeNumber(rewardsData?.[3]?.toString(), 0);
const dustPriceUsd = safeNumber(dustPriceResult?.data?.price, 0);
const nshmonSupply = safeNumber(ethers.formatUnits(nshmonSupplyRaw || 0, Number(nshmonDecimals || 18)), 0);
let incentiveApyPct = 0;
if (distributionEnd > Math.floor(now / 1000) && emissionPerSecond > 0 && dustPriceUsd > 0 && nshmonSupply > 0 && shmonPriceUsd > 0) {
const annualRewardsUsd = emissionPerSecond * 31536000 * dustPriceUsd;
const totalSuppliedUsd = nshmonSupply * shmonPriceUsd;
incentiveApyPct = totalSuppliedUsd > 0 ? (annualRewardsUsd / totalSuppliedUsd) * 100 : 0;
}
const result = {
totalApyPct: round(baseSupplyApyPct + incentiveApyPct, 4),
baseSupplyApyPct: round(baseSupplyApyPct, 4),
dustIncentiveApyPct: round(incentiveApyPct, 4),
emissionPerSecond: round(emissionPerSecond, 8),
distributionEnd,
nshmonSupply: round(nshmonSupply, 4),
shmonPriceUsd: round(shmonPriceUsd, 6),
dustPriceUsd: round(dustPriceUsd, 6),
source: {
reserveProvider: NEVERLAND_UI_POOL_DATA_PROVIDER,
rewardsController: NEVERLAND_REWARDS_CONTROLLER,
rewardToken: DUST_TOKEN_ADDRESS,
asset: NSHMON_ADDRESS
}
};
neverlandSupplyApyCache.data = result;
neverlandSupplyApyCache.timestamp = now;
return result;
}
function calculateSingleStrategyQuote({
principalMon,
monPriceUsd,
shmonToMon,
principalGrowthApyPct,
resultUnit,
profile,
rewardContext = null
}) {
const leveragedExposureMon = principalMon * profile.leverage;
const grossEarningsMon = leveragedExposureMon * (principalGrowthApyPct / 100);
const borrowedPrincipalMon = principalMon * Math.max(profile.leverage - 1, 0);
const borrowCostMon = borrowedPrincipalMon * (profile.borrowApy / 100);
const riskReserveMon = borrowedPrincipalMon * (profile.riskReserveBps / 10000);
const netEarningsMon = grossEarningsMon - borrowCostMon - riskReserveMon;
const endingMon = principalMon + netEarningsMon;
const netApyPct = principalMon > 0 ? (netEarningsMon / principalMon) * 100 : 0;
const earningsInResultUnit = resultUnit === 'USDC'
? netEarningsMon * monPriceUsd
: netEarningsMon;
const endingInResultUnit = resultUnit === 'USDC'
? endingMon * monPriceUsd
: endingMon;
let rewards = null;
if (rewardContext && shmonToMon > 0 && rewardContext.nshmonSupply > 0) {
const suppliedShmon = leveragedExposureMon / shmonToMon;
const annualDustRewards = (suppliedShmon / rewardContext.nshmonSupply)
* rewardContext.emissionPerSecond
* rewardContext.annualRewardSeconds;
const annualDustRewardsUsd = annualDustRewards * rewardContext.dustPriceUsd;
rewards = {
dust: {
estimatedAmount: round(annualDustRewards, 6),
estimatedUsd: round(annualDustRewardsUsd, 4),
priceUsd: round(rewardContext.dustPriceUsd, 6),
annualRewardSeconds: rewardContext.annualRewardSeconds
},
note: 'DUST rewards are separate from MON/shMON ending balance. veDUST / USDC boost not included.'
};
}
return {
id: profile.id,
name: profile.name,
risk: profile.risk,
leverage: profile.leverage,
assumptions: {
borrowApyPct: profile.borrowApy,
riskReserveBps: profile.riskReserveBps
},
grossApyPct: round(principalGrowthApyPct * profile.leverage, 4),
netApyPct: round(netApyPct, 4),
pnl: {
principalMon: round(principalMon, 6),
grossEarningsMon: round(grossEarningsMon, 6),
borrowCostMon: round(borrowCostMon, 6),
riskReserveMon: round(riskReserveMon, 6),
netEarningsMon: round(netEarningsMon, 6),
endingMon: round(endingMon, 6)
},
display: {
resultUnit,
earnings: round(earningsInResultUnit, 4),
endingBalance: round(endingInResultUnit, 4)
},
rewards
};
}
// ==================== API 路由 ====================
/**
* GET /api/rate
* 获取汇率 (1 shMON = ? MON)
*/
app.get('/api/rate', async (req, res) => {
const data = await getExchangeRate();
res.json({
success: data.method !== 'error',
data: {
exchangeRate: data.rate, // 1 shMON = ? MON
method: data.method,
timestamp: data.timestamp
}
});
});
/**
* GET /api/staking-rate
* 获取质押率 (1 MON = ? shMON)
*/
app.get('/api/staking-rate', async (req, res) => {
const data = await getStakingRate();
res.json({
success: data.method !== 'error',
data: {
stakingRate: data.rate, // 1 MON = ? shMON
method: data.method,
timestamp: data.timestamp
}
});
});
/**
* GET /api/both
* 获取两个方向的汇率
*/
app.get('/api/both', async (req, res) => {
const exchangeData = await getExchangeRate();
const rate = parseFloat(exchangeData.rate);
res.json({
success: exchangeData.method !== 'error',
data: {
// 赎回: 1 shMON = ? MON
shmonToMon: exchangeData.rate,
// 质押: 1 MON = ? shMON
monToShmon: rate > 0 ? (1 / rate).toFixed(18) : "1.0",
method: exchangeData.method,
timestamp: exchangeData.timestamp
}
});
});
/**
* GET /api/health
* 健康检查
*/
app.get('/api/health', (req, res) => {
res.json({
status: 'ok',
rpc: MONAD_RPC,
contract: SHMONAD_ADDRESS,
timestamp: Date.now()
});
});
/**
* GET /api/contract-info
* 获取合约基本信息
*/
app.get('/api/contract-info', async (req, res) => {
try {
const [name, symbol, decimals, totalSupply] = await Promise.all([
shmonadContract.name().catch(() => "shMonad"),
shmonadContract.symbol().catch(() => "shMON"),
shmonadContract.decimals().catch(() => 18),
shmonadContract.totalSupply().catch(() => 0n)
]);
res.json({
success: true,
data: {
address: SHMONAD_ADDRESS,
name,
symbol,
decimals: Number(decimals),
totalSupply: ethers.formatUnits(totalSupply, Number(decimals)),
rpc: MONAD_RPC
}
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
// ==================== 价格 API 端点 ====================
/**
* GET /api/price
* 获取指定 Token 价格
* Query params: ids (comma-separated), vs_currencies (default: usd)
* Example: /api/price?ids=bitcoin,ethereum&vs_currencies=usd
*/
app.get('/api/price', async (req, res) => {
const { ids, vs_currencies = 'usd' } = req.query;
const defaultIds = 'bitcoin,ethereum,monad,tether,usd-coin';
const result = await getCoinGeckoPrice(ids || defaultIds, vs_currencies);
if (result.success) {
res.json({
success: true,
data: result.data,
cached: result.cached || false,
timestamp: Date.now()
});
} else {
res.status(500).json({
success: false,
error: result.error
});
}
});
/**
* GET /api/price/btc-eth
* 获取 BTC/ETH 价格 (常用)
*/
app.get('/api/price/btc-eth', async (req, res) => {
const prices = await getBtcEthPrice();
if (prices) {
res.json({
success: true,
data: prices,
timestamp: Date.now()
});
} else {
res.status(500).json({
success: false,
error: 'Failed to fetch prices'
});
}
});
/**
* GET /api/price/monad
* 获取 Monad Token 价格
*/
app.get('/api/price/monad', async (req, res) => {
const result = await getCoinGeckoPrice('monad', 'usd');
if (result.success && result.data && result.data.monad) {
res.json({
success: true,
data: {
symbol: 'MON',
name: 'Monad',
price: result.data.monad.usd,
marketCap: result.data.monad.usd_market_cap,
volume24h: result.data.monad.usd_24h_vol,
change24h: result.data.monad.usd_24h_change
},
timestamp: Date.now()
});
} else {
res.status(500).json({
success: false,
error: 'Failed to fetch Monad price'
});
}
});
/**
* GET /api/price/stables
* 获取稳定币价格 (USDT, USDC, DAI)
*/
app.get('/api/price/stables', async (req, res) => {
const result = await getCoinGeckoPrice('tether,usd-coin,dai', 'usd');
if (result.success) {
const stables = {};
for (const [key, value] of Object.entries(result.data)) {
stables[key] = {
price: value.usd,
marketCap: value.usd_market_cap,
volume24h: value.usd_24h_vol
};
}
res.json({
success: true,
data: stables,
timestamp: Date.now()
});
} else {
res.status(500).json({
success: false,
error: result.error
});
}
});
/**
* GET /api/price/featured
* 获取 Token Prices MVP 固定展示的 4 个币种价格:
* BTC / MON / DUST / shMON
*/
app.get('/api/price/featured', async (req, res) => {
try {
const now = Date.now();
if (featuredPriceCache.data && (now - featuredPriceCache.timestamp) < featuredPriceCache.ttl) {
return res.json({
success: true,
data: featuredPriceCache.data,
cached: true,
timestamp: now
});
}
const [coingeckoResult, exchangeDataFast, dustResult] = await Promise.all([
withTimeout(
getCoinGeckoPrice('bitcoin,monad', 'usd'),
2500,
{ success: false, error: 'CoinGecko simple price timeout' }
),
withTimeout(getExchangeRate(), 1500, null),
withTimeout(
getDexScreenerPriceByTokenAddress(DUST_TOKEN_ADDRESS),
2500,
{ success: false, error: 'DexScreener timeout' }
)
]);
const btc = coingeckoResult?.data?.bitcoin || {};
const mon = coingeckoResult?.data?.monad || {};
// 优先用最新链上汇率,超时则回退最近成功值
if (exchangeDataFast?.rate) {
exchangeRateLastKnown.rate = exchangeDataFast.rate;
exchangeRateLastKnown.method = exchangeDataFast.method || 'unknown';
exchangeRateLastKnown.timestamp = exchangeDataFast.timestamp || now;
}
const exchangeData = exchangeDataFast || exchangeRateLastKnown;
// 1 shMON = exchangeRate MON -> shMON(USD) = MON(USD) * exchangeRate
const exchangeRate = parseFloat(exchangeData?.rate || '0');
const shMonPrice = mon.usd && exchangeRate > 0 ? mon.usd * exchangeRate : null;
const tokens = [
{
id: 'bitcoin',
symbol: 'BTC',
name: 'Bitcoin',
price: btc.usd ?? null,
marketCap: btc.usd_market_cap ?? null,
volume24h: btc.usd_24h_vol ?? null,
change24h: btc.usd_24h_change ?? null,
priceAvailable: !!btc.usd,
source: 'coingecko',
iconUrl: BTC_ICON_URL
},
{
id: 'monad',
symbol: 'MON',
name: 'Monad',
price: mon.usd ?? null,
marketCap: mon.usd_market_cap ?? null,
volume24h: mon.usd_24h_vol ?? null,
change24h: mon.usd_24h_change ?? null,
priceAvailable: !!mon.usd,
source: 'coingecko',
iconUrl: MON_ICON_URL
},
{
id: 'dust',
symbol: 'DUST',
name: 'DUST',
price: dustResult?.data?.price ?? null,
marketCap: dustResult?.data?.marketCap ?? null,
volume24h: dustResult?.data?.volume24h ?? null,
change24h: dustResult?.data?.change24h ?? null,
priceAvailable: dustResult?.success && dustResult?.data?.price != null,
source: dustResult?.success ? `dexscreener:${dustResult?.data?.dexId || 'unknown'}` : 'dexscreener',
tokenAddress: DUST_TOKEN_ADDRESS,
iconUrl: dustResult?.data?.iconUrl || null
},
{
id: 'shmonad',
symbol: 'shMON',
name: 'shMonad',
price: shMonPrice,
marketCap: mon.usd_market_cap ?? null,
volume24h: mon.usd_24h_vol ?? null,
change24h: mon.usd_24h_change ?? null,
priceAvailable: shMonPrice != null,
source: `monad_exchange_rate:${exchangeData?.method || 'unknown'}`,
iconUrl: SHMON_ICON_URL
}
];
const payload = {
tokens,
exchangeRate: exchangeData?.rate || null,
exchangeRateMethod: exchangeData?.method || null
};
featuredPriceCache.data = payload;
featuredPriceCache.timestamp = now;
res.json({
success: true,
data: payload,
partial:
!coingeckoResult?.success ||
!dustResult?.success ||
!exchangeDataFast,
cached: false,
timestamp: now
});
} catch (error) {
console.error('Featured price API error:', error);
res.status(500).json({
success: false,
error: error.message
});
}
});
// ==================== Token 分页 API ====================
/**
* GET /api/tokens
* 分页获取 Token 列表和价格
* Query params:
* - page: 页码 (默认 1)
* - limit: 每页数量 (默认 12)
* - category: 分类过滤 (可选)
* - search: 搜索关键词 (可选)
*/
app.get('/api/tokens', async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 12;
const category = req.query.category;
const search = req.query?.search?.toLowerCase();
// 获取所有 Token
let allTokens = getAllTokens();
// 按分类过滤
if (category && category !== 'all') {
allTokens = allTokens.filter(t => t.category === category);
}
// 搜索过滤
if (search) {
allTokens = allTokens.filter(t =>
t.symbol.toLowerCase().includes(search) ||
t.name.toLowerCase().includes(search) ||
t.id.toLowerCase().includes(search)
);
}
// 分页
const total = allTokens.length;
const totalPages = Math.ceil(total / limit);
const startIndex = (page - 1) * limit;
const endIndex = startIndex + limit;
const paginatedTokens = allTokens.slice(startIndex, endIndex);
// 获取这些 Token 的价格
const coingeckoIds = paginatedTokens.map(t => t.coingeckoId).join(',');
const priceResult = await getCoinGeckoPrice(coingeckoIds, 'usd');
// 合并价格数据
const tokensWithPrices = paginatedTokens.map(token => {
const priceData = priceResult.success ? priceResult.data[token.coingeckoId] : null;
return {
id: token.id,
symbol: token.symbol,
name: token.name,
category: token.category,
categoryDesc: token.categoryDesc,
type: token.type,
underlying: token.underlying || null,
// 价格数据
price: priceData?.usd || null,
marketCap: priceData?.usd_market_cap || null,
volume24h: priceData?.usd_24h_vol || null,
change24h: priceData?.usd_24h_change || null,
priceAvailable: !!priceData?.usd
};
});