-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1232 lines (1129 loc) · 48.1 KB
/
server.js
File metadata and controls
1232 lines (1129 loc) · 48.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
/**
* x402 AgentData API — Base Mainnet, Self-Hosted Facilitator
*/
import express from 'express';
import { x402HTTPResourceServer, x402ResourceServer, paymentMiddlewareFromHTTPServer } from '@x402/express';
import { requestLogger, errorHandler, logUpstreamFailure, getStats } from './analytics.js';
import { mcpHandler } from './mcp-http.js';
import { startIndexer, getRevenueStats, indexPayments } from './revenue.js';
import { cached, getCacheStats, flushCache } from './cache.js';
import { ExactEvmScheme as ServerScheme } from '@x402/evm/exact/server';
import { ExactEvmScheme as FacilitatorScheme } from '@x402/evm/exact/facilitator';
import { toFacilitatorEvmSigner } from '@x402/evm';
import { x402Facilitator } from '@x402/core/facilitator';
import { config } from 'dotenv';
import { createWalletClient, createPublicClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { base, baseSepolia } from 'viem/chains';
config();
const PORT = process.env.PORT || 4021;
const IS_PROD = process.env.NODE_ENV === 'production';
const PAYEE = process.env.WALLET_ADDRESS;
const CHAIN = IS_PROD ? base : baseSepolia;
const NETWORK = IS_PROD ? 'eip155:8453' : 'eip155:84532';
const NETWORK_NAME = IS_PROD ? 'Base Mainnet' : 'Base Sepolia';
const RPC_URL = process.env.BASE_RPC_URL || (IS_PROD ? 'https://mainnet.base.org' : 'https://sepolia.base.org');
// ============ FACILITATOR ============
const facAccount = privateKeyToAccount(process.env.FACILITATOR_PRIVATE_KEY);
const publicClient = createPublicClient({ chain: CHAIN, transport: http(RPC_URL) });
const walletClient = createWalletClient({ account: facAccount, chain: CHAIN, transport: http(RPC_URL) });
const facSigner = toFacilitatorEvmSigner({
address: facAccount.address,
signTypedData: (msg) => walletClient.signTypedData(msg),
verifyTypedData: (args) => publicClient.verifyTypedData(args),
verifyMessage: (args) => publicClient.verifyMessage(args),
readContract: (args) => publicClient.readContract(args),
writeContract: (args) => walletClient.writeContract(args),
getTransactionReceipt: (args) => publicClient.getTransactionReceipt(args),
waitForTransactionReceipt: (args) => publicClient.waitForTransactionReceipt(args),
sendRawTransaction: (args) => walletClient.sendRawTransaction(args),
signTransaction: (args) => walletClient.signTransaction(args),
getTransactionCount: (args) => publicClient.getTransactionCount(args),
estimateFeesPerGas: () => publicClient.estimateFeesPerGas(),
estimateGas: (args) => publicClient.estimateGas(args),
getCode: (args) => publicClient.getCode(args),
getBalance: (args) => publicClient.getBalance(args),
call: (args) => publicClient.call(args),
simulateContract: (args) => publicClient.simulateContract(args),
getChainId: () => publicClient.getChainId(),
});
const localFacilitator = new x402Facilitator()
.register(NETWORK, new FacilitatorScheme(facSigner));
/** Adapter: local facilitator → FacilitatorClient interface */
class LocalFacilitatorClient {
constructor(f) { this.f = f; }
async verify(p, r) { return this.f.verify(p, r); }
async settle(p, r) { return this.f.settle(p, r); }
async getSupported() { return this.f.getSupported(); }
toJsonSafe() { return { type: 'local' }; }
}
// ============ DATA ============
async function fetchPrices() {
return cached('prices', 15, async () => {
const syms = ['BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'BNBUSDT', 'XRPUSDT'];
const out = {};
for (const s of syms) {
try { const r = await fetch(`https://api.mexc.com/api/v3/ticker/price?symbol=${s}`); const d = await r.json(); out[s] = { price: parseFloat(d.price), ts: Date.now() }; }
catch (e) { out[s] = { error: e.message }; }
}
return out;
});
}
async function fetchFundingRates() {
return cached('funding-rates', 30, async () => {
const syms = ['BTC_USDT', 'ETH_USDT', 'SOL_USDT'];
const out = {};
for (const s of syms) {
try {
const r = await fetch(`https://contract.mexc.com/api/v1/contract/funding_rate/${s}`);
const d = await r.json();
if (d.success && d.data?.resultList?.[0]) {
const rate = parseFloat(d.data.resultList[0].fundingRate);
out[s] = { rate, annualized: (rate * 3 * 365 * 100).toFixed(1) + '%', signal: rate > 0.0001 ? 'LONGS_PAY' : rate < -0.0001 ? 'SHORTS_PAY' : 'NEUTRAL' };
}
} catch (e) { out[s] = { error: e.message }; }
}
return out;
});
}
async function fetchOverview() {
const [p, f] = await Promise.all([fetchPrices(), fetchFundingRates()]);
const btcFR = f.BTC_USDT?.rate || 0;
return { ts: new Date().toISOString(), prices: p, fundingRates: f, signals: {
bias: btcFR > 0.0003 ? 'EXTREME_GREED' : btcFR > 0.0001 ? 'BULLISH' : btcFR < -0.0003 ? 'EXTREME_FEAR' : btcFR < -0.0001 ? 'BEARISH' : 'NEUTRAL',
arbOpportunity: Math.abs(btcFR) > 0.0005,
fundingYieldAnnual: (Math.abs(btcFR) * 3 * 365 * 100).toFixed(1) + '%',
}};
}
async function fetchVolatility() {
return cached('volatility', 30, async () => {
// 24h Kline für BTC, ETH, SOL → Volatilität berechnen
const syms = ['BTCUSDT', 'ETHUSDT', 'SOLUSDT'];
const out = {};
for (const s of syms) {
try {
const r = await fetch(`https://api.mexc.com/api/v3/klines?symbol=${s}&interval=1h&limit=24`);
const candles = await r.json();
const closes = candles.map(c => parseFloat(c[4]));
const high = Math.max(...candles.map(c => parseFloat(c[2])));
const low = Math.min(...candles.map(c => parseFloat(c[3])));
const current = closes[closes.length - 1];
const open24h = parseFloat(candles[0][1]);
const returns = [];
for (let i = 1; i < closes.length; i++) returns.push((closes[i] - closes[i-1]) / closes[i-1]);
const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
const vol = Math.sqrt(returns.reduce((a, r) => a + (r - mean) ** 2, 0) / returns.length) * Math.sqrt(24 * 365) * 100;
out[s] = {
price: current,
change24h: ((current - open24h) / open24h * 100).toFixed(2) + '%',
high24h: high,
low24h: low,
range24h: ((high - low) / low * 100).toFixed(2) + '%',
annualizedVolatility: vol.toFixed(1) + '%',
volatilitySignal: vol > 100 ? 'EXTREME' : vol > 60 ? 'HIGH' : vol > 30 ? 'MODERATE' : 'LOW',
};
} catch (e) { out[s] = { error: e.message }; }
}
return { ts: new Date().toISOString(), data: out };
});
}
async function fetchLiquidationLevels() {
return cached('liquidation-levels', 30, async () => {
const syms = ['BTC_USDT', 'ETH_USDT', 'SOL_USDT'];
const out = {};
for (const s of syms) {
try {
const [tickerRes, frRes] = await Promise.all([
fetch(`https://contract.mexc.com/api/v1/contract/ticker?symbol=${s}`),
fetch(`https://contract.mexc.com/api/v1/contract/funding_rate/${s}`),
]);
const ticker = await tickerRes.json();
const fr = await frRes.json();
if (ticker.success && ticker.data) {
const price = parseFloat(ticker.data.lastPrice);
const oi = parseFloat(ticker.data.holdVol || 0);
const fundingRate = fr.success ? parseFloat(fr.data?.resultList?.[0]?.fundingRate || 0) : 0;
out[s] = {
price,
openInterest: oi,
fundingRate,
estimatedLiquidationZones: {
longLiquidations: { '5x': (price * 0.80).toFixed(0), '10x': (price * 0.90).toFixed(0), '20x': (price * 0.95).toFixed(0) },
shortLiquidations: { '5x': (price * 1.20).toFixed(0), '10x': (price * 1.10).toFixed(0), '20x': (price * 1.05).toFixed(0) },
},
riskLevel: Math.abs(fundingRate) > 0.0005 ? 'HIGH' : Math.abs(fundingRate) > 0.0002 ? 'MODERATE' : 'LOW',
};
}
} catch (e) { out[s] = { error: e.message }; }
}
return { ts: new Date().toISOString(), data: out };
});
}
async function fetchCorrelation() {
return cached('correlation', 300, async () => {
const pairs = { BTCUSDT: [], ETHUSDT: [], SOLUSDT: [] };
for (const sym of Object.keys(pairs)) {
try {
const r = await fetch(`https://api.mexc.com/api/v3/klines?symbol=${sym}&interval=1d&limit=30`);
const data = await r.json();
pairs[sym] = data.map(c => parseFloat(c[4]));
} catch {}
}
const calcCorr = (a, b) => {
if (a.length !== b.length || a.length < 3) return null;
const n = a.length;
const meanA = a.reduce((s, v) => s + v, 0) / n;
const meanB = b.reduce((s, v) => s + v, 0) / n;
let num = 0, denA = 0, denB = 0;
for (let i = 0; i < n; i++) { num += (a[i]-meanA)*(b[i]-meanB); denA += (a[i]-meanA)**2; denB += (b[i]-meanB)**2; }
return denA && denB ? num / Math.sqrt(denA * denB) : null;
};
return {
ts: new Date().toISOString(),
period: '30 days',
correlations: {
'ETH/BTC': calcCorr(pairs.ETHUSDT, pairs.BTCUSDT)?.toFixed(4),
'SOL/BTC': calcCorr(pairs.SOLUSDT, pairs.BTCUSDT)?.toFixed(4),
'SOL/ETH': calcCorr(pairs.SOLUSDT, pairs.ETHUSDT)?.toFixed(4),
},
interpretation: '>0.8 = strongly correlated, <0.5 = weak, <0 = inverse',
};
});
}
// ============ NEW ENDPOINTS ============
// JSON-RPC helper for EVM chains
async function rpc(url, method, params = []) {
const r = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
});
const d = await r.json();
if (d.error) throw new Error(d.error.message);
return d.result;
}
// 1) Gas prices for Base / Ethereum / Solana
async function fetchGasPrices() {
return cached('gas-prices', 10, async () => {
const out = { ts: new Date().toISOString(), chains: {} };
// Base + Ethereum via RPC (eth_gasPrice in wei)
const evmChains = {
base: 'https://mainnet.base.org',
ethereum: 'https://eth.llamarpc.com',
};
for (const [name, url] of Object.entries(evmChains)) {
try {
const hex = await rpc(url, 'eth_gasPrice');
const gwei = parseInt(hex, 16) / 1e9;
out.chains[name] = {
gasPriceGwei: gwei.toFixed(3),
gasPriceWei: parseInt(hex, 16),
estimatedCostSimpleTransferUSD: ((gwei * 21000 * 1e-9) * (name === 'ethereum' ? 3500 : 3500)).toFixed(4),
};
} catch (e) { out.chains[name] = { error: e.message }; }
}
// Solana: use getRecentPrioritizationFees
try {
const url = 'https://api.mainnet-beta.solana.com';
const r = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getRecentPrioritizationFees', params: [] }),
});
const d = await r.json();
if (d.result && d.result.length) {
const fees = d.result.map(f => f.prioritizationFee);
const avg = fees.reduce((a, b) => a + b, 0) / fees.length;
out.chains.solana = {
avgPrioritizationFeeMicroLamports: avg.toFixed(0),
medianFee: fees.sort((a, b) => a - b)[Math.floor(fees.length / 2)],
};
}
} catch (e) { out.chains.solana = { error: e.message }; }
return out;
});
}
// 2) Base network activity
async function fetchBaseActivity() {
return cached('base-activity', 10, async () => {
const url = 'https://mainnet.base.org';
try {
const [blockHex, gasHex] = await Promise.all([
rpc(url, 'eth_blockNumber'),
rpc(url, 'eth_gasPrice'),
]);
const blockNum = parseInt(blockHex, 16);
const latestBlock = await rpc(url, 'eth_getBlockByNumber', [blockHex, false]);
const prevBlock = await rpc(url, 'eth_getBlockByNumber', ['0x' + (blockNum - 10).toString(16), false]);
const blockTime = parseInt(latestBlock.timestamp, 16);
const prevTime = parseInt(prevBlock.timestamp, 16);
const avgBlockTime = (blockTime - prevTime) / 10;
const txCount = latestBlock.transactions.length;
return {
ts: new Date().toISOString(),
network: 'Base Mainnet',
latestBlock: blockNum,
blockTimestamp: new Date(blockTime * 1000).toISOString(),
avgBlockTimeSeconds: avgBlockTime.toFixed(2),
txInLatestBlock: txCount,
estimatedTPS: (txCount / avgBlockTime).toFixed(2),
gasPriceGwei: (parseInt(gasHex, 16) / 1e9).toFixed(3),
gasUsed: parseInt(latestBlock.gasUsed, 16),
gasLimit: parseInt(latestBlock.gasLimit, 16),
utilization: ((parseInt(latestBlock.gasUsed, 16) / parseInt(latestBlock.gasLimit, 16)) * 100).toFixed(2) + '%',
};
} catch (e) {
return { error: e.message };
}
});
}
// 3) DeFi yields from DefiLlama
async function fetchDefiYields() {
return cached('defi-yields', 300, async () => {
try {
const r = await fetch('https://yields.llama.fi/pools');
const d = await r.json();
if (!d.data) return { error: 'No data' };
// Filter: stablecoin pools with TVL > $10M, sort by APY
const stablePools = d.data
.filter(p => p.stablecoin && p.tvlUsd > 10_000_000 && p.apy > 0 && p.apy < 50)
.sort((a, b) => b.apy - a.apy)
.slice(0, 20)
.map(p => ({
project: p.project,
chain: p.chain,
symbol: p.symbol,
tvlUsd: p.tvlUsd,
apy: p.apy.toFixed(2),
apyBase: p.apyBase?.toFixed(2) || null,
apyReward: p.apyReward?.toFixed(2) || null,
rewardTokens: p.rewardTokens || [],
ilRisk: p.ilRisk,
exposure: p.exposure,
}));
// ETH/BTC yields
const majorPools = d.data
.filter(p => ['ETH', 'WETH', 'BTC', 'WBTC', 'cbETH', 'wstETH'].some(t => p.symbol?.includes(t)) && p.tvlUsd > 10_000_000 && p.apy > 0)
.sort((a, b) => b.apy - a.apy)
.slice(0, 10)
.map(p => ({ project: p.project, chain: p.chain, symbol: p.symbol, tvlUsd: p.tvlUsd, apy: p.apy.toFixed(2) }));
return {
ts: new Date().toISOString(),
totalPoolsScanned: d.data.length,
topStablecoinYields: stablePools,
topMajorAssetYields: majorPools,
};
} catch (e) { return { error: e.message }; }
});
}
// 4) Cross-exchange arbitrage opportunities
async function fetchArbitrage() {
return cached('arbitrage', 10, async () => {
const symbols = ['BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'BNBUSDT', 'XRPUSDT'];
const exchanges = {
mexc: s => `https://api.mexc.com/api/v3/ticker/price?symbol=${s}`,
binance: s => `https://api.binance.com/api/v3/ticker/price?symbol=${s}`,
bybit: s => `https://api.bybit.com/v5/market/tickers?category=spot&symbol=${s}`,
okx: s => `https://www.okx.com/api/v5/market/ticker?instId=${s.replace('USDT', '-USDT')}`,
};
const prices = {};
for (const sym of symbols) {
prices[sym] = {};
await Promise.allSettled(Object.entries(exchanges).map(async ([name, urlFn]) => {
try {
const r = await fetch(urlFn(sym));
const d = await r.json();
let price = null;
if (name === 'mexc' || name === 'binance') price = parseFloat(d.price);
else if (name === 'bybit') price = parseFloat(d.result?.list?.[0]?.lastPrice);
else if (name === 'okx') price = parseFloat(d.data?.[0]?.last);
if (price && !isNaN(price)) prices[sym][name] = price;
} catch {}
}));
}
const opportunities = [];
for (const [sym, venues] of Object.entries(prices)) {
const entries = Object.entries(venues);
if (entries.length < 2) continue;
const sorted = entries.sort((a, b) => a[1] - b[1]);
const [cheapest, cheapPrice] = sorted[0];
const [expensive, expPrice] = sorted[sorted.length - 1];
const spreadPct = ((expPrice - cheapPrice) / cheapPrice) * 100;
if (spreadPct > 0.05) {
opportunities.push({
symbol: sym,
buyOn: cheapest,
buyPrice: cheapPrice,
sellOn: expensive,
sellPrice: expPrice,
spreadPct: spreadPct.toFixed(3),
profitableAfterFees: spreadPct > 0.2,
});
}
}
return {
ts: new Date().toISOString(),
exchangesChecked: Object.keys(exchanges),
allPrices: prices,
opportunities: opportunities.sort((a, b) => parseFloat(b.spreadPct) - parseFloat(a.spreadPct)),
};
});
}
// 5) DEX vs CEX price comparison
async function fetchDexVsCex() {
return cached('dex-vs-cex', 10, async () => {
try {
const tokens = {
'BTC': 'coingecko:bitcoin',
'ETH': 'coingecko:ethereum',
'SOL': 'coingecko:solana',
};
const keys = Object.values(tokens).join(',');
const [dexR, cexPrices] = await Promise.all([
fetch(`https://coins.llama.fi/prices/current/${keys}`),
fetchPrices(),
]);
const dex = await dexR.json();
const out = {};
for (const [sym, key] of Object.entries(tokens)) {
const dexPrice = dex.coins[key]?.price;
const cexPrice = cexPrices[sym + 'USDT']?.price;
if (dexPrice && cexPrice) {
const spread = ((cexPrice - dexPrice) / dexPrice) * 100;
out[sym] = {
dexPrice,
cexPrice,
spreadPct: spread.toFixed(3),
direction: spread > 0 ? 'CEX_PREMIUM' : 'DEX_PREMIUM',
};
}
}
return { ts: new Date().toISOString(), data: out };
} catch (e) { return { error: e.message }; }
});
}
// 6) Technical indicators (RSI, MACD, Bollinger)
async function fetchIndicators(symbol = 'BTCUSDT', interval = '1h') {
return cached(`indicators:${symbol}:${interval}`, 30, async () => {
try {
const r = await fetch(`https://api.mexc.com/api/v3/klines?symbol=${symbol}&interval=${interval}&limit=100`);
const candles = await r.json();
if (!Array.isArray(candles) || candles.length < 26) return { error: 'Insufficient data' };
const closes = candles.map(c => parseFloat(c[4]));
// RSI (14)
const rsiPeriod = 14;
let gains = 0, losses = 0;
for (let i = 1; i <= rsiPeriod; i++) {
const diff = closes[i] - closes[i-1];
if (diff > 0) gains += diff; else losses -= diff;
}
let avgGain = gains / rsiPeriod, avgLoss = losses / rsiPeriod;
for (let i = rsiPeriod + 1; i < closes.length; i++) {
const diff = closes[i] - closes[i-1];
avgGain = (avgGain * (rsiPeriod - 1) + (diff > 0 ? diff : 0)) / rsiPeriod;
avgLoss = (avgLoss * (rsiPeriod - 1) + (diff < 0 ? -diff : 0)) / rsiPeriod;
}
const rsi = avgLoss === 0 ? 100 : 100 - 100 / (1 + avgGain / avgLoss);
// MACD (12, 26, 9)
const ema = (arr, period) => {
const k = 2 / (period + 1);
let e = arr.slice(0, period).reduce((a, b) => a + b, 0) / period;
const out = [e];
for (let i = period; i < arr.length; i++) { e = arr[i] * k + e * (1 - k); out.push(e); }
return out;
};
const ema12 = ema(closes, 12);
const ema26 = ema(closes, 26);
const macdLine = ema12.slice(ema12.length - ema26.length).map((v, i) => v - ema26[i]);
const signalLine = ema(macdLine, 9);
const histogram = macdLine[macdLine.length - 1] - signalLine[signalLine.length - 1];
// Bollinger Bands (20, 2)
const bbPeriod = 20;
const last20 = closes.slice(-bbPeriod);
const sma = last20.reduce((a, b) => a + b, 0) / bbPeriod;
const stdDev = Math.sqrt(last20.reduce((a, c) => a + (c - sma) ** 2, 0) / bbPeriod);
const bbUpper = sma + 2 * stdDev;
const bbLower = sma - 2 * stdDev;
const current = closes[closes.length - 1];
const bbPosition = ((current - bbLower) / (bbUpper - bbLower) * 100).toFixed(1);
// ATR (14)
const trValues = [];
for (let i = 1; i < candles.length; i++) {
const high = parseFloat(candles[i][2]);
const low = parseFloat(candles[i][3]);
const prevClose = parseFloat(candles[i-1][4]);
trValues.push(Math.max(high - low, Math.abs(high - prevClose), Math.abs(low - prevClose)));
}
const atr = trValues.slice(-14).reduce((a, b) => a + b, 0) / 14;
return {
ts: new Date().toISOString(),
symbol, interval, price: current,
indicators: {
rsi: { value: rsi.toFixed(2), signal: rsi > 70 ? 'OVERBOUGHT' : rsi < 30 ? 'OVERSOLD' : 'NEUTRAL' },
macd: { macd: macdLine[macdLine.length - 1].toFixed(4), signal: signalLine[signalLine.length - 1].toFixed(4), histogram: histogram.toFixed(4), trend: histogram > 0 ? 'BULLISH' : 'BEARISH' },
bollinger: { upper: bbUpper.toFixed(2), middle: sma.toFixed(2), lower: bbLower.toFixed(2), positionPct: bbPosition, signal: bbPosition > 80 ? 'NEAR_UPPER' : bbPosition < 20 ? 'NEAR_LOWER' : 'MIDDLE' },
atr: { value: atr.toFixed(4), volatilityPct: (atr / current * 100).toFixed(2) + '%' },
},
};
} catch (e) { return { error: e.message }; }
});
}
// 7) Support & Resistance via fractal analysis
async function fetchSupportResistance(symbol = 'BTCUSDT') {
return cached(`sr:${symbol}`, 60, async () => {
try {
const r = await fetch(`https://api.mexc.com/api/v3/klines?symbol=${symbol}&interval=4h&limit=200`);
const candles = await r.json();
if (!Array.isArray(candles)) return { error: 'Invalid data' };
const highs = candles.map(c => parseFloat(c[2]));
const lows = candles.map(c => parseFloat(c[3]));
const current = parseFloat(candles[candles.length - 1][4]);
// Fractal: a peak/valley requires 2 candles on each side
const peaks = [], valleys = [];
for (let i = 2; i < candles.length - 2; i++) {
if (highs[i] > highs[i-1] && highs[i] > highs[i-2] && highs[i] > highs[i+1] && highs[i] > highs[i+2]) peaks.push(highs[i]);
if (lows[i] < lows[i-1] && lows[i] < lows[i-2] && lows[i] < lows[i+1] && lows[i] < lows[i+2]) valleys.push(lows[i]);
}
// Filter S/R levels relevant to current price (within ±20%)
const resistances = [...new Set(peaks)].filter(p => p > current && p < current * 1.2).sort((a, b) => a - b).slice(0, 5);
const supports = [...new Set(valleys)].filter(v => v < current && v > current * 0.8).sort((a, b) => b - a).slice(0, 5);
return {
ts: new Date().toISOString(),
symbol,
currentPrice: current,
timeframe: '4h over 200 candles (~33 days)',
resistances: resistances.map(r => ({ price: r.toFixed(2), distancePct: ((r - current) / current * 100).toFixed(2) + '%' })),
supports: supports.map(s => ({ price: s.toFixed(2), distancePct: ((current - s) / current * 100).toFixed(2) + '%' })),
nearestResistance: resistances[0]?.toFixed(2) || null,
nearestSupport: supports[0]?.toFixed(2) || null,
};
} catch (e) { return { error: e.message }; }
});
}
// 8) Market sentiment (Fear & Greed + derived)
async function fetchSentiment() {
return cached('sentiment', 300, async () => {
try {
const [fgR, funding] = await Promise.all([
fetch('https://api.alternative.me/fng/?limit=7'),
fetchFundingRates(),
]);
const fg = await fgR.json();
const current = fg.data?.[0];
const btcFR = funding.BTC_USDT?.rate || 0;
// Derive composite sentiment
const fgValue = parseInt(current?.value || 50);
const fundingSentiment = btcFR > 0.0003 ? 80 : btcFR > 0.0001 ? 65 : btcFR < -0.0003 ? 20 : btcFR < -0.0001 ? 35 : 50;
const composite = (fgValue * 0.7 + fundingSentiment * 0.3).toFixed(0);
return {
ts: new Date().toISOString(),
fearGreedIndex: {
value: fgValue,
classification: current?.value_classification || 'unknown',
yesterday: parseInt(fg.data?.[1]?.value || 0),
lastWeek: parseInt(fg.data?.[6]?.value || 0),
},
fundingBasedSentiment: fundingSentiment,
compositeSentiment: { value: parseInt(composite), classification:
composite >= 75 ? 'EXTREME_GREED' : composite >= 60 ? 'GREED' : composite >= 40 ? 'NEUTRAL' : composite >= 25 ? 'FEAR' : 'EXTREME_FEAR' },
btcFundingRate: btcFR,
};
} catch (e) { return { error: e.message }; }
});
}
// 9) Stablecoin health (peg + TVL)
async function fetchStablecoinHealth() {
return cached('stablecoin-health', 60, async () => {
try {
const [llamaR, usdcR, usdtR, daiR] = await Promise.all([
fetch('https://stablecoins.llama.fi/stablecoins?includePrices=true'),
fetch('https://api.mexc.com/api/v3/ticker/price?symbol=USDCUSDT'),
fetch('https://api.mexc.com/api/v3/ticker/price?symbol=USDTUSDC'),
fetch('https://api.mexc.com/api/v3/ticker/price?symbol=DAIUSDT'),
]);
const llama = await llamaR.json();
const usdcPrice = parseFloat((await usdcR.json()).price || 0);
const daiPrice = parseFloat((await daiR.json()).price || 0);
const topStables = (llama.peggedAssets || [])
.sort((a, b) => (b.circulating?.peggedUSD || 0) - (a.circulating?.peggedUSD || 0))
.slice(0, 10)
.map(s => ({
symbol: s.symbol,
name: s.name,
circulating: Math.floor(s.circulating?.peggedUSD || 0),
currentPrice: s.price || null,
pegType: s.pegType,
}));
return {
ts: new Date().toISOString(),
liveDepegCheck: {
USDC: { price: usdcPrice, pegDeviation: ((Math.abs(usdcPrice - 1)) * 100).toFixed(4) + '%', status: Math.abs(usdcPrice - 1) < 0.002 ? 'PEGGED' : 'DEPEG_RISK' },
DAI: { price: daiPrice, pegDeviation: ((Math.abs(daiPrice - 1)) * 100).toFixed(4) + '%', status: Math.abs(daiPrice - 1) < 0.002 ? 'PEGGED' : 'DEPEG_RISK' },
},
topStablecoinsByMarketCap: topStables,
totalStablecoinMarketCap: topStables.reduce((a, s) => a + s.circulating, 0),
};
} catch (e) { return { error: e.message }; }
});
}
// 10) Historical OHLCV data (paginated)
async function fetchHistorical(symbol = 'BTCUSDT', interval = '1d', limit = 100) {
return cached(`historical:${symbol}:${interval}:${limit}`, 60, async () => {
try {
limit = Math.min(parseInt(limit) || 100, 500);
const r = await fetch(`https://api.mexc.com/api/v3/klines?symbol=${symbol}&interval=${interval}&limit=${limit}`);
const candles = await r.json();
if (!Array.isArray(candles)) return { error: 'Invalid data' };
const data = candles.map(c => ({
timestamp: c[0],
date: new Date(c[0]).toISOString(),
open: parseFloat(c[1]),
high: parseFloat(c[2]),
low: parseFloat(c[3]),
close: parseFloat(c[4]),
volume: parseFloat(c[5]),
}));
// Summary stats
const closes = data.map(d => d.close);
const first = closes[0], last = closes[closes.length - 1];
const high = Math.max(...data.map(d => d.high));
const low = Math.min(...data.map(d => d.low));
return {
ts: new Date().toISOString(),
symbol, interval,
candleCount: data.length,
summary: {
firstPrice: first, lastPrice: last,
change: (last - first).toFixed(2),
changePct: ((last - first) / first * 100).toFixed(2) + '%',
highestHigh: high, lowestLow: low,
totalVolume: data.reduce((a, d) => a + d.volume, 0).toFixed(2),
},
candles: data,
};
} catch (e) { return { error: e.message }; }
});
}
// ============ APP SETUP ============
async function startServer() {
const app = express();
app.set('trust proxy', true); // behind nginx
// Request analytics middleware — first in chain so all requests get logged
app.use(requestLogger());
// 1. Build resource server with local facilitator
const facClient = new LocalFacilitatorClient(localFacilitator);
const resourceServer = new x402ResourceServer(facClient);
resourceServer.register(NETWORK, new ServerScheme());
// 2. Routes config
// Helper: build route with input & output schemas + example
const route = (price, desc, outputProps, queryParams = {}, outputExample = null) => {
const inputSchema = {
type: 'http',
method: 'GET',
discoverable: true,
queryParams,
};
const outputSchema = {
type: 'http',
contentType: 'application/json',
schema: { type: 'object', properties: outputProps },
};
return {
accepts: { scheme: 'exact', price, network: NETWORK, payTo: PAYEE,
extra: { name: 'USD Coin', version: '2', inputSchema, outputSchema },
},
description: desc,
inputSchema,
outputSchema,
// For agentcash v2 bazaar extraction
queryParamsSchema: { type: 'object', properties: queryParams, additionalProperties: false },
outputExample: outputExample || { success: true, data: {} },
};
};
const routes = {
'GET /api/prices': route('$0.001',
'Real-time prices for BTC, ETH, SOL, BNB, XRP', {
success: { type: 'boolean' },
data: {
type: 'object',
description: 'Map of symbol → { price, ts }',
additionalProperties: { type: 'object', properties: { price: { type: 'number' }, ts: { type: 'number' } } },
},
}),
'GET /api/funding-rates': route('$0.001',
'Perpetual funding rates with long/short signals', {
success: { type: 'boolean' },
data: {
type: 'object',
description: 'Map of symbol → { rate, annualized, signal }',
additionalProperties: {
type: 'object',
properties: {
rate: { type: 'number' },
annualized: { type: 'string' },
signal: { type: 'string', enum: ['LONGS_PAY', 'SHORTS_PAY', 'NEUTRAL'] },
},
},
},
}),
'GET /api/market-overview': route('$0.002',
'Full market overview with sentiment and arbitrage signals', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
ts: { type: 'string' },
prices: { type: 'object' },
fundingRates: { type: 'object' },
signals: {
type: 'object',
properties: {
bias: { type: 'string', enum: ['EXTREME_GREED', 'BULLISH', 'NEUTRAL', 'BEARISH', 'EXTREME_FEAR'] },
arbOpportunity: { type: 'boolean' },
fundingYieldAnnual: { type: 'string' },
},
},
},
},
}),
'GET /api/volatility': route('$0.001',
'24h volatility, range, annualized vol for BTC/ETH/SOL', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
ts: { type: 'string' },
data: {
type: 'object',
additionalProperties: {
type: 'object',
properties: {
price: { type: 'number' },
change24h: { type: 'string' },
high24h: { type: 'number' },
low24h: { type: 'number' },
range24h: { type: 'string' },
annualizedVolatility: { type: 'string' },
volatilitySignal: { type: 'string', enum: ['LOW', 'MODERATE', 'HIGH', 'EXTREME'] },
},
},
},
},
},
}),
'GET /api/liquidation-levels': route('$0.002',
'Estimated liquidation zones by leverage (5x/10x/20x)', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
ts: { type: 'string' },
data: {
type: 'object',
additionalProperties: {
type: 'object',
properties: {
price: { type: 'number' },
openInterest: { type: 'number' },
fundingRate: { type: 'number' },
estimatedLiquidationZones: {
type: 'object',
properties: {
longLiquidations: { type: 'object' },
shortLiquidations: { type: 'object' },
},
},
riskLevel: { type: 'string', enum: ['LOW', 'MODERATE', 'HIGH'] },
},
},
},
},
},
}),
'GET /api/correlation': route('$0.001',
'30-day price correlation matrix (ETH/BTC, SOL/BTC, SOL/ETH)', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
ts: { type: 'string' },
period: { type: 'string' },
correlations: { type: 'object' },
},
},
}),
// ==== New Endpoints ====
'GET /api/gas-prices': route('$0.001',
'Current gas prices for Base, Ethereum, Solana with USD cost estimation', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: { ts: { type: 'string' }, chains: { type: 'object' } },
},
}),
'GET /api/base-activity': route('$0.002',
'Base Mainnet network activity: latest block, TPS, gas utilization, whale activity', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
latestBlock: { type: 'number' }, blockTimestamp: { type: 'string' },
avgBlockTimeSeconds: { type: 'string' }, txInLatestBlock: { type: 'number' },
estimatedTPS: { type: 'string' }, gasPriceGwei: { type: 'string' },
utilization: { type: 'string' },
},
},
}),
'GET /api/defi-yields': route('$0.002',
'Top DeFi yield opportunities across protocols (Aave, Compound, Morpho, Pendle, etc) from DefiLlama', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
totalPoolsScanned: { type: 'number' },
topStablecoinYields: { type: 'array' },
topMajorAssetYields: { type: 'array' },
},
},
}),
'GET /api/arbitrage-opportunities': route('$0.003',
'Cross-exchange arbitrage opportunities between MEXC, Binance, Bybit, OKX (spread > 0.05%)', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
exchangesChecked: { type: 'array' },
allPrices: { type: 'object' },
opportunities: { type: 'array' },
},
},
}),
'GET /api/dex-vs-cex': route('$0.003',
'DEX aggregated prices vs CEX prices with spread analysis for BTC/ETH/SOL', {
success: { type: 'boolean' },
data: { type: 'object', properties: { ts: { type: 'string' }, data: { type: 'object' } } },
}),
'GET /api/indicators': route('$0.002',
'Technical indicators (RSI, MACD, Bollinger Bands, ATR). Query params: symbol (default BTCUSDT), interval (default 1h)', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
symbol: { type: 'string' }, interval: { type: 'string' }, price: { type: 'number' },
indicators: { type: 'object' },
},
},
},
{
symbol: { type: 'string', description: 'Trading pair (e.g. BTCUSDT)', default: 'BTCUSDT' },
interval: { type: 'string', enum: ['1m', '5m', '15m', '30m', '1h', '4h', '1d'], default: '1h' },
}),
'GET /api/support-resistance': route('$0.003',
'Support & Resistance levels via fractal analysis on 4h timeframe. Query param: symbol (default BTCUSDT)', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
symbol: { type: 'string' }, currentPrice: { type: 'number' },
resistances: { type: 'array' }, supports: { type: 'array' },
},
},
},
{
symbol: { type: 'string', description: 'Trading pair (e.g. BTCUSDT)', default: 'BTCUSDT' },
}),
'GET /api/sentiment': route('$0.001',
'Composite market sentiment: Fear & Greed Index + Funding-based sentiment + composite score', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
fearGreedIndex: { type: 'object' },
fundingBasedSentiment: { type: 'number' },
compositeSentiment: { type: 'object' },
},
},
}),
'GET /api/stablecoin-health': route('$0.001',
'Stablecoin peg monitoring (USDC, DAI live depeg check) + top 10 stablecoins by market cap', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
liveDepegCheck: { type: 'object' },
topStablecoinsByMarketCap: { type: 'array' },
totalStablecoinMarketCap: { type: 'number' },
},
},
}),
'GET /api/historical': route('$0.005',
'Historical OHLCV candles. Query params: symbol (default BTCUSDT), interval (1m/5m/15m/1h/4h/1d), limit (max 500)', {
success: { type: 'boolean' },
data: {
type: 'object',
properties: {
symbol: { type: 'string' }, interval: { type: 'string' },
candleCount: { type: 'number' },
summary: { type: 'object' },
candles: { type: 'array' },
},
},
},
{
symbol: { type: 'string', description: 'Trading pair', default: 'BTCUSDT' },
interval: { type: 'string', enum: ['1m', '5m', '15m', '30m', '1h', '4h', '1d'], default: '1d' },
limit: { type: 'integer', minimum: 1, maximum: 500, default: 100 },
}),
};
// 3. Build HTTP server and INITIALIZE before accepting requests
const httpResourceServer = new x402HTTPResourceServer(resourceServer, routes);
await httpResourceServer.initialize();
console.log(' x402 initialized — payment kinds loaded');
// 4a. 402-response interceptor: patch the PAYMENT-REQUIRED header
// to add agentcash/x402scan-compatible outputSchema.input/output
// (both at accepts[0] level and in extensions.bazaar)
app.use((req, res, next) => {
const routeKey = `${req.method} ${req.path}`;
const cfg = routes[routeKey];
if (!cfg) return next();
// Capture the original setHeader to patch PAYMENT-REQUIRED on the way out
const origSetHeader = res.setHeader.bind(res);
let payloadPatch = null;
res.setHeader = function (name, value) {
const nameLower = String(name).toLowerCase();
if (nameLower === 'payment-required' && typeof value === 'string' && value.length > 10) {
try {
const decoded = JSON.parse(Buffer.from(value, 'base64').toString('utf8'));
if (decoded.accepts && Array.isArray(decoded.accepts)) {
decoded.accepts = decoded.accepts.map(a => ({
...a,
maxAmountRequired: a.amount || a.maxAmountRequired,
outputSchema: {
input: cfg.inputSchema,
output: cfg.outputSchema,
},
}));
decoded.extensions = {
...decoded.extensions,
bazaar: {
schema: {
properties: {
input: { properties: { queryParams: cfg.queryParamsSchema || { type: 'object', properties: {} } } },
output: { properties: { example: cfg.outputExample || { success: true, data: {} } } },
},
},
},
};
const reEncoded = Buffer.from(JSON.stringify(decoded)).toString('base64');
payloadPatch = decoded;
return origSetHeader(name, reEncoded);
}