-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
597 lines (541 loc) · 17.1 KB
/
Copy pathserver.js
File metadata and controls
597 lines (541 loc) · 17.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
require('dotenv').config();
const cron = require('node-cron');
const { setTimeout: delay } = require('node:timers/promises');
const FUNDING_LOCK_KEY = 834911; // constant for advisory lock
async function fetchAddressData(address) {
const url = `https://api.blockchair.com/zcash/dashboards/address/${address}?transactions=true`;
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP error ${response.status}`);
const data = await response.json();
return data;
}
async function fetchWalletInfo(addresses) {
const results = [];
let total_balance = 0;
let total_received = 0;
let total_sent = 0;
for (const addr of addresses) {
try {
const data = await fetchAddressData(addr);
const info = data.data[addr].address;
const balance = info.balance / 1e8;
const received = info.received / 1e8;
const sent = info.sent / 1e8;
const transactions = data.data[addr].transactions.slice(0, 10);
total_balance += balance;
total_received += received;
total_sent += sent;
results.push({
address: addr,
balance,
total_received: received,
total_sent: sent,
transactions
});
} catch (error) {
results.push({
address: addr,
error: error.message
});
}
}
return {
addresses: results,
totals: {
balance: total_balance,
total_received: total_received,
total_sent: total_sent
}
};
}
// ---- Scheduled funding updater (adds new functionality; leaves existing routes untouched) ----
async function runFundingUpdater(pool, { dryRun = false } = {}) {
const client = await pool.connect();
const start = Date.now();
let updated = 0, failed = 0;
try {
const { rows } = await client.query('SELECT pg_try_advisory_lock($1) AS locked', [FUNDING_LOCK_KEY]);
if (!rows[0].locked) {
console.log('[funding-cron] Another updater is running; skipping.');
return { skipped: true };
}
const { rows: cards } = await client.query(`
SELECT id, wallet_addresses, funding_spent
FROM cards
WHERE visibility = 'PUBLIC'
AND wallet_addresses IS NOT NULL
AND array_length(wallet_addresses, 1) > 0
`);
console.log(`[funding-cron] Updating ${cards.length} card(s)...`);
for (const card of cards) {
try {
const walletInfo = await fetchWalletInfo(card.wallet_addresses);
const zecReceived = Number(walletInfo?.totals?.total_received || 0);
const spent = Number(card.funding_spent || 0);
const available = Number((zecReceived - spent).toFixed(8));
if (!dryRun) {
await client.query(`
UPDATE cards
SET funding_received = $1,
funding_available = $2,
last_updated = NOW()
WHERE id = $3
`, [zecReceived, available, card.id]);
}
updated++;
await delay(150); // light throttle for upstream API courtesy
} catch (e) {
failed++;
console.error('[funding-cron] Card update failed:', card.id, e.message);
}
}
const ms = Date.now() - start;
console.log(`[funding-cron] Done. Updated=${updated} Failed=${failed} in ${ms}ms`);
return { updated, failed, ms };
} catch (e) {
console.error('[funding-cron] Fatal error:', e);
throw e;
} finally {
try { await client.query('SELECT pg_advisory_unlock($1)', [FUNDING_LOCK_KEY]); } catch {}
client.release();
}
}
const swaggerUi = require('swagger-ui-express');
const swaggerJSDoc = require('swagger-jsdoc');
const swaggerDefinition = {
openapi: '3.0.0',
info: {
title: 'ZDA Funding Wallet API',
version: '1.0.0',
description: 'API for managing cards, milestones, and funding',
},
servers: [
{ url: 'https://zdabe.onrender.com' }
],
};
const options = {
swaggerDefinition,
apis: ['./server.js'], // We'll add swagger comments here
};
const swaggerSpec = swaggerJSDoc(options);
const express = require('express');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const { Pool } = require('pg');
// Replace this with your actual Supabase connection string
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
pool.connect()
.then(() => {
console.log('Connected to the database');
// Schedule: Twice per day at 03:15 and 15:15 Eastern Time
cron.schedule('15 3,15 * * *', async () => {
console.log('[funding-cron] Starting scheduled run…');
try {
await runFundingUpdater(pool);
} catch (e) {
// errors are logged inside runFundingUpdater
}
}, { timezone: 'America/New_York' });
// Optional: run once 30s after startup to avoid stale data on fresh deploys
setTimeout(() => runFundingUpdater(pool).catch(() => {}), 30_000);
})
.catch(err => console.error('Database connection error:', err.stack));
const app = express();
const PORT = 3000;
// Enable CORS
app.use(cors());
// Rate limiter: 60 requests per minute per IP
const limiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
message: 'Too many requests, please try again later.'
});
app.use(limiter);
app.use((req, res, next) => {
res.set('X-API-Version', 'v1');
next();
});
// Simple test route
app.get('/', (req, res) => {
res.send('ZDA Funding Wallet API v1 is running');
});
/**
* @swagger
* /api/v1/exchange-rate:
* get:
* summary: Get the current ZEC to USD exchange rate
* responses:
* 200:
* description: Exchange rate data
* content:
* application/json:
* schema:
* type: object
* properties:
* zec_to_usd:
* type: number
* description: The current exchange rate from ZEC to USD
* example: 72.55
* timestamp:
* type: string
* format: date-time
* description: Timestamp of the exchange rate
* example: "2025-07-01T12:00:00.000Z"
*/
app.get('/api/v1/exchange-rate', (req, res) => {
res.set('Cache-Control', 'public, max-age=30');
res.json({
zec_to_usd: 72.55,
timestamp: new Date().toISOString()
});
});
/**
* @swagger
* /api/v1/cards:
* get:
* summary: Get a list of cards with pagination and filters
* parameters:
* - in: query
* name: page
* schema:
* type: integer
* description: Page number (default 1)
* - in: query
* name: per_page
* schema:
* type: integer
* description: Number of cards per page (default 10)
* - in: query
* name: priority
* schema:
* type: string
* description: Filter by priority
* - in: query
* name: status
* schema:
* type: string
* description: Filter by card status
* - in: query
* name: stage
* schema:
* type: string
* description: Filter by card stage
* - in: query
* name: tags
* schema:
* type: string
* description: Comma-separated list of tags
* responses:
* 200:
* description: A paginated list of cards
* content:
* application/json:
* schema:
* type: object
* properties:
* pagination:
* type: object
* properties:
* current_page:
* type: integer
* per_page:
* type: integer
* total_pages:
* type: integer
* cards:
* type: array
* items:
* type: object
* properties:
* id:
* type: string
* title:
* type: string
* description:
* type: string
* status:
* type: string
* stage:
* type: string
* stage_funding:
* type: array
* items:
* type: object
* properties:
* stage:
* type: string
* funding_requested:
* type: string
* total_funding_requested:
* type: string
*/
app.get('/api/v1/cards', async (req, res) => {
res.set('Cache-Control', 'public, max-age=30');
const {
page = 1,
per_page = 10,
sort_by = 'last_updated',
sort_dir = 'desc'
} = req.query;
const limit = Math.min(parseInt(per_page, 10) || 10, 100);
const offset = (parseInt(page, 10) - 1) * limit;
const validSortBy = ['last_updated', 'priority', 'percent_funded', 'date'];
const validSortDir = ['asc', 'desc'];
const sortBySafe = validSortBy.includes(sort_by) ? sort_by : 'last_updated';
const sortDirSafe = validSortDir.includes(sort_dir) ? sort_dir : 'desc';
const conditions = [`visibility = 'PUBLIC'`];
const values = [];
let idx = 1;
if (req.query.priority) {
conditions.push(`priority = $${idx++}`);
values.push(req.query.priority);
}
if (req.query.status) {
conditions.push(`status = $${idx++}`);
values.push(req.query.status);
}
if (req.query.stage) {
conditions.push(`stage = $${idx++}`);
values.push(req.query.stage);
}
if (req.query.tags) {
conditions.push(`tags && string_to_array($${idx++}, ',')`);
values.push(req.query.tags);
}
const whereClause = conditions.join(' AND ');
try {
const totalResult = await pool.query(
`SELECT COUNT(*) FROM cards WHERE ${whereClause}`,
values
);
const totalRows = parseInt(totalResult.rows[0].count, 10);
const totalPages = Math.ceil(totalRows / limit);
const result = await pool.query(
`SELECT * FROM cards WHERE ${whereClause} ORDER BY ${sortBySafe} ${sortDirSafe} LIMIT $${idx++} OFFSET $${idx}`,
[...values, limit, offset]
);
const stageFundingResult = await pool.query(`
SELECT card_id, stage, funding_requested
FROM card_stage_funding
`);
const stageFundingMap = {};
for (const row of stageFundingResult.rows) {
if (!stageFundingMap[row.card_id]) {
stageFundingMap[row.card_id] = [];
}
stageFundingMap[row.card_id].push({
stage: row.stage,
funding_requested: row.funding_requested,
currency: row.currency || 'ZEC',
note: row.note || null
});
}
// Attach stage_funding and total_stage_funding_requested to each card
const cardsWithFunding = result.rows.map(card => {
const stageEntries = stageFundingMap[card.id] || [];
const totalRequested = stageEntries.reduce(
(sum, s) => sum + parseFloat(s.funding_requested || 0), 0
).toFixed(8);
return {
...card,
stage_funding: stageEntries,
total_funding_requested: totalRequested
};
});
res.json({
pagination: {
current_page: parseInt(page, 10),
per_page: limit,
total_pages: totalPages
},
cards: cardsWithFunding
});
} catch (err) {
console.error('DB query error:', err);
res.status(500).json({ error: 'Internal server error' });
}
});
/**
* @swagger
* /api/v1/cards/{id}:
* get:
* summary: Get details of a single card by ID
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: UUID of the card
* responses:
* 200:
* description: Card details
* content:
* application/json:
* schema:
* type: object
* properties:
* id:
* type: string
* title:
* type: string
* description:
* type: string
* creators:
* type: array
* items:
* type: string
* date:
* type: string
* format: date-time
* contributors:
* type: integer
* tags:
* type: array
* items:
* type: string
* priority:
* type: string
* funding_earned:
* type: string
* funding_spent:
* type: string
* funding_requested:
* type: string
* funding_received:
* type: string
* funding_available:
* type: string
* percent_funded:
* type: string
* visibility:
* type: string
* milestones:
* type: array
* items:
* type: object
* status:
* type: string
* stage:
* type: string
* created_by:
* type: string
* owned_by:
* type: string
* last_updated:
* type: string
* format: date-time
* wallet_addresses:
* type: array
* items:
* type: string
* view_keys:
* type: array
* items:
* type: string
* 404:
* description: Card not found
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* example: Not Found
*/
app.get('/api/v1/cards/:id', async (req, res) => {
res.set('Cache-Control', 'public, max-age=30');
try {
const result = await pool.query(
`SELECT * FROM cards WHERE id = $1 AND visibility = 'PUBLIC'`,
[req.params.id]
);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Not Found' });
}
const card = result.rows[0];
if (card.wallet_addresses && card.wallet_addresses.length > 0) {
try {
const walletInfo = await fetchWalletInfo(card.wallet_addresses);
res.json({ ...card, wallet_info: walletInfo });
} catch (err) {
console.error('Error fetching wallet info:', err);
// Send card data anyway, with a note about wallet info failure
res.json({ ...card, wallet_info_error: 'Failed to retrieve wallet info' });
}
} else {
res.json(card);
}
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Internal server error' });
}
});
/**
* @swagger
* /api/v1/funding-summary:
* get:
* summary: Get aggregated funding summary across all public cards
* responses:
* 200:
* description: Aggregated funding data
* content:
* application/json:
* schema:
* type: object
* properties:
* total_earned:
* type: string
* description: Total funding earned
* total_spent:
* type: string
* description: Total funding spent
* total_requested:
* type: string
* description: Total funding requested
* total_received:
* type: string
* description: Total funding received
* total_available:
* type: string
* description: Total funding available
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* example: Internal server error
*/
app.get('/api/v1/funding-summary', async (req, res) => {
res.set('Cache-Control', 'public, max-age=30');
try {
const result = await pool.query(`
SELECT
SUM(funding_earned)::text AS total_earned,
SUM(funding_spent)::text AS total_spent,
SUM(funding_requested)::text AS total_requested,
SUM(funding_received)::text AS total_received,
SUM(funding_available)::text AS total_available
FROM cards
WHERE visibility = 'PUBLIC'
`);
res.json(result.rows[0]);
} catch (err) {
console.error('Summary query error:', err);
res.status(500).json({ error: 'Internal server error' });
}
});
app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});