-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyield-server.js
More file actions
322 lines (280 loc) · 8.2 KB
/
yield-server.js
File metadata and controls
322 lines (280 loc) · 8.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
const express = require('express');
const cors = require('cors');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = 3457;
app.use(cors());
app.use(express.json());
// Cache for yield data
let yieldCache = {
data: [],
timestamp: null,
ttl: 60000 // 60 seconds
};
// Signature tracking for replay protection
const usedSignatures = new Set();
// Risk scoring function
function calculateRisk(pool) {
const tvl = pool.tvlUsd || 0;
const apy = pool.apy || 0;
let score = 0;
// TVL scoring (lower TVL = higher risk)
if (tvl < 500000) score += 4;
else if (tvl < 1000000) score += 3;
else if (tvl < 5000000) score += 1;
// APY scoring (higher APY = higher risk)
if (apy > 200) score += 4;
else if (apy > 100) score += 2;
else if (apy > 50) score += 1;
return Math.min(score, 10);
}
function getRiskLabel(score) {
if (score <= 2) return 'Low';
if (score <= 5) return 'Medium';
if (score <= 7) return 'High';
return 'Very High';
}
// Fetch yield data from DefiLlama
async function fetchYields(refresh = false) {
const now = Date.now();
if (!refresh && yieldCache.data.length > 0 && (now - yieldCache.timestamp) < yieldCache.ttl) {
return yieldCache.data;
}
try {
console.log('Fetching fresh data from DefiLlama...');
const response = await axios.get('https://yields.llama.fi/pools', {
timeout: 15000,
headers: { 'User-Agent': 'X-Money-Yield-API/1.0' }
});
// Filter for Base network, APY >= 15%, TVL >= $100k
const filtered = response.data.data
.filter(pool =>
pool.chain === 'Base' &&
pool.apy >= 15 &&
pool.tvlUsd >= 100000
)
.map(pool => ({
pool: pool.pool,
symbol: pool.symbol,
project: pool.project,
apy: pool.apy,
apyBase: pool.apyBase || 0,
apyReward: pool.apyReward || 0,
tvlUsd: pool.tvlUsd,
riskScore: calculateRisk(pool),
riskLabel: getRiskLabel(calculateRisk(pool)),
chain: pool.chain,
url: pool.url
}))
.sort((a, b) => b.apy - a.apy);
yieldCache = { data: filtered, timestamp: now };
console.log(`Cached ${filtered.length} pools`);
return filtered;
} catch (error) {
console.error('Error fetching yields:', error.message);
if (yieldCache.data.length > 0) {
return yieldCache.data; // Return stale data on error
}
throw error;
}
}
// Payment validation middleware
function validatePayment(req, res, next) {
const paymentHeader = req.headers['x-402-payment'];
if (!paymentHeader) {
return res.status(402).json({
success: false,
error: 'Payment required. Send X-402-Payment header or subscribe for $5/month',
paymentInfo: {
recipient: '0x6d15eE39fB46Eb439d7B19ACed5d36A4A327eAa2',
amount: '10000 micros ($0.01)',
header: 'X-402-Payment: scheme=ethereum; signature=0x...; amount=10000'
}
});
}
// Parse payment header
const parts = paymentHeader.split(';').map(p => p.trim());
const payment = {};
parts.forEach(part => {
const [key, value] = part.split('=').map(s => s.trim());
if (key && value) payment[key] = value;
});
// Basic validation
if (!payment.scheme || !payment.signature || !payment.amount) {
return res.status(402).json({
success: false,
error: 'Invalid payment header format'
});
}
// Check amount (10000 micros = $0.01)
const amount = parseInt(payment.amount);
if (amount < 10000) {
return res.status(402).json({
success: false,
error: 'Insufficient payment. Minimum: 10000 micros ($0.01)'
});
}
// Replay protection
if (usedSignatures.has(payment.signature)) {
return res.status(402).json({
success: false,
error: 'Signature already used (replay protection)'
});
}
usedSignatures.add(payment.signature);
// Clean old signatures (keep last 1000)
if (usedSignatures.size > 1000) {
const arr = Array.from(usedSignatures);
usedSignatures.clear();
arr.slice(-500).forEach(sig => usedSignatures.add(sig));
}
console.log(`Payment validated: ${payment.signature.substring(0, 16)}...`);
next();
}
// ============ PUBLIC ENDPOINTS (No Payment) ============
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'landing.html'));
});
app.get('/api-docs.md', (req, res) => {
res.sendFile(path.join(__dirname, 'api-docs.md'));
});
app.get('/api/health', async (req, res) => {
try {
const data = await fetchYields(false);
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
poolsCached: data.length,
lastUpdate: new Date(yieldCache.timestamp).toISOString(),
endpoints: {
free: ['/api/health', '/api/pricing'],
paid: ['/api/yields', '/api/top', '/api/alerts', '/api/risk']
}
});
} catch (error) {
res.json({
status: 'degraded',
timestamp: new Date().toISOString(),
error: error.message
});
}
});
app.get('/api/pricing', (req, res) => {
res.json({
pricing: {
perRequest: '$0.01',
monthly: '$5.00',
features: [
'Real-time Base DeFi yields',
'Risk scoring (0-10)',
'TVL filtering',
'Protocol filtering',
'60s cache TTL'
]
},
payment: {
method: 'x402',
header: 'X-402-Payment',
recipient: '0x6d15eE39fB46Eb439d7B19ACed5d36A4A327eAa2',
minAmount: '10000 micros ($0.01)'
},
endpoints: {
'/api/yields': 'All filtered yields',
'/api/top': 'Top N yields with filters',
'/api/alerts': 'High yield alerts',
'/api/risk': 'Low-risk pools only'
}
});
});
// ============ PAID ENDPOINTS ============
app.get('/api/yields', validatePayment, async (req, res) => {
try {
const refresh = req.query.refresh === 'true';
const minApy = parseFloat(req.query.minApy) || 15;
const minTvl = parseFloat(req.query.minTvl) || 100000;
const data = await fetchYields(refresh);
const filtered = data.filter(p => p.apy >= minApy && p.tvlUsd >= minTvl);
res.json({
success: true,
timestamp: new Date().toISOString(),
count: filtered.length,
filters: { minApy, minTvl },
data: filtered
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
app.get('/api/top', validatePayment, async (req, res) => {
try {
const limit = parseInt(req.query.limit) || 10;
const minApy = parseFloat(req.query.minApy) || 15;
const data = await fetchYields();
const filtered = data.filter(p => p.apy >= minApy).slice(0, limit);
res.json({
success: true,
timestamp: new Date().toISOString(),
count: filtered.length,
filters: { limit, minApy },
data: filtered
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
app.get('/api/alerts', validatePayment, async (req, res) => {
try {
const threshold = parseFloat(req.query.threshold) || 50;
const data = await fetchYields();
const alerts = data.filter(p => p.apy >= threshold);
res.json({
success: true,
timestamp: new Date().toISOString(),
threshold,
count: alerts.length,
data: alerts
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
app.get('/api/risk', validatePayment, async (req, res) => {
try {
const maxRisk = parseInt(req.query.maxRisk) || 3;
const data = await fetchYields();
const safe = data.filter(p => p.riskScore <= maxRisk);
res.json({
success: true,
timestamp: new Date().toISOString(),
maxRisk,
count: safe.length,
data: safe
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
// Start server
app.listen(PORT, () => {
console.log(`🚀 X-Money Yield API running on port ${PORT}`);
console.log(`📊 Health: http://localhost:${PORT}/api/health`);
console.log(`💰 Landing: http://localhost:${PORT}/`);
});
// Serve landing page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'landing.html'));
});