/
index.js
85 lines (77 loc) · 2.2 KB
/
index.js
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
import { Router } from 'express';
import {
TRANSACTION_QUERY_LIMIT,
} from '../../constant';
import {
userCollection as dbRef,
txCollection as txLogRef,
} from '../../util/firebase';
import { jwtAuth } from '../../middleware/jwt';
import { ValidationError } from '../../util/ValidationError';
import {
filterTxData,
checkAddressValid,
} from '../../util/ValidationHelper';
const web3Utils = require('web3-utils');
const router = Router();
router.get('/id/:id', async (req, res, next) => {
try {
const txHash = req.params.id;
const doc = await txLogRef.doc(txHash).get();
if (doc.exists) {
const payload = doc.data();
res.json(filterTxData(payload));
} else {
res.sendStatus(404);
}
} catch (err) {
next(err);
}
});
router.get('/history/addr/:addr', jwtAuth('read'), async (req, res, next) => {
try {
const { addr } = req.params;
if (!checkAddressValid(addr)) {
throw new ValidationError('Invalid address');
}
const query = await dbRef.where('wallet', '==', addr).get();
if (query.docs.length > 0) {
const [user] = query.docs;
if (req.user.user !== user.id) {
res.status(401).send('LOGIN_NEEDED');
return;
}
} else {
res.sendStatus(404);
return;
}
let { ts, count } = req.query;
ts = Number(ts);
if (!ts || Number.isNaN(ts)) ts = Date.now();
count = Number(count);
if (!count || Number.isNaN(count) || count > TRANSACTION_QUERY_LIMIT) {
count = TRANSACTION_QUERY_LIMIT;
}
const queryTo = txLogRef
.where('to', '==', web3Utils.toChecksumAddress(addr))
.orderBy('ts', 'desc')
.startAt(ts)
.limit(count)
.get();
const queryFrom = txLogRef
.where('from', '==', web3Utils.toChecksumAddress(addr))
.orderBy('ts', 'desc')
.startAt(ts)
.limit(count)
.get();
const [dataTo, dataFrom] = await Promise.all([queryTo, queryFrom]);
let results = dataTo.docs.concat(dataFrom.docs);
results = results.map(d => ({ id: d.id, ...filterTxData(d.data()) }));
results.sort((a, b) => (b.ts - a.ts));
results.splice(count);
res.json(results);
} catch (err) {
next(err);
}
});
export default router;